message stringlengths 2 48.6k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 318 108k | cluster float64 8 8 | __index_level_0__ int64 636 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,177 | 8 | 106,354 |
Tags: constructive algorithms, math
Correct Solution:
```
x=input()
s=input()
l=s.split(" ")
for i in l:
n=int(i)
if(n>14 and (n%14<=6 and n%14>=1)):
print("YES")
else:
print("NO")
``` | output | 1 | 53,177 | 8 | 106,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible. | instruction | 0 | 53,178 | 8 | 106,356 |
Tags: constructive algorithms, math
Correct Solution:
```
n = int(input())
l = list(map(int,input().split()))
for i in l:
q = i//7
w = i%7
if q%2 == 0 and q!=0 and w>0:
print('YES')
else:
print("NO")
``` | output | 1 | 53,178 | 8 | 106,357 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible.
Submitted Solution:
```
n=int(input())
a=list(map(int,input().split()))
for i in range (n):
if a[i]%14>0 and a[i]%14<7 and a[i]>14:
print("YES")
else:
print("NO")
``` | instruction | 0 | 53,180 | 8 | 106,360 |
Yes | output | 1 | 53,180 | 8 | 106,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible.
Submitted Solution:
```
import sys
import math
import re
import io
def solve2(n, k):
n += k
if n >= 21 and (n - 15) % 14 == 0:
return True
return False
def solve(n):
for i in range(1, 7):
if solve2(n, i):
return True
return False
def main():
n = int(input())
A = list(map(int, input().split()))
for a in A:
if solve(a):
print('YES')
else:
print('NO')
if __name__ == "__main__":
main()
``` | instruction | 0 | 53,185 | 8 | 106,370 |
No | output | 1 | 53,185 | 8 | 106,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bob is playing with 6-sided dice. A net of such standard cube is shown below.
<image>
He has an unlimited supply of these dice and wants to build a tower by stacking multiple dice on top of each other, while choosing the orientation of each dice. Then he counts the number of visible pips on the faces of the dice.
For example, the number of visible pips on the tower below is 29 — the number visible on the top is 1, from the south 5 and 3, from the west 4 and 2, from the north 2 and 4 and from the east 3 and 5.
<image>
The one at the bottom and the two sixes by which the dice are touching are not visible, so they are not counted towards total.
Bob also has t favourite integers x_i, and for every such integer his goal is to build such a tower that the number of visible pips is exactly x_i. For each of Bob's favourite integers determine whether it is possible to build a tower that has exactly that many visible pips.
Input
The first line contains a single integer t (1 ≤ t ≤ 1000) — the number of favourite integers of Bob.
The second line contains t space-separated integers x_i (1 ≤ x_i ≤ 10^{18}) — Bob's favourite integers.
Output
For each of Bob's favourite integers, output "YES" if it is possible to build the tower, or "NO" otherwise (quotes for clarity).
Example
Input
4
29 34 19 38
Output
YES
YES
YES
NO
Note
The first example is mentioned in the problem statement.
In the second example, one can build the tower by flipping the top dice from the previous tower.
In the third example, one can use a single die that has 5 on top.
The fourth example is impossible.
Submitted Solution:
```
n = int(input())
l = list(map(int, input().strip().split()))[:n]
for x in l:
x = x % 14
if x >= 1 and x <= 6:
print("YES")
else:
print("NO")
``` | instruction | 0 | 53,186 | 8 | 106,372 |
No | output | 1 | 53,186 | 8 | 106,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
Input
The first line contains two space-separated integers n and m <image>.
Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.
Consider all the chemicals numbered from 1 to n in some order.
Output
Print a single integer — the maximum possible danger.
Examples
Input
1 0
Output
1
Input
2 1
1 2
Output
2
Input
3 2
1 2
2 3
Output
4
Note
In the first sample, there's only one way to pour, and the danger won't increase.
In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.
In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring). | instruction | 0 | 53,422 | 8 | 106,844 |
Tags: dfs and similar, dsu, greedy
Correct Solution:
```
# 445B
__author__ = 'artyom'
read = lambda: map(int, input().split())
n, m = read()
graph = [set() for _ in range(n + 1)]
for __ in range(m):
x, y = read()
graph[x].add(y)
graph[y].add(x)
visited = set()
def dfs(start, counter):
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
counter *= 2
visited.add(vertex)
stack.extend(graph[vertex] - visited)
return counter // 2
res = 1
for v in range(1, n + 1):
if v not in visited:
res = dfs(v, res)
print(res)
``` | output | 1 | 53,422 | 8 | 106,845 |
Provide tags and a correct Python 3 solution for this coding contest problem.
DZY loves chemistry, and he enjoys mixing chemicals.
DZY has n chemicals, and m pairs of them will react. He wants to pour these chemicals into a test tube, and he needs to pour them in one by one, in any order.
Let's consider the danger of a test tube. Danger of an empty test tube is 1. And every time when DZY pours a chemical, if there are already one or more chemicals in the test tube that can react with it, the danger of the test tube will be multiplied by 2. Otherwise the danger remains as it is.
Find the maximum possible danger after pouring all the chemicals one by one in optimal order.
Input
The first line contains two space-separated integers n and m <image>.
Each of the next m lines contains two space-separated integers xi and yi (1 ≤ xi < yi ≤ n). These integers mean that the chemical xi will react with the chemical yi. Each pair of chemicals will appear at most once in the input.
Consider all the chemicals numbered from 1 to n in some order.
Output
Print a single integer — the maximum possible danger.
Examples
Input
1 0
Output
1
Input
2 1
1 2
Output
2
Input
3 2
1 2
2 3
Output
4
Note
In the first sample, there's only one way to pour, and the danger won't increase.
In the second sample, no matter we pour the 1st chemical first, or pour the 2nd chemical first, the answer is always 2.
In the third sample, there are four ways to achieve the maximum possible danger: 2-1-3, 2-3-1, 1-2-3 and 3-2-1 (that is the numbers of the chemicals in order of pouring). | instruction | 0 | 53,428 | 8 | 106,856 |
Tags: dfs and similar, dsu, greedy
Correct Solution:
```
def read_input():
global n, m, edge
n, m = map(int, input().split())
edge = []
for i in range(m):
u, v = map(int, input().split())
edge.append((u-1, v-1))
def init():
global lab
lab = [-1] * n
def find_set(u):
global lab
if lab[u] < 0:
return u
lab[u] = find_set(lab[u])
return lab[u]
def union(r,s):
global lab
lab[r] = s
def solve():
global edge, cc
init()
cc = n
for e in edge:
r = find_set(e[0])
s = find_set(e[1])
if r != s:
union(r, s)
cc -= 1
print(2**(n-cc))
if __name__ == '__main__':
read_input()
solve()
``` | output | 1 | 53,428 | 8 | 106,857 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
ans = []
for i in range(n):
j = b.index(a[i], i)
while i < j:
ans.append(f'{j} {j+1}')
b[j - 1], b[j] = b[j], b[j - 1]
j -= 1
print(len(ans))
print('\n'.join(ans))
``` | instruction | 0 | 53,478 | 8 | 106,956 |
Yes | output | 1 | 53,478 | 8 | 106,957 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
moves = []
for i in range(n):
for j in range(i, n):
if a[i] == b[j]:
for k in range(j-i):
moves.append((j+1-k, j-k))
b = [b[j]] + b[:j] + b[j+1:]
break
print(len(moves))
for move in moves:
print(f"{move[1]} {move[0]}")
``` | instruction | 0 | 53,479 | 8 | 106,958 |
Yes | output | 1 | 53,479 | 8 | 106,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
n=int(input())
l1=list(map(int,input().split()))
l2=list(map(int,input().split()))
ans=[]
i=0
while(i<n-1):
for j in range(i,n):
if l2[j]==l1[i]:
for k in range(j,i,-1):
ans.append([k,k+1])
l2[k],l2[k-1]=l2[k-1],l2[k]
break
i+=1
print(len(ans))
for i in ans:
print(*i)
``` | instruction | 0 | 53,480 | 8 | 106,960 |
Yes | output | 1 | 53,480 | 8 | 106,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
def sor(t):
f=[]
for i in range(n):
for j in range(n-i-1):
if t[j]>t[j+1]:
t[j],t[j+1] = t[j+1],t[j]
f.append([j+1,j+2])
return f
n= int(input())
a = list(map(int,input().split()))
b= list(map(int,input().split()))
if a==b:
print(0)
else:
A=sor(b)
A+=sor(a)[::-1]
print(len(A))
for j in A:
print(*j)
``` | instruction | 0 | 53,481 | 8 | 106,962 |
Yes | output | 1 | 53,481 | 8 | 106,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
num = 0
swap = []
for i in range(n - 1, -1, -1):
if b[i] != a[i]:
num += 1
right = a[i]
ind = b.index(right)
s = b[i]
b[i] = a[i]
b[ind] = s
li = [str(ind + 1),str(i + 1)]
swap.append(li)
print(num)
if num != 0:
for i in range(num):
print(' '.join(swap[i]))
``` | instruction | 0 | 53,482 | 8 | 106,964 |
No | output | 1 | 53,482 | 8 | 106,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
n = int(input())
*a, = map(int, input().split())
*b, = map(int, input().split())
ans, s, k = [], 0, 0
while a:
x = a.index(b[k])
a.remove(b[k])
ans.append((x + k + 1, k + 1))
s += x
k += 1
print(s)
for i in ans:
for j in range(i[0], i[1], -1):
print(j, j - 1)
``` | instruction | 0 | 53,483 | 8 | 106,966 |
No | output | 1 | 53,483 | 8 | 106,967 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
import re
import sys
exit=sys.exit
from bisect import bisect_left as bsl,bisect_right as bsr
from collections import Counter,defaultdict as ddict,deque
from functools import lru_cache
cache=lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum=enumerate
ri=lambda:int(rln())
ris=lambda:list(map(int,rfs()))
rln=sys.stdin.readline
rl=lambda:rln().rstrip('\n')
rfs=lambda:rln().split()
cat=''.join
catn='\n'.join
mod=1000000007
d4=[(0,-1),(1,0),(0,1),(-1,0)]
d8=[(-1,-1),(0,-1),(1,-1),(-1,0),(1,0),(-1,1),(0,1),(1,1)]
########################################################################
def solve():
n,a,b=ri(),ris(),ris()
ans=[]
num_swaps=0
for i in range(n):
j=i
while a[i]!=b[j]:
j+=1
swaps=[]
while i<j:
b[j-1],b[j]=b[j],b[j-1]
swaps.append((j,j+1))
j-=1
if swaps:
num_swaps+=len(swaps)
ans.append(swaps)
print(num_swaps)
for swaps in ans:
for i,j in reversed(swaps):
print(i,j)
solve()
``` | instruction | 0 | 53,484 | 8 | 106,968 |
No | output | 1 | 53,484 | 8 | 106,969 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasya is a school PE teacher. Unlike other PE teachers, Vasya doesn't like it when the students stand in line according to their height. Instead, he demands that the children stand in the following order: a1, a2, ..., an, where ai is the height of the i-th student in the line and n is the number of students in the line. The children find it hard to keep in mind this strange arrangement, and today they formed the line in the following order: b1, b2, ..., bn, which upset Vasya immensely. Now Vasya wants to rearrange the children so that the resulting order is like this: a1, a2, ..., an. During each move Vasya can swap two people who stand next to each other in the line. Help Vasya, find the sequence of swaps leading to the arrangement Vasya needs. It is not required to minimize the number of moves.
Input
The first line contains an integer n (1 ≤ n ≤ 300) which is the number of students. The second line contains n space-separated integers ai (1 ≤ ai ≤ 109) which represent the height of the student occupying the i-th place must possess. The third line contains n space-separated integers bi (1 ≤ bi ≤ 109) which represent the height of the student occupying the i-th place in the initial arrangement. It is possible that some students possess similar heights. It is guaranteed that it is possible to arrange the children in the required order, i.e. a and b coincide as multisets.
Output
In the first line print an integer k (0 ≤ k ≤ 106) which is the number of moves. It is not required to minimize k but it must not exceed 106. Then print k lines each containing two space-separated integers. Line pi, pi + 1 (1 ≤ pi ≤ n - 1) means that Vasya should swap students occupying places pi and pi + 1.
Examples
Input
4
1 2 3 2
3 2 1 2
Output
4
2 3
1 2
3 4
2 3
Input
2
1 100500
1 100500
Output
0
Submitted Solution:
```
n = int(input())
target = list(map(int,input().split()))
got = list(map(int,input().split()))
swaps = []
for i in range(n-1,-1,-1):
for j in range(i+1):
if got[j] == target[i] and j != i:
swaps.append((j,j+1))
got[j],got[j+1] = got[j+1],got[j]
print(len(swaps))
for i in swaps:
print(*i)
``` | instruction | 0 | 53,485 | 8 | 106,970 |
No | output | 1 | 53,485 | 8 | 106,971 |
Provide tags and a correct Python 3 solution for this coding contest problem.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3 | instruction | 0 | 53,486 | 8 | 106,972 |
Tags: dp
Correct Solution:
```
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if a==b:
continue
if (e[a] and e[a]!=b) or (e[b] and e[b]!=a):
ok = 0
e[a], e[b] = b,a
if c=="<":
a,b,c = b,a,">"
if c==">":
l[a].append(b)
if c=="<=":
a,b,c = b,a,">="
if c==">=":
le[a].append(b)
def check(i, j, a, b):
if e[a] and e[a]!=a and e[a]!=b:
return 0
for x in l[a]:
if x>i and x<j:
return 0
for x in le[a]:
if x>i and x<j and x!=a and x!=b:
return 0
return 1
dp = [[0]*n for i in range(n)]
dp[0][n-1] = 1
ans = 0
for i in range(n):
for j in range(n-1,i,-1):
if i+1==j:
ans+=dp[i][j]
elif ((i+j)%2)==1:
if check(i,j,i+1,i+2) and check(i,j,i+2,i+1):
dp[i+2][j]+=dp[i][j]
if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2):
dp[i][j-2]+=dp[i][j]
if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1):
dp[i+1][j-1]+=dp[i][j]
print(ans if ok else 0)
``` | output | 1 | 53,486 | 8 | 106,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3 | instruction | 0 | 53,487 | 8 | 106,974 |
Tags: dp
Correct Solution:
```
def check(l, r, a, b):
if a < 0 or b >= 2 * N:
return 0
def val(p):
if p in [a, b]: return '0'
if l <= p and p < r: return '1'
return '-1'
for i in range(K):
x, y = val(A[i]), val(C[i])
if A[i] in [a, b] or C[i] in [a, b]:
if not eval(x + B[i] + y):
return 0
return 1
N, K = map(int, input().split())
tmp = [input().split() for i in range(K)]
try: A, B, C = zip(*tmp)
except: A, B, C = [], [], []
A = [int(x) - 1 for x in A]
B = ['==' if x is '=' else x for x in B]
C = [int(x) - 1 for x in C]
dp = []
for i in range(N + 1):
dp.append([0] * (2 * N + 1))
dp[N][0] = 1
for i in range(N, 0, -1):
for j in range(0, 2 * (N - i) + 3):
d, k = 0, j + 2 * i - 2
if check(j, k, j - 2, j - 1): d += dp[i][j - 2]
if check(j, k, j - 1, k): d += dp[i][j - 1]
if check(j, k, k, k + 1): d += dp[i][j]
dp[i - 1][j] = d
print(sum(dp[0]) // 3)
``` | output | 1 | 53,487 | 8 | 106,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3 | instruction | 0 | 53,488 | 8 | 106,976 |
Tags: dp
Correct Solution:
```
import sys
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
n, k = map(int, input().split())
dp = [[0] * 2 * n for i in range(2 * n)]
require = list()
inf = int(1e5)
order = [inf] * 2 * n
for i in range(k):
require.append(input().split())
require[i][0] = int(require[i][0]) - 1
if require[i][1] == '=':
require[i][1] = '=='
require[i][2] = int(require[i][2]) - 1
def Solve(left, right, h):
global dp, require, order
for element in require:
first = order[element[0]]
second = order[element[2]]
string = str(first) + element[1] + str(second)
if first == second == inf and left + 1 != right:
continue
if eval(string) == False:
return 0
if dp[left][right] != 0:
return dp[left][right]
if left + 1 == right:
dp[left][right] = 1
return 1
order[left] = h
order[left + 1] = h
dp[left][right] = Solve(left + 2, right, h + 1)
order[left + 1] = inf
order[right] = h
dp[left][right] += Solve(left + 1, right - 1, h + 1)
order[left] = inf
order[right - 1] = h
dp[left][right] += Solve(left, right - 2, h + 1)
order[right - 1] = inf
order[right] = inf
return dp[left][right]
print(Solve(0, 2 * n - 1, 0))
``` | output | 1 | 53,488 | 8 | 106,977 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3
Submitted Solution:
```
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if a==b:
continue
if e[a] or e[b]:
ok = 0
e[a], e[b] = b,a
if c=="<":
a,b,c = b,a,">"
if c==">":
l[a].append(b)
if c=="<=":
a,b,c = b,a,">="
if c==">=":
le[a].append(b)
def check(i, j, a, b):
if e[a] and e[a]!=a and e[a]!=b:
return 0
for x in l[a]:
if x>i and x<j:
return 0
for x in le[a]:
if x>i and x<j and x!=a and x!=b:
return 0
return 1
dp = [[0]*n for i in range(n)]
dp[0][n-1] = 1
ans = 0
for i in range(n):
for j in range(n-1,i,-1):
if i+1==j:
ans+=dp[i][j]
elif ((i+j)%2)==1:
if check(i,j,i+1,i+2) and check(i,j,i+2,i+1):
dp[i+2][j]+=dp[i][j]
if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2):
dp[i][j-2]+=dp[i][j]
if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1):
dp[i+1][j-1]+=dp[i][j]
print(ans if ok else 0)
``` | instruction | 0 | 53,489 | 8 | 106,978 |
No | output | 1 | 53,489 | 8 | 106,979 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3
Submitted Solution:
```
n,k = map(int,input().split())
n*=2
n+=2
l,le,e = [[] for i in range(n)],[[] for i in range(n)],[0]*n
ok = 1
for i in range(k):
a,c,b = input().split()
a,b = int(a), int(b)
if c=="=":
if e[a] or e[b]:
ok = 0
e[a], e[b] = b,a
if c=="<":
a,b,c = b,a,">"
if c==">":
l[a].append(b)
if c=="<=":
a,b,c = b,a,">="
if c==">=":
le[a].append(b)
def check(i, j, a, b):
if e[a] and e[a]!=a and e[a]!=b:
return 0
for x in l[a]:
if x>i and x<j:
return 0
for x in le[a]:
if x>i and x<j and x!=a and x!=b:
return 0
return 1
dp = [[0]*n for i in range(n)]
dp[0][n-1] = 1
ans = 0
for i in range(n):
for j in range(n-1,i,-1):
if i+1==j:
ans+=dp[i][j]
elif ((i+j)%2)==1:
if check(i,j,i+1,i+2) and check(i,j,i+2,i+1):
dp[i+2][j]+=dp[i][j]
if i+3<j and check(i,j,j-2,j-1) and check(i,j,j-1,j-2):
dp[i][j-2]+=dp[i][j]
if i+3<j and check(i,j,i+1,j-1) and check(i,j,j-1,i+1):
dp[i+1][j-1]+=dp[i][j]
print(ans if ok else 0)
``` | instruction | 0 | 53,490 | 8 | 106,980 |
No | output | 1 | 53,490 | 8 | 106,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3
Submitted Solution:
```
import sys
#sys.stdin = open('input.txt', 'r')
#sys.stdout = open('output.txt', 'w')
n, k = map(int, input().split())
dp = [[-1] * 2 * n for i in range(2 * n)]
require = list()
inf = int(1e5)
order = [inf] * 2 * n
for i in range(k):
require.append(input().split())
require[i][0] = int(require[i][0]) - 1
if require[i][1] == '=':
require[i][1] = '=='
require[i][2] = int(require[i][2]) - 1
def Solve(left, right, h):
global dp, require, order
if dp[left][right] != -1:
return dp[left][right]
for element in require:
first = order[element[0]]
second = order[element[2]]
string = str(first) + element[1] + str(second)
if first == second == inf and left + 1 != right:
continue
if eval(string) == False:
dp[left][right] = 0
return 0
if left + 1 == right:
dp[left][right] = 1
return 1
dp[left][right] = 0
order[left] = h
order[left + 1] = h
dp[left][right] = Solve(left + 2, right, h + 1)
order[left + 1] = inf
order[right] = h
dp[left][right] += Solve(left + 1, right - 1, h + 1)
order[left] = inf
order[right - 1] = h
dp[left][right] += Solve(left, right - 2, h + 1)
order[right - 1] = inf
order[right] = inf
return dp[left][right]
print(Solve(0, 2 * n - 1, 0))
``` | instruction | 0 | 53,491 | 8 | 106,982 |
No | output | 1 | 53,491 | 8 | 106,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
King of Berland Berl IV has recently died. Hail Berl V! As a sign of the highest achievements of the deceased king the new king decided to build a mausoleum with Berl IV's body on the main square of the capital.
The mausoleum will be constructed from 2n blocks, each of them has the shape of a cuboid. Each block has the bottom base of a 1 × 1 meter square. Among the blocks, exactly two of them have the height of one meter, exactly two have the height of two meters, ..., exactly two have the height of n meters.
The blocks are arranged in a row without spacing one after the other. Of course, not every arrangement of blocks has the form of a mausoleum. In order to make the given arrangement in the form of the mausoleum, it is necessary that when you pass along the mausoleum, from one end to the other, the heights of the blocks first were non-decreasing (i.e., increasing or remained the same), and then — non-increasing (decrease or remained unchanged). It is possible that any of these two areas will be omitted. For example, the following sequences of block height meet this requirement:
* [1, 2, 2, 3, 4, 4, 3, 1];
* [1, 1];
* [2, 2, 1, 1];
* [1, 2, 3, 3, 2, 1].
Suddenly, k more requirements appeared. Each of the requirements has the form: "h[xi] signi h[yi]", where h[t] is the height of the t-th block, and a signi is one of the five possible signs: '=' (equals), '<' (less than), '>' (more than), '<=' (less than or equals), '>=' (more than or equals). Thus, each of the k additional requirements is given by a pair of indexes xi, yi (1 ≤ xi, yi ≤ 2n) and sign signi.
Find the number of possible ways to rearrange the blocks so that both the requirement about the shape of the mausoleum (see paragraph 3) and the k additional requirements were met.
Input
The first line of the input contains integers n and k (1 ≤ n ≤ 35, 0 ≤ k ≤ 100) — the number of pairs of blocks and the number of additional requirements.
Next k lines contain listed additional requirements, one per line in the format "xi signi yi" (1 ≤ xi, yi ≤ 2n), and the sign is on of the list of the five possible signs.
Output
Print the sought number of ways.
Examples
Input
3 0
Output
9
Input
3 1
2 > 3
Output
1
Input
4 1
3 = 6
Output
3
Submitted Solution:
```
def check(l, r, a, b):
if a < 0 or b >= 2 * N:
return 0
def val(p):
if p in [a, b]: return '0'
if l <= p and p < r: return '1'
return '-1'
for i in range(K):
x, y = val(A[i]), val(C[i])
if A[i] in [a, b] or C[i] in [a, b]:
if not eval(x + B[i] + y):
return 0
return 1
N, K = map(int, input().split())
tmp = [input().split() for i in range(K)]
try: A, B, C = zip(*tmp)
except: A, B, C = [], [], []
A = list(map(int, A))
C = list(map(int, C))
dp = []
for i in range(N + 1):
dp.append([0] * (2 * N + 1))
dp[N][0] = 1
for i in range(N, 0, -1):
for j in range(0, 2 * (N - i) + 3):
d, k = 0, j + 2 * i - 2
if check(j, k, j - 2, j - 1): d += dp[i][j - 2]
if check(j, k, j - 1, k): d += dp[i][j - 1]
if check(j, k, k, k + 1): d += dp[i][j]
dp[i - 1][j] = d
print(sum(dp[0]) // 3)
``` | instruction | 0 | 53,492 | 8 | 106,984 |
No | output | 1 | 53,492 | 8 | 106,985 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
Input
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.
The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left.
Output
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
Examples
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
Note
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
<image> | instruction | 0 | 53,511 | 8 | 107,022 |
Tags: combinatorics, dp, number theory
Correct Solution:
```
mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
ans = x = 0
for i in range(n):
ans += h[i] + min(h[i], h[i - 1]) * x
if i < n - 1:
x *= min(h[i - 1], h[i], h[i + 1])
x += min(h[i], h[i + 1])
ans %= mod
x %= mod
print(ans)
``` | output | 1 | 53,511 | 8 | 107,023 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
Input
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.
The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left.
Output
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
Examples
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
Note
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
<image>
Submitted Solution:
```
n = int(input())
h = list(map(int, input().split()))
pk = 0
k = h[0] - 1
for i in range(1, n):
if h[i - 1] <= h[i]:
pk = k
k = k * h[i - 1] + h[i] - 1
else:
acc = k
k = (h[i] - 1) + pk * h[i] * (h[i] - 1) + k - 1
pk = acc
k %= 1000000007
print(k)
``` | instruction | 0 | 53,512 | 8 | 107,024 |
No | output | 1 | 53,512 | 8 | 107,025 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Long ago, Vasily built a good fence at his country house. Vasily calls a fence good, if it is a series of n consecutively fastened vertical boards of centimeter width, the height of each in centimeters is a positive integer. The house owner remembers that the height of the i-th board to the left is hi.
Today Vasily decided to change the design of the fence he had built, by cutting his top connected part so that the fence remained good. The cut part should consist of only the upper parts of the boards, while the adjacent parts must be interconnected (share a non-zero length before cutting out of the fence).
You, as Vasily's curious neighbor, will count the number of possible ways to cut exactly one part as is described above. Two ways to cut a part are called distinct, if for the remaining fences there is such i, that the height of the i-th boards vary.
As Vasily's fence can be very high and long, get the remainder after dividing the required number of ways by 1 000 000 007 (109 + 7).
Input
The first line contains integer n (1 ≤ n ≤ 1 000 000) — the number of boards in Vasily's fence.
The second line contains n space-separated numbers h1, h2, ..., hn (1 ≤ hi ≤ 109), where hi equals the height of the i-th board to the left.
Output
Print the remainder after dividing r by 1 000 000 007, where r is the number of ways to cut exactly one connected part so that the part consisted of the upper parts of the boards and the remaining fence was good.
Examples
Input
2
1 1
Output
0
Input
3
3 4 2
Output
13
Note
From the fence from the first example it is impossible to cut exactly one piece so as the remaining fence was good.
All the possible variants of the resulting fence from the second sample look as follows (the grey shows the cut out part):
<image>
Submitted Solution:
```
mod = 10 ** 9 + 7
n = int(input())
h = list(map(lambda x: int(x) - 1, input().split()))
dp = [0] * n
dp2 = [0] * n
dp[0] = h[0]
if n > 1 and h[0] > h[1]:
dp2[0] = h[0] - h[1]
for i in range(1, n):
if h[i] >= h[i - 1]:
dp[i] = (h[i] + dp[i - 1] * h[i - 1]) % mod
else:
dp[i] = (h[i] * (1 + dp[i - 1] - dp2[i - 1])) % mod
if i < n - 1 and h[i] > h[i + 1]:
if h[i] >= h[i - 1]:
dp2[i] = h[i] - h[i + 1]
if h[i - 1] > h[i + 1]:
dp2[i] += (h[i - 1] - h[i + 1]) * dp[i - 1]
else:
dp2[i] = (h[i] - h[i + 1]) * (dp[i - 1] - dp2[i - 1])
dp2[i] %= mod
ans = sum(dp) % mod
print(ans)
``` | instruction | 0 | 53,513 | 8 | 107,026 |
No | output | 1 | 53,513 | 8 | 107,027 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,093 | 8 | 108,186 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
from collections import defaultdict
from random import randint
itl = lambda: list(map(int, input().strip().split()))
class Problem:
def read(self):
# self.N = 100000
# self.A, self.R, self.M = [randint(1, 10000) for _ in range(3)]
# self.pillars = [randint(0, 1000000000) for _ in range(self.N)]
self.N, self.A, self.R, self.M = itl()
self.pillars = itl()
self.lo = min(self.pillars)
self.hi = max(self.pillars)
def solve(self):
lo = self.lo
hi = self.hi
while lo <= hi:
mid = (lo + hi) >> 1
left = self.cost(mid - 1)
center = self.cost(mid)
right = self.cost(mid + 1)
if center < right and center < left:
return center
assert left >= center >= right or left <= center <= right
if right > left:
hi = mid - 1
else:
lo = mid + 1
return self.cost(lo)
def cost(self, target):
below = 0
above = 0
for p in self.pillars:
if p < target:
below += target - p
elif p > target:
above += p - target
option1 = self.A * below + self.R * above
option2 = self.M * min(below, above) + abs(below - above) * (self.A if below > above else self.R)
return min(option1, option2)
def bruteforce(self):
ans = float('inf')
for target in range(min(self.pillars), max(self.pillars) + 1):
cost = self.cost(target)
print(target, cost)
ans = min(ans, cost)
return ans
if __name__ == '__main__':
P = Problem()
P.read()
# print(P.bruteforce())
print(P.solve())
``` | output | 1 | 54,093 | 8 | 108,187 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,094 | 8 | 108,188 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
# https://codeforces.com/contest/1355/problem/E
import bisect
def func(val):
cost = 0
toAdd,toRemove = 0,0
lessEqual = bisect.bisect_right(arr,val)
greater = n - lessEqual
toAdd = (lessEqual * val) - dp[lessEqual]
toRemove = (total - dp[lessEqual]) - (greater * val)
if toRemove >= toAdd:
confirmRemove = toRemove - toAdd
toRemove = toAdd
cost += (confirmRemove * R)
cost += min(toAdd * A + R * toRemove, toAdd * M)
else:
confirmAdd = toAdd - toRemove
cost += (confirmAdd * A)
toAdd = toRemove
cost += min(toAdd * A + R * toRemove, toAdd * M)
return cost
n, A, R, M = map(int, input().split())
arr = sorted([int(x) for x in input().split()])
dp = [0]
for item in arr:
dp.append(dp[-1]+item)
total = sum(arr)
ans = R * total
avg = total//n
heightsToCheck = arr + [avg,avg+1]
cost = min([func(h) for h in heightsToCheck])
print(min(ans,cost))
``` | output | 1 | 54,094 | 8 | 108,189 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,095 | 8 | 108,190 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
import sys
input = sys.stdin.readline
from bisect import *
N, A, R, M = map(int, input().split())
M = min(M, A+R)
h = list(map(int, input().split()))
h.sort()
acc = [0]*(N+1)
for i in range(N):
acc[i+1] = acc[i]+h[i]
S = sum(h)
bs = h+[S//N-1, S//N, S//N+1]
ans = 10**18
for b in bs:
i = bisect_left(h, b)
P = i*b-acc[i]
Q = acc[N]-acc[i]-(N-i)*b
if P>=Q:
ans = min(ans, M*Q+(P-Q)*A)
else:
ans = min(ans, M*P+(Q-P)*R)
print(ans)
``` | output | 1 | 54,095 | 8 | 108,191 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,096 | 8 | 108,192 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
n,a,r,m = li()
l = sorted(li())
cnt1 = [0]
for i in l:cnt1.append(cnt1[-1] + i)
# cnt1 = cnt1[1:]
cnt2 = [0]
for i in l[::-1]:cnt2.append(cnt2[-1] + i)
# cnt2 = cnt2[1:]
cnt2 = cnt2[::-1]
def give(s):
leftind = bl(l,s)
rightind = br(l,s)
a = leftind*s - cnt1[leftind]
b = cnt2[rightind] - (len(l) - rightind)*s
return [a,b]
def cost(s,b):
temp = min(b,s)
return temp*m + (b - temp)*r + (s - temp)*a
def binary():
ans = float('inf')
left = 0
right = 10**18
while left <= right:
mid = (left + right) >> 1
s1,b1 = give(mid)
s2,b2 = give(mid + 1)
if cost(s1,b1) < cost(s2,b2):
ans = min(ans,cost(s1,b1))
right = mid - 1
else:
ans = min(ans,cost(s2,b2))
left = mid + 1
return ans
m = min(m,a + r)
print(binary())
``` | output | 1 | 54,096 | 8 | 108,193 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,097 | 8 | 108,194 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
n,a,r,m=map(int,input().split())
if m>a+r:
m=a+r
h=[int(i) for i in input().split()]
def checker(height):
above,below=0,0
for i in h:
if i>height:
above+=(i-height)
elif i<height:
below+=height-i
if below>above:
return(above*m+(below-above)*a)
elif below<above:
return(below*m+(above-below)*r)
return(below*m)
lo,hi=0,1000000000
while lo<hi:
mid=(lo+(hi-1))//2
mx=checker(mid)
mx1=checker(mid+1)
#print(mx,mx1,hi,lo,mid)
if mx<mx1:
hi=mid
else:
lo=mid+1
print(min(mx1,mx))
``` | output | 1 | 54,097 | 8 | 108,195 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,098 | 8 | 108,196 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
import bisect
N, A, R, M = map(int, input().split())
aa = sorted(map(int, input().split()))
raa = [0]
for a in aa:
raa.append(raa[-1] + a)
ans = 10 ** 15
# a に揃える時のコスト
def calc(a):
i = bisect.bisect_right(aa, a)
add_n = a * i - raa[i]
rem_n = (raa[-1] - raa[i]) - (a * (N - i))
# move する
if rem_n < add_n:
tmp1 = rem_n * M + (add_n - rem_n) * A
else:
tmp1 = add_n * M + (rem_n - add_n) * R
# move しない
tmp2 = rem_n * R + add_n * A
return min(tmp1, tmp2)
ans = min([calc(a) for a in set(aa)])
tmp = sum(aa) // N
ans = min([ans, calc(tmp), calc(tmp + 1)])
print(ans)
``` | output | 1 | 54,098 | 8 | 108,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,099 | 8 | 108,198 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
import sys,bisect
input = sys.stdin.buffer.readline
n,A,R,M = map(int,input().split())
h = list(map(int,input().split()))
h.sort()
b = []
tmp = 0
for e in h:
tmp += e
b.append(tmp)
def f(x):
k = bisect.bisect_left(h,x)
if k == 0:
plus = 0
mns = b[-1]-n*x
else:
plus = k*x - b[k-1]
mns = (b[-1]-b[k-1]) - (n-k)*x
if mns <= plus:
return mns*M + (plus-mns)*A
return plus*M + (mns-plus)*R
if A+R <= M:
bef,aft = 0,sum(h)
res = aft*R
for i in range(n):
res = min(res,(i*h[i]-bef)*A + (aft-(n-i)*h[i])*R)
bef += h[i]
aft -= h[i]
print(res)
else:
high = 10**9
low = 0
while high - low > 5:
mid_left = high//3+low*2//3
mid_right = high*2//3+low//3
if f(mid_left) >= f(mid_right):
low = mid_left
else:
high = mid_right
res = b[-1]*R
for i in range(low,high+1):
res = min(res,f(i))
print(res)
``` | output | 1 | 54,099 | 8 | 108,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,100 | 8 | 108,200 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
#!/usr/bin/env python3
import io
import os
from bisect import bisect
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
def get_str():
return input().decode().strip()
def rint():
return map(int, input().split())
def oint():
return int(input())
def find_lu_value(th):
hi = bisect(h, th) - 1
lv = th * (hi + 1) - ps[hi]
uv = (ps[n - 1] - ps[hi]) - (n - 1 - hi) * th
return lv, uv
def calc_cost(th):
cost = 0
l, u = find_lu_value(th)
if l > u:
cost += u * m + (l - u) * a
else:
cost += l * m + (u - l) * r
return cost
def calc_prefixsum(h):
ps = [h[0]]
for i in range(1, n):
ps.append(h[i] + ps[-1])
return ps
n, a, r, m = rint()
h = list(rint())
m = min(m, a + r)
h.sort()
ps = calc_prefixsum(h)
ans = 10**99
lv = h[0]
rv = h[-1]
ans = min(ans, calc_cost(lv), calc_cost(rv))
while rv-lv > 1:
ll = (rv-lv)//3 + lv
rr = (rv-lv)//3*2 + lv
lc = calc_cost(ll)
rc = calc_cost(rr)
if lc > rc:
lv = ll
else:
rv = rr
ans = min(ans, lc, rc)
print(ans)
``` | output | 1 | 54,100 | 8 | 108,201 |
Provide tags and a correct Python 2 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,101 | 8 | 108,202 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
# input = sys.stdin.read().split('\n')[::-1].pop
# out = __pypy__.builders.StringBuilder()
def give_it_all():
if sys.version_info[0] < 3:
os.write(1,out.build())
else:
os.write(1,out.build().encode())
def result_out(*args):
for arg in args:
out.append(arg)
out.append(' ')
out.append('\n')
# Built In GDC is much slower on python
def gcd(x, y):
""" greatest common divisor of x and y """
while y:
x, y = y, x % y
return x
def input1(type=int):
return type(input())
def input2(type=int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type=int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type=int):
return list(map(type, input().split()))
def input_string():
s = input()
return list(s)
def solve(h, arr, a, r, m):
rgt = len(arr) - 1
while rgt >= 0 and arr[rgt] <= h:
rgt -= 1
i = 0
res = 0
while i < len(arr):
if arr[i] < h:
if rgt != -1 and m <= a + r:
nw = min(h - arr[i], arr[rgt] - h)
res += nw * m
arr[rgt] -= nw
arr[i] += nw
if arr[rgt] == h:
rgt -= 1
else:
res += (h - arr[i]) * a
arr[i] = h
elif arr[i] > h:
res += (arr[i] - h) * r
arr[i] = h
while rgt >= 0 and arr[rgt] <= h:
rgt -= 1
if arr[i] == h:
i += 1
# print('f', h, res)
return res
def main():
[n, a, r, m] = input_array()
arr = input_array()
arr.sort()
low = -1
high = max(arr)
while high - low > 1:
mid = (high + low) >> 1
# print('lmh', low, mid, high)
if solve(mid, arr[:], a, r, m) < solve(mid+1, arr[:], a, r, m):
high = mid
else:
low = mid
print(solve(low + 1, arr[:], a, r, m))
pass
if __name__ == '__main__':
main()
``` | output | 1 | 54,101 | 8 | 108,203 |
Provide tags and a correct Python 2 solution for this coding contest problem.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3 | instruction | 0 | 54,102 | 8 | 108,204 |
Tags: binary search, greedy, math, sortings, ternary search
Correct Solution:
```
""" Python 3 compatibility tools. """
from __future__ import division, print_function
import itertools
import sys
if sys.version_info[0] < 3:
input = raw_input
range = xrange
filter = itertools.ifilter
map = itertools.imap
zip = itertools.izip
input = sys.stdin.read().split('\n')[::-1].pop
# out = __pypy__.builders.StringBuilder()
def give_it_all():
if sys.version_info[0] < 3:
os.write(1,out.build())
else:
os.write(1,out.build().encode())
def result_out(*args):
for arg in args:
out.append(arg)
out.append(' ')
out.append('\n')
# Built In GDC is much slower on python
def gcd(x, y):
""" greatest common divisor of x and y """
while y:
x, y = y, x % y
return x
def input1(type=int):
return type(input())
def input2(type=int):
[a, b] = list(map(type, input().split()))
return a, b
def input3(type=int):
[a, b, c] = list(map(type, input().split()))
return a, b, c
def input_array(type=int):
return list(map(type, input().split()))
def input_string():
s = input()
return list(s)
def solve(h, arr, a, r, m):
rgt = len(arr) - 1
while rgt >= 0 and arr[rgt] <= h:
rgt -= 1
i = 0
res = 0
while i < len(arr):
if arr[i] < h:
if rgt != -1 and m <= a + r:
nw = min(h - arr[i], arr[rgt] - h)
res += nw * m
arr[rgt] -= nw
arr[i] += nw
if arr[rgt] == h:
rgt -= 1
else:
res += (h - arr[i]) * a
arr[i] = h
elif arr[i] > h:
res += (arr[i] - h) * r
arr[i] = h
while rgt >= 0 and arr[rgt] <= h:
rgt -= 1
if arr[i] == h:
i += 1
# print('f', h, res)
return res
def main():
[n, a, r, m] = input_array()
arr = input_array()
arr.sort()
low = -1
high = max(arr)
while high - low > 1:
mid = (high + low) >> 1
# print('lmh', low, mid, high)
if solve(mid, arr[:], a, r, m) < solve(mid+1, arr[:], a, r, m):
high = mid
else:
low = mid
print(solve(low + 1, arr[:], a, r, m))
pass
if __name__ == '__main__':
main()
``` | output | 1 | 54,102 | 8 | 108,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
# import sys
# input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
n,a,r,m = li()
l = sorted(li())
cnt1 = [0]
for i in l:cnt1.append(cnt1[-1] + i)
cnt2 = [0]
for i in l[::-1]:cnt2.append(cnt2[-1] + i)
cnt2 = cnt2[::-1]
def give(s):
leftind = bl(l,s)
rightind = br(l,s)
a = leftind*s - cnt1[leftind]
b = cnt2[rightind] - (len(l) - rightind)*s
return [a,b]
def cost(s,b):
temp = min(b,s)
return temp*m + (b - temp)*r + (s - temp)*a
def binary():
ans = float('inf')
left = 0
right = max(l)
while left <= right:
mid = (left + right) >> 1
s1,b1 = give(mid)
s2,b2 = give(mid + 1)
if cost(s1,b1) < cost(s2,b2):
ans = min(ans,cost(s1,b1))
right = mid - 1
else:
ans = min(ans,cost(s2,b2))
left = mid + 1
return ans
m = min(m,a + r)
print(binary())
``` | instruction | 0 | 54,103 | 8 | 108,206 |
Yes | output | 1 | 54,103 | 8 | 108,207 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
import sys
import math
import itertools
from collections import deque
n,a,r,m=map(int,input().split())
m=min(m,a+r)
h=list(map(int,input().split()))
low=0
high=0
def cost(he):
add=0
remov=0
for num in h:
if(num<he):
add+=he-num
else:
remov+=num-he
need=abs(add-remov)
if(add>remov):
need*=a
else:
need*=r
return min(add,remov)*m+need
for num in h:
high=max(high,num)
while(low<high):
mid=(low+high)>>1
mid2=mid+1
val1=cost(mid)
val2=cost(mid2)
if(val1<=val2):
high=mid
else:
low=mid+1
ans=cost(low)
print(ans)
``` | instruction | 0 | 54,104 | 8 | 108,208 |
Yes | output | 1 | 54,104 | 8 | 108,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
from itertools import accumulate
n,a,r,m = map(int,input().split())
m = min(a+r,m)
ls = list(map(int,input().split()))
ls.sort()
acc = [0]+list(accumulate(ls))
ansls = []
sm = acc[-1]
less = sm//n
more = less+1
flg = 0
for i in range(n+1):
if i == 0:
minus = 0
plus = acc[n]
else:
minus = ls[i-1]*(i-1)-acc[i-1]
plus = acc[n]-acc[i]-ls[i-1]*(n-i)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
if i > 0 and less < ls[i-1] and not flg:
flg = 1
minus = less*(i-1)-acc[i-1]
plus = acc[n]-acc[i-1]-less*(n-i+1)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
if i > 0 and more < ls[i-1] and flg == 1:
flg = 2
minus = more*(i-1)-acc[i-1]
plus = acc[n]-acc[i-1]-more*(n-i+1)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
print(min(ansls))
``` | instruction | 0 | 54,105 | 8 | 108,210 |
Yes | output | 1 | 54,105 | 8 | 108,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
def f(h):
numofh=0
numofl=0
for i in li:
if(i<h):
numofl+=(h-i)
else:
numofh+=(i-h)
if(numofh>numofl):
return m*(numofl)+(numofh-numofl)*r
else:
return m*(numofh)+(numofl-numofh)*a
def binary_search(low,high):
if(low>high):
return
mid=(low+high)//2
if(f(mid-1)<f(mid)):
return binary_search(low,mid-1)
if(f(mid+1)<f(mid)):
return binary_search(mid+1,high)
return mid
n,a,r,m=map(int,input().split())
l=input().split()
li=[int(i) for i in l]
m=min(a+r,m)
print(f(binary_search(0,10**10)))
``` | instruction | 0 | 54,106 | 8 | 108,212 |
Yes | output | 1 | 54,106 | 8 | 108,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
a,b,c,d=map(int,input().split())
l=list(map(int,input().split()))
p=sum(l)
q=p//a
z=0
for i in l:
if i<q:
z+=q-i
z*=d
z+=(p%a)*b
dd=0
if b<c:
cc=max(l)
hh=b
else:
cc=min(l)
hh=c
for i in l:
dd+=abs(cc-i)
y=dd*hh
print(min(z,y))
``` | instruction | 0 | 54,107 | 8 | 108,214 |
No | output | 1 | 54,107 | 8 | 108,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
def find(h, x):
l = 0
r = len(h) - 1
while abs(r-l) > 1:
c = (l + r) // 2
if h[c] > x:
r = c
elif h[c] < x:
l = c
elif h[c] == x:
return c
return l + 1
def function(height):
global h
if h.count(height) == 0:
less = find(h, height)
more = len(h) - less
less_bricks = height * less - sum(h[0:less:])
more_bricks = (height * more - sum(h[-1:- len(h) + less - 1:-1])) * -1
# print(h[-1:- len(h) + less - 1:-1], " more")
# print(h[0:less:], " less")
# print(f"{height} _____________________ {less_bricks} {more_bricks}")
else:
less = h.index(height)
more = len(h) - less - h.count(height)
# print(h[-1:-len(h) + less + h.count(height) - 1:-1], " more")
# print(h[0:less:], " less")
less_bricks = height * less - sum(h[0:less:])
more_bricks = (height * more - sum(h[-1:-len(h) + less + h.count(height) - 1:-1])) * -1
# print(f"{height} _____________________ {less_bricks} {more_bricks}")
# sum(h[-1:-len(h) + less + h.count(height) - 1:-1]) - height * len(h) - less - h.count(height)
# print(h[-1:-len(h) + less + h.count(height) - 1:-1])
# len(h) - less - h.count(height)
#print(height, less, more)
if more_bricks >= less_bricks:
cost = less_bricks * M + abs(more_bricks - less_bricks) * R
else:
cost = more_bricks * M + abs(more_bricks - less_bricks) * A
# if otv != [] and cost > otv[-1]:
# print("---")
# break
return cost
otv = []
probably = []
N, A, R, M = map(int, input().split())
h = list(map(int, input().split()))
h.sort()
height = h[0]
# h_set = list(set(h))
# print(height)
if A + R < M:
M = A + R
#=====================
left = h[0]
right = h[-1]
c = (left + right) // 2
flag = 0
if function(left) < function(left + 1):
print(f"{function(left)} {left}")
flag = 1
elif function(right) < function(right - 1):
print(f"{function(right)} {right}")
flag = 1
else:
while flag == 0 and abs(left - right) > 2:
if function(c - 1) < function(c):
right = c
elif function(c + 1) < function(c):
left = c
elif function(c) < function(c-1) and function(c) < function(c + 1):
break
elif function(c - 1) == function(c):
break
c = (left + right) // 2
#print(c,left,right)
print(function(c))
``` | instruction | 0 | 54,108 | 8 | 108,216 |
No | output | 1 | 54,108 | 8 | 108,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
import math
import time
from collections import defaultdict,deque
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
t=1
# t=int(input())
for _ in range(t):
n,a,r,m=map(int,stdin.readline().split())
arr=list(map(int,stdin.readline().split()))
mi=min(arr)
ma=max(arr)
su=sum(arr)
poss=False
if(su%n==0):
poss=True
s=su//n
avg=round(su/n)
a1=0
a2=0
a3=0
a4=0
for i in arr:
a1+=(i-mi)*r
a2+=(ma-i)*a
if(poss):
a3+=abs(i-s)
if(i>avg):
a4+=(i-avg)*r
elif(i<avg):
a4+=(avg-i)*a
ans=min(a1,a2,a4)
if(poss):
a3=(a3//2)*m
ans=min(ans,a3)
else:
forl=0
forh=0
s=su//n
for i in arr:
if(i>s):
forl+=(i-s )*m
if(i>s+1):
forh+=(i-s-1)*m
ans=min(ans,forl+((su-(s*n))*r))
ans=min(ans,forh+((((s+1)*n)-su)*a))
print(ans)
``` | instruction | 0 | 54,109 | 8 | 108,218 |
No | output | 1 | 54,109 | 8 | 108,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have to restore the wall. The wall consists of N pillars of bricks, the height of the i-th pillar is initially equal to h_{i}, the height is measured in number of bricks. After the restoration all the N pillars should have equal heights.
You are allowed the following operations:
* put a brick on top of one pillar, the cost of this operation is A;
* remove a brick from the top of one non-empty pillar, the cost of this operation is R;
* move a brick from the top of one non-empty pillar to the top of another pillar, the cost of this operation is M.
You cannot create additional pillars or ignore some of pre-existing pillars even if their height becomes 0.
What is the minimal total cost of restoration, in other words, what is the minimal total cost to make all the pillars of equal height?
Input
The first line of input contains four integers N, A, R, M (1 ≤ N ≤ 10^{5}, 0 ≤ A, R, M ≤ 10^{4}) — the number of pillars and the costs of operations.
The second line contains N integers h_{i} (0 ≤ h_{i} ≤ 10^{9}) — initial heights of pillars.
Output
Print one integer — the minimal cost of restoration.
Examples
Input
3 1 100 100
1 3 8
Output
12
Input
3 100 1 100
1 3 8
Output
9
Input
3 100 100 1
1 3 8
Output
4
Input
5 1 2 4
5 5 3 6 5
Output
4
Input
5 1 2 2
5 5 3 6 5
Output
3
Submitted Solution:
```
from itertools import accumulate
n,a,r,m = map(int,input().split())
m = min(a+r,m)
ls = list(map(int,input().split()))
ls.sort()
acc = [0]+list(accumulate(ls))
ansls = []
sm = acc[-1]
less = sm//n
more = less+1
flg = 0
for i in range(n+1):
if i == 0:
minus = 0
plus = acc[n]
else:
minus = ls[i-1]*(i-1)-acc[i-1]
plus = acc[n]-acc[i]-ls[i-1]*(n-i)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
if less < acc[i] and not flg:
flg = 1
minus = less*(i-1)-acc[i-1]
plus = acc[n]-acc[i-1]-less*(n-i+1)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
if more < acc[i] and flg == 1:
flg = 2
minus = more*(i-1)-acc[i-1]
plus = acc[n]-acc[i-1]-more*(n-i+1)
if plus > minus:
ansls.append(minus*m+(plus-minus)*r)
else:
ansls.append(plus*m+(minus-plus)*a)
print(min(ansls))
``` | instruction | 0 | 54,110 | 8 | 108,220 |
No | output | 1 | 54,110 | 8 | 108,221 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,340 | 8 | 108,680 |
Tags: string suffix structures, strings
Correct Solution:
```
def KMPSearch(pat, txt):
ans=0
M = len(pat)
N = len(txt)
lps = [0]*M
j = 0
computeLPSArray(pat, M, lps)
i = 0
while i < N:
if pat[j] == txt[i]:
i += 1
j += 1
if j == M:
ans+=1
j = lps[j-1]
elif i < N and pat[j] != txt[i]:
if j != 0:
j = lps[j-1]
else:
i += 1
return ans
def computeLPSArray(pat, M, lps):
len = 0
lps[0]
i = 1
while i < M:
if pat[i]== pat[len]:
len += 1
lps[i] = len
i += 1
else:
if len != 0:
len = lps[len-1]
else:
lps[i] = 0
i += 1
n,w=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
if w==1:
print(n)
else:
l,p=[],[]
for i in range(1,len(a)):
l.append(a[i]-a[i-1])
for i in range(1,len(b)):
p.append(b[i]-b[i-1])
print(KMPSearch(p,l))
``` | output | 1 | 54,340 | 8 | 108,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,341 | 8 | 108,682 |
Tags: string suffix structures, strings
Correct Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
import sys
from io import BytesIO, IOBase
from bisect import *
def pie(s): # pie function of KMP algorithm ; pi[i] tell that ending at i what is the maximum length of the suffix that matches with preffix
n = len(s)
pi = [0] * n
for i in range(1, n):
j=pi[i-1]
while j>0 and s[i] != s[j]:
j = pi[j - 1]
j += (s[i] == s[j])
pi[i] = j
return pi
def solve(x):
ans=[]
for i in range(len(x)-1):
ans.append(x[i+1]-x[i])
return ans
def main():
n,w=map(int,input().split())
a=list(map(int,input().split()))
b=list(map(int,input().split()))
if w==1:
print(n)
elif n==1:
print(0)
else:
pi,ans=pie(solve(b)+[10**12]+solve(a)),0
for i in range(w,len(pi),1):
if pi[i]==w-1:
ans+=1
print(ans)
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 54,341 | 8 | 108,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,342 | 8 | 108,684 |
Tags: string suffix structures, strings
Correct Solution:
```
# -*- coding:utf-8 -*-
"""
created by shuangquan.huang at 2/11/20
"""
import collections
import time
import os
import sys
import bisect
import heapq
from typing import List
def solve_prefix(N, W, A, B):
# https://cp-algorithms.com/string/prefix-function.html
if len(B) == 1:
return N
A = [A[i] - A[i + 1] for i in range(N - 1)]
B = [B[i] - B[i + 1] for i in range(W - 1)]
v = max(max(A), max(B)) + 1
C = B + [v] + A
M = len(C)
pi = [0 for _ in range(M)]
for i in range(1, M):
j = pi[i-1]
while j > 0 and C[i] != C[j]:
j = pi[j-1]
if C[i] == C[j]:
j += 1
pi[i] = j
return pi.count(W-1)
def solve_zfunc(N, W, A, B):
# https://cp-algorithms.com/string/z-function.html
if len(B) == 1:
return N
A = [A[i]-A[i+1] for i in range(N-1)]
B = [B[i]-B[i+1] for i in range(W-1)]
v = max(max(A), max(B)) + 1
C = B + [v] + A
M = len(C)
z = [0 for _ in range(M)]
l, r = 0, 0
# i starts from 1
for i in range(1, M):
if i <= r:
z[i] = min(z[i-l], r-i+1)
while i + z[i] < M and C[z[i]] == C[i+z[i]]:
z[i] += 1
if i + z[i] - 1 > r:
r = i + z[i] - 1
l = i
# print(C)
# print(z)
return z.count(W-1)
N, W = map(int, input().split())
A = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
# print(solve_zfunc(N, W, A, B))
print(solve_prefix(N, W, A, B))
``` | output | 1 | 54,342 | 8 | 108,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,343 | 8 | 108,686 |
Tags: string suffix structures, strings
Correct Solution:
```
n, k = map(int, input().split())
a = tuple(map(int, input().split()))
b = tuple(map(int, input().split()))
if k == 1:
print(n)
elif k > n:
print(0)
else:
p = int(1e16 + 7)
q = int(499)
h1 = 0
hs = [0] * (n + 1)
pw = [1] * (n + 1)
z = 1
for i in range(1, n):
hs[i] = (hs[i - 1] * q + (a[i] - a[i - 1]) % int(1e18)) % p
pw[i] = (pw[i - 1] * q) % p
if i < k:
h1 = (h1 * q + (b[i] - b[i - 1]) % int(1e18)) % p
def get_hash(a, b): # hash [a, b)
return (hs[b - 1] - (hs[a] * pw[b - a - 1]) % p + p) % p
ans = 0
for i in range(n - k + 1):
if get_hash(i, i + k) - h1 == 0:
ans += 1
print(ans)
``` | output | 1 | 54,343 | 8 | 108,687 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,344 | 8 | 108,688 |
Tags: string suffix structures, strings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
import math as mt
import inspect, re
def varname(p): # prints name of the variable
for line in inspect.getframeinfo(inspect.currentframe().f_back)[3]:
m = re.search(r'\bvarname\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)', line)
if m:
return m.group(1)
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
mod = int(1e9) + 7
def power(k, n):
if n == 0:
return 1
if n % 2:
return (power(k, n - 1) * k) % mod
t = power(k, n // 2)
return (t * t) % mod
def totalPrimeFactors(n):
count = 0
if (n % 2) == 0:
count += 1
while (n % 2) == 0:
n //= 2
i = 3
while i * i <= n:
if (n % i) == 0:
count += 1
while (n % i) == 0:
n //= i
i += 2
if n > 2:
count += 1
return count
# #MAXN = int(1e7 + 1)
# # spf = [0 for i in range(MAXN)]
#
#
# def sieve():
# spf[1] = 1
# for i in range(2, MAXN):
# spf[i] = i
# for i in range(4, MAXN, 2):
# spf[i] = 2
#
# for i in range(3, mt.ceil(mt.sqrt(MAXN))):
# if (spf[i] == i):
# for j in range(i * i, MAXN, i):
# if (spf[j] == j):
# spf[j] = i
#
#
# def getFactorization(x):
# ret = 0
# while (x != 1):
# k = spf[x]
# ret += 1
# # ret.add(spf[x])
# while x % k == 0:
# x //= k
#
# return ret
# Driver code
# precalculating Smallest Prime Factor
# sieve()
pow2 = []
def gethash(x):
curr = 0
for i in range(len(x)):
curr = (curr + (x[i] * pow2[i]+mod)%mod) % mod
return curr
def main():
n, w = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
da = []
db = []
for i in range(1, n):
da.append(a[i] - a[i - 1]+int(2e5))
for i in range(1, w):
db.append(b[i] - b[i - 1]+int(2e5))
hb = gethash(db)
pre=[0]
# print(da)
# print(db)
for i in range(1,len(da)+1):
pre.append((pre[i-1]+pow2[i-1]*da[i-1]+mod)%mod)
#print(pre)
ans = 0
for i in range(len(da)):
if i+w-1>=len(pre):
break
curr_hash=(pre[i+w-1]-pre[i]+mod)%mod
if curr_hash==hb*pow2[i]%mod:
#print(curr_hash, i, hb*pow2[i]%mod)
ans+=1
if len(b)==1:
ans+=1
print(ans)
return
if __name__ == "__main__":
pow2.append(1)
for i in range(1, int(2e5) + 1):
pow2.append(pow2[i - 1] * 31 % mod)
main()
``` | output | 1 | 54,344 | 8 | 108,689 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,345 | 8 | 108,690 |
Tags: string suffix structures, strings
Correct Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO,IOBase
def calprefix(pat):
n = len(pat)
pi = [0]*n
for i in range(1,n):
j = pi[i-1]
while j and pat[i] != pat[j]:
j = pi[j-1]
if pat[i] == pat[j]:
j += 1
pi[i] = j
return pi
def kmp(pi,s,pat):
j,n,m,ans = 0,len(s),len(pat),0
for i in range(n):
while pat[j] != s[i]:
if j:
j = pi[j-1]
else:
break
if pat[j] == s[i]:
i,j = i+1,j+1
if j == m:
ans += 1
j = pi[j-1]
return ans
def main():
n,m = map(int,input().split())
a = list(map(int,input().split()))
b = list(map(int,input().split()))
if m == 1:
print(n)
elif n == 1:
print(0)
else:
string = [a[i+1]-a[i] for i in range(n-1)]
pat = [b[i+1]-b[i] for i in range(m-1)]
print(kmp(calprefix(pat),string,pat))
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self,file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE))
self.newlines = b.count(b"\n")+(not b)
ptr = self.buffer.tell()
self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd,self.buffer.getvalue())
self.buffer.truncate(0),self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self,file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s:self.buffer.write(s.encode("ascii"))
self.read = lambda:self.buffer.read().decode("ascii")
self.readline = lambda:self.buffer.readline().decode("ascii")
sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout)
input = lambda:sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | output | 1 | 54,345 | 8 | 108,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polar bears Menshykov and Uslada from the zoo of St. Petersburg and elephant Horace from the zoo of Kiev got hold of lots of wooden cubes somewhere. They started making cube towers by placing the cubes one on top of the other. They defined multiple towers standing in a line as a wall. A wall can consist of towers of different heights.
Horace was the first to finish making his wall. He called his wall an elephant. The wall consists of w towers. The bears also finished making their wall but they didn't give it a name. Their wall consists of n towers. Horace looked at the bears' tower and wondered: in how many parts of the wall can he "see an elephant"? He can "see an elephant" on a segment of w contiguous towers if the heights of the towers on the segment match as a sequence the heights of the towers in Horace's wall. In order to see as many elephants as possible, Horace can raise and lower his wall. He even can lower the wall below the ground level (see the pictures to the samples for clarification).
Your task is to count the number of segments where Horace can "see an elephant".
Input
The first line contains two integers n and w (1 ≤ n, w ≤ 2·105) — the number of towers in the bears' and the elephant's walls correspondingly. The second line contains n integers ai (1 ≤ ai ≤ 109) — the heights of the towers in the bears' wall. The third line contains w integers bi (1 ≤ bi ≤ 109) — the heights of the towers in the elephant's wall.
Output
Print the number of segments in the bears' wall where Horace can "see an elephant".
Examples
Input
13 5
2 4 5 5 4 3 2 2 2 3 3 2 1
3 4 4 3 2
Output
2
Note
The picture to the left shows Horace's wall from the sample, the picture to the right shows the bears' wall. The segments where Horace can "see an elephant" are in gray.
<image> | instruction | 0 | 54,346 | 8 | 108,692 |
Tags: string suffix structures, strings
Correct Solution:
```
"""
Codeforces Contest 269 Div 2 Problem D
Author : chaotic_iak
Language: Python 3.3.4
"""
def main():
n,w = read()
if w == 1: return n
a = read()
b = read()
c,d = [],[]
for i in range(n-1):
c.append(a[i+1]-a[i])
for i in range(w-1):
d.append(b[i+1]-b[i])
print(kmp(c,d))
# KMP from wikipedia translated
def kmp(s,w):
w.append(1234567890987654321)
ls = len(s)
lw = len(w)
# populate table
pos = 2
cnd = 0
t = [0] * lw
t[0] = -1
t[1] = 0
while pos < lw:
if w[pos-1] == w[cnd]:
cnd += 1
t[pos] = cnd
pos += 1
elif cnd > 0:
cnd = t[cnd]
else:
t[pos] = 0
pos += 1
# find matches
m = 0
i = 0
matches = []
while m+i < ls:
if w[i] == s[m+i]:
if i == lw-2: matches.append(m)
i += 1
else:
if t[i] > -1:
m += i-t[i]
i = t[i]
else:
i = 0
m += 1
return len(matches)
################################### NON-SOLUTION STUFF BELOW
def read(mode=2):
# 0: String
# 1: List of strings
# 2: List of integers
inputs = input().strip()
if mode == 0: return inputs
if mode == 1: return inputs.split()
if mode == 2: return list(map(int, inputs.split()))
def write(s="\n"):
if s is None: s = ""
if isinstance(s, list): s = " ".join(map(str, s))
s = str(s)
print(s, end="")
write(main())
``` | output | 1 | 54,346 | 8 | 108,693 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.