text stringlengths 198 433k | conversation_id int64 0 109k |
|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
Submitted Solution:
```
t=int(input())
for _ in range(t):
n = int(input())
l=[]
i=int(0)
for i in range(n):
l.append(input())
x1=l[0][1]
x2=l[1][0]
y1,y2 = l[-2][-1],l[-1][-2]
# print(x1)
# print(x2)
# print(y1)
# print(y2)
if(x1==x2==y1==y2):
print("2")
print("1 2")
print("2 1")
print("k")
elif ((x1==x2)and(y1==y2)):
print("0")
elif ((x1==x2) and (y1!=y2)):
if ((x1=='0') and (y1=='0')):
print("1")
print(n-1,n)
elif ((x1=='0') and (y2=='0')):
print("1")
print(n, n-1)
elif ((x1=='1') and (y1=='1')):
print("1")
print(n-1, n)
elif ((x1=='1') and (y2=='1')):
print("1")
print(n, n-1)
elif ((x1!=x2) and (y1==y2)):
if ((y1=='0') and (x1=='0')):
print("1")
print("1 2")
elif ((y1=='0') and (x2=='0')):
print("1")
print("2 1")
elif ((y1=='1') and (x1=='1')):
print("1")
print("1 2")
elif ((y1=='1') and (x2=='1')):
print("1")
print("2 1")
elif ((x1!=x2) and (y1!=y2)):
if (x1=='1' and y1=='1'):
print("2")
print("2 1")
print(n-1,n)
elif (x1=='1' and y2=='1'):
print("2")
print("2 1")
print(n, n-1)
elif (x1=='0' and y2=='0'):
print("2")
print("2 1")
print(n-1, n)
elif (x1=='0' and y2=='0'):
print("2")
print("2 1")
print(n,n-1)
```
No
| 85,900 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
Submitted Solution:
```
import sys
input = sys.stdin.readline
def solve():
n=int(input())
M=[list(input().strip()) for _ in range(n)]
def check():
ans= []
if M[0][1]==M[1][0]=='1':
if M[n-1][n-2]=='1':
ans.append([n,n-1])
if M[n-2][n-1]=='1':
ans.append([n-1,n])
return ans
if M[0][1]==M[1][0]=='0':
if M[n-1][n-2]=='0':
ans.append([n,n-1])
if M[n-2][n-1]=='0':
ans.append([n-1,n])
return ans
else:
if M[0][1]=='0':
ans.append([1,2])
if M[1][0]=='0':
ans.append([2,1])
if M[n-1][n-2]=='1':
ans.append([n,n-1])
if M[n-2][n-1]=='1':
ans.append([n-1,n])
return ans
def pr(ans):
print(len(ans))
for i in ans:
print(*i)
ans = check()
pr(ans)
if __name__=="__main__":
for _ in range(int(input())):
solve()
```
No
| 85,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Pink Floyd are pulling a prank on Roger Waters. They know he doesn't like [walls](https://www.youtube.com/watch?v=YR5ApYxkU-U), he wants to be able to walk freely, so they are blocking him from exiting his room which can be seen as a grid.
Roger Waters has a square grid of size nΓ n and he wants to traverse his grid from the upper left (1,1) corner to the lower right corner (n,n). Waters can move from a square to any other square adjacent by a side, as long as he is still in the grid. Also except for the cells (1,1) and (n,n) every cell has a value 0 or 1 in it.
Before starting his traversal he will pick either a 0 or a 1 and will be able to only go to cells values in which are equal to the digit he chose. The starting and finishing cells (1,1) and (n,n) are exempt from this rule, he may go through them regardless of picked digit. Because of this the cell (1,1) takes value the letter 'S' and the cell (n,n) takes value the letter 'F'.
For example, in the first example test case, he can go from (1, 1) to (n, n) by using the zeroes on this path: (1, 1), (2, 1), (2, 2), (2, 3), (3, 3), (3, 4), (4, 4)
The rest of the band (Pink Floyd) wants Waters to not be able to do his traversal, so while he is not looking they will invert at most two cells in the grid (from 0 to 1 or vice versa). They are afraid they will not be quick enough and asked for your help in choosing the cells. Note that you cannot invert cells (1, 1) and (n, n).
We can show that there always exists a solution for the given constraints.
Also note that Waters will pick his digit of the traversal after the band has changed his grid, so he must not be able to reach (n,n) no matter what digit he picks.
Input
Each test contains multiple test cases. The first line contains the number of test cases t (1 β€ t β€ 50). Description of the test cases follows.
The first line of each test case contains one integers n (3 β€ n β€ 200).
The following n lines of each test case contain the binary grid, square (1, 1) being colored in 'S' and square (n, n) being colored in 'F'.
The sum of values of n doesn't exceed 200.
Output
For each test case output on the first line an integer c (0 β€ c β€ 2) β the number of inverted cells.
In i-th of the following c lines, print the coordinates of the i-th cell you inverted. You may not invert the same cell twice. Note that you cannot invert cells (1, 1) and (n, n).
Example
Input
3
4
S010
0001
1000
111F
3
S10
101
01F
5
S0101
00000
01111
11111
0001F
Output
1
3 4
2
1 2
2 1
0
Note
For the first test case, after inverting the cell, we get the following grid:
S010
0001
1001
111F
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
s = []
for __ in range(n):
s.append([int(x) for x in input() if x.isdigit()])
s[0].insert(0,0)
s[n-1].insert(n-1,0)
c = 0
ans = []
#for i in s:
# print(*i)
if s[0][1] and s[1][0]:
if not s[n-1][n-2]:
c += 1
ans.append([n,n-1])
if not s[n-2][n-1]:
c += 1
ans.append([n-1,n])
print(c)
for i in ans:
print(*i)
continue
elif not(s[0][1] or s[1][0]):
if not s[n-1][n-2]:
c += 1
ans.append([n,n-1])
if not s[n-2][n-1]:
c += 1
ans.append([n-1,n])
print(c)
for i in ans:
print(*i)
continue
elif s[0][1] or s[1][0]:
if s[n-1][n-2] or s[n-2][n-1]:
if s[n-1][n-2]:
if s[0][1]:
print(2)
print(1, 2)
print(n-2, n-1)
else:
print(2)
print(2, 1)
print(n-2, n-1)
else:
if s[0][1]:
print(2)
print(1, 2)
print(n-2, n-1)
else:
print(2)
print(2, 1)
print(n-2, n-1)
else:
if not s[0][1]:
print(1)
print(0, 1)
continue
else:
print(1)
print(1, 1)
c += 1
ans.append([n-1,n])
```
No
| 85,902 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
c=((c1-d1)+r2)//2
b=((r1-c1)+d2)//2
a=r1-b
d=d1-a
e={a,b,c,d}
if len(e)==4 and 10>a>0 and 10>b>0 and 10>c>0 and 10>d>0:
if a+b==r1 and c+d==r2 and a+c==c1 and b+d==c2 and a+d==d1 and b+c==d2:
print(a,b)
print(c,d)
else: print(-1)
else: print(-1)
"""
a+b=r1 c+d=r2
a+c=c1 b+d=c2
a+d=d1 b+c=d2
b-c=r1-c1 c-b=r2-c2
b+c=d2
2b=(r1-c1)+d2
c-d=c1-d1
c+d=r2
2c=(c1-d1)+r2
"""
```
| 85,903 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2 = map(int,input().split())
c1,c2 = map(int,input().split())
d1,d2 = map(int,input().split())
ans = []
a = (r1+c1-d2)//2
ans.append(a)
b = r1 - a
ans.append(b)
c = c1 - a
ans.append(c)
d = d1 - a
ans.append(d)
ans = list(set(ans))
if(len(ans)<4):
print(-1)
elif(ans[3]>9):
print(-1)
elif(a*b*c*d <=0):
print(-1)
elif(max(a,b,c,d)>9):
print(-1)
elif((c+d)!=r2 or (b+d)!=c2 or (c+b)!=d2):
print(-1)
else:
print(a,b)
print(c,d)
```
| 85,904 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
a=(r1+c1-d2)//2
b=r1-a
c=c1-a
d=c2-b
if a+d==d1 and b+c==d2 and a+b==r1 and c+d==r2 and a+c==c1 and b+d==c2 and len(set([a,b,c,d]))==4 and len(set([a,b,c,d]))==4 and max(a,b,c,d)<10 and min(a,b,c,d)>0:
print(a,b)
print(c,d)
else:
print(-1)
```
| 85,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2 = map(int,input().split())
c1,c2 = map(int,input().split())
d1,d2 = map(int,input().split())
res = [[-1]]
for i in range(1,10):
for j in range(1,10):
for k in range(1,10):
for l in range(1,10):
if i + j == r1 and i + k == c1 and i +l == d1 and j +l == c2 and k +l == r2 and j+k == d2 :
if len(set([i,j,k,l])) == 4:
res = [[i,j],[k,l]]
[print(*i) for i in res]
```
| 85,906 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
a=(r1+c1-d2)//2
b=c1-a
c=r1-a
d=d1-a
l={a,b,c,d}
if len(l)<4 or min(l)<1 or max(l)>9 or b+d!=r2 or a+d!=d1 or c+d!=c2:
print(-1)
else:
print(a,c)
print(b,d)
```
| 85,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
def solve():
def readinput():
return map(int, input().strip().split())
r1, r2 = readinput()
c1, c2 = readinput()
d1, d2 = readinput()
for g1 in range(1, 10):
for g2 in range(1, 10):
for g3 in range(1, 10):
for g4 in range(1, 10):
s = set([g1, g2, g3, g4])
if len(s) == 4:
if r1 == g1 + g2 and r2 == g3 + g4 and c1 == g1 + g3 and c2 == g2 + g4 and d1 == g1 + g4 and d2 == g2 + g3:
return f"{g1} {g2}\n{g3} {g4}"
return -1
print(solve())
```
| 85,908 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1,r2 = input().split(" ")
c1,c2 = input().split(" ")
d1,d2 = input().split(" ")
r1,r2,c1,c2,d1,d2 = int(r1),int(r2),int(c1),int(c2),int(d1),int(d2)
ar1 = []
z = True
m = max(c1,c2)
if(r1+r2 == c1+c2 == d1+d2):
for n in range((r1-1)//2):
ar1.append([r1-1-n,1+n])
for n in ar1:
if n[0] < 10 and n[0] <= m:
ar2 = []
ar2.append(c1-n[0])
ar2.append(r2-ar2[0])
if(n[0] == ar2[0] or n[1] == ar2[1] or ar2[0] == ar2[1] or n[0] == ar2[1] or n[1] == ar2[0]):
n[0],n[1] = n[1],n[0]
ar2 = []
ar2.append(c1-n[0])
ar2.append(r2-ar2[0])
if not (n[0] == ar2[0] or n[1] == ar2[1] or ar2[0] == ar2[1] or n[0] == ar2[1] or n[1] == ar2[0]):
if(n[0]+ar2[1] == d1 and n[1] + ar2[0] == d2 and ar2[0] < 10 and ar2[1] < 10 and ar2[0] > 0 and ar2[1] > 0):
print(n[0],n[1])
print(ar2[0],ar2[1])
z = False
break
else:
if(n[0]+ar2[1] == d1 and n[1] + ar2[0] == d2 and ar2[0] < 10 and ar2[1] < 10 and ar2[0] > 0 and ar2[1] > 0):
print(n[0],n[1])
print(ar2[0],ar2[1])
z = False
break
else:
n[0],n[1] = n[1],n[0]
ar2 = []
ar2.append(c1-n[0])
ar2.append(r2-ar2[0])
if not(n[0] == ar2[0] or n[1] == ar2[1] or ar2[0] == ar2[1] or n[0] == ar2[1] or n[1] == ar2[0]):
if(n[0]+ar2[1] == d1 and n[1] + ar2[0] == d2 and ar2[0] < 10 and ar2[1] < 10 and ar2[1] > 0 and ar2[0] > 0):
print(n[0],n[1])
print(ar2[0],ar2[1])
z = False
break
if z:
print("-1")
else:
print("-1")
```
| 85,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Tags: brute force, math
Correct Solution:
```
r1, r2 = list(map(int, input().split()))
c1, c2 = list(map(int, input().split()))
d1, d2 = list(map(int, input().split()))
for i in range(1, 10):
for j in range(1, 10):
if i == j:
continue
for k in range(1, 10):
if i == k or j == k:
continue
for l in range(1, 10):
if i == l or j == l or k == l:
continue
if i + j == r1 and k + l == r2 and i + k == c1 and j + l == c2 and i + l == d1 and j + k == d2:
print(i, j)
print(k, l)
exit()
print(-1)
```
| 85,910 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
__author__ = 'asmn'
r1,r2=tuple(map(int,input().split()))
c1,c2=tuple(map(int,input().split()))
d1,d2=tuple(map(int,input().split()))
for a11 in range(1,10):
a12=r1-a11
a21=c1-a11
a22=c2-a12
if a21+a22==r2 and a11+a22==d1 and a12+a21==d2 and 1<=a12<=9 and 1<=a21<=9 and 1<=a22<=9 and a12 !=a11 and a21!=a11 and a21!=a12 and a22 != a11 and a22!=a12 and a22!=a21:
print('%d %d\n%d %d'%(a11,a12,a21,a22))
break
else:
print(-1)
```
Yes
| 85,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
r1,r2=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
a=(r1+c1-d2)/2
b=r1-a;c=c1-a;d=d1-a
A=set()
A.add(a);A.add(b);A.add(c);A.add(d)
if(a>9 or b>9 or c>9 or d>9):
print("-1")
elif(a<1 or c<1 or b<1 or d<1):
print("-1")
elif(a!=int(a)):
print("-1")
elif(len(A)<4):
print("-1")
elif(a+b!=r1 or c+d !=r2 or a+c !=c1 or b+d!=c2 or a+d!=d1 or b+c !=d2):
print("-1")
else:
print(int(a),int(b))
print(int(c),int(d))
```
Yes
| 85,912 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
import sys
r1, r2 = map(int, input().split())
c1, c2 = map(int, input().split())
d1, d2 = map(int, input().split())
lst = []
r1l = []
r2l = []
c1l = []
c2l = []
d1l = []
d2l = []
newlist = []
perfectlist = []
for i in range(10):
for y in range(10):
lst.append([i,y])
for item in lst:
if sum(item) == r1:
r1l.append(item)
if sum(item) == r2:
r2l.append(item)
if sum(item) == c1:
c1l.append(item)
if sum(item) == c2:
c2l.append(item)
if sum(item) == d1:
d1l.append(item)
if sum(item) == d2:
d2l.append(item)
for item1 in r1l:
for item2 in r2l:
if item1[0] + item2[0] == c1 and item1[1] + item2[1] == c2:
newlist.append([item1,item2])
for item in newlist:
r11,r22 = item
if r11[0] + r22[1] == d1 and r11[1] + r22[0] == d2:
perfectlist.append([r11,r22])
if perfectlist == []:
print(-1)
sys.exit()
y = perfectlist[0]
if y == [] or y[0][0] == y[0][1] or y[0][0] == y[1][0] or y[0][0] == y[1][1] or y[0][1] == y[1][0] or y[0][1] == y[1][1] or y[1][1] == y[1][0] or y[0][0] == 0 or y[0][1] == 0 or y[1][0] == 0 or y[1][1] == 0:
print(-1)
sys.exit()
print(y[0][0],y[0][1])
print(y[1][0],y[1][1])
```
Yes
| 85,913 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
from sys import stdin,stdout
i1 = lambda : int(stdin.readline())
iia = lambda : map(int, stdin.readline().split())
isa = lambda: stdin.readline().split()
r1, r2 = iia()
c1, c2 = iia()
d1, d2 = iia()
if (c2 + r2 - d2) % 2 == 0:
d = (c2 + r2 - d2) // 2
c = r2 - d
b = c2 - d
a = r1 - b
temp = [a, b, c, d]
if len(set(temp)) != 4:
print(-1)
else:
for i in temp:
if not (i > 0 and i < 10):
print(-1)
break
else:
print(a, b)
print(c, d)
else:
print(-1)
```
Yes
| 85,914 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
import math
r = list(map(int, input().split()))
c = list(map(int, input().split()))
d = list(map(int, input().split()))
x3 = math.ceil((c[0] + d[1] - r[0])/2)
x1 = c[0] - x3
x2 = d[1] - x3
x4 = r[1] - x3
#print(x1,x2)
#print(x3,x4)
if (x3 > 9) or (x1 > 9) or (x2 > 9) or (x4 > 9) or (x3 <= 0) or (x1 <= 0) or (x2 <= 0) or (x4 <= 0):
print(-1)
#print(0)
elif x3 == x1 or x3 == x2 or x3 == x4 or x1 == x2 or x1 == x4 or x2 == x4 :
print(-1)
#print(1)
else:
print(x1,x2)
print(x3,x4)
```
No
| 85,915 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
k=[]
for i in range(3):
k.append(list(map(int,input().split())))
r1,r2,c1,c2,d1,d2=k[0][0],k[0][1],k[1][0],k[1][1],k[2][0],k[2][1]
x1=(r1-d2+c1)//2
x2=r1-x1
x3=(d2-r1+c1)//2
x4=d1-x1
if x1<0 or x2<0 or x3<0 or x4<0 or x1>9 or x2>9 or x3>9 or x4>9:print(-1)
else:
print(x1,x2)
print(x3,x4)
```
No
| 85,916 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
r1,r2=map(int,input().split())
c1,c2=map(int,input().split())
d1,d2=map(int,input().split())
flag=0
for i in range(1,10):
l=[]
x1=i
y1=r1-x1
x2=c1-x1
y2=c2-r1+x1
if(0<y1<10 and 0<x2<10 and 0<y2<10):
l.append(x1)
l.append(y2)
l.append(y1)
l.append(x2)
if(len(set(l))==4):
flag=1
print(x1,y1)
print(x2,y2)
break;
if(flag==0):
print("-1")
```
No
| 85,917 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Vasilisa the Wise from the Kingdom of Far Far Away got a magic box with a secret as a present from her friend Hellawisa the Wise from the Kingdom of A Little Closer. However, Vasilisa the Wise does not know what the box's secret is, since she cannot open it again. She hopes that you will help her one more time with that.
The box's lock looks as follows: it contains 4 identical deepenings for gems as a 2 Γ 2 square, and some integer numbers are written at the lock's edge near the deepenings. The example of a lock is given on the picture below.
<image>
The box is accompanied with 9 gems. Their shapes match the deepenings' shapes and each gem contains one number from 1 to 9 (each number is written on exactly one gem). The box will only open after it is decorated with gems correctly: that is, each deepening in the lock should be filled with exactly one gem. Also, the sums of numbers in the square's rows, columns and two diagonals of the square should match the numbers written at the lock's edge. For example, the above lock will open if we fill the deepenings with gems with numbers as is shown on the picture below.
<image>
Now Vasilisa the Wise wants to define, given the numbers on the box's lock, which gems she should put in the deepenings to open the box. Help Vasilisa to solve this challenging task.
Input
The input contains numbers written on the edges of the lock of the box. The first line contains space-separated integers r1 and r2 that define the required sums of numbers in the rows of the square. The second line contains space-separated integers c1 and c2 that define the required sums of numbers in the columns of the square. The third line contains space-separated integers d1 and d2 that define the required sums of numbers on the main and on the side diagonals of the square (1 β€ r1, r2, c1, c2, d1, d2 β€ 20). Correspondence between the above 6 variables and places where they are written is shown on the picture below. For more clarifications please look at the second sample test that demonstrates the example given in the problem statement.
<image>
Output
Print the scheme of decorating the box with stones: two lines containing two space-separated integers from 1 to 9. The numbers should be pairwise different. If there is no solution for the given lock, then print the single number "-1" (without the quotes).
If there are several solutions, output any.
Examples
Input
3 7
4 6
5 5
Output
1 2
3 4
Input
11 10
13 8
5 16
Output
4 7
9 1
Input
1 2
3 4
5 6
Output
-1
Input
10 10
10 10
10 10
Output
-1
Note
Pay attention to the last test from the statement: it is impossible to open the box because for that Vasilisa the Wise would need 4 identical gems containing number "5". However, Vasilisa only has one gem with each number from 1 to 9.
Submitted Solution:
```
r1,r2 = map(int,input().split())
c1,c2 = map(int,input().split())
d1,d2 = map(int,input().split())
a=0 ;b=0;c=0;d=0
if (r1+c1-d2)%2==0:
a = (r1+c1-d2)//2
if (r1+c2-d1)%2==0:
b = (r1-d1+c2)//2
c = c1-a
d = d1-a
if a and b and c and d and a!=b and c!=d:
print(a,b)
print(c,d)
else:
print(-1)
```
No
| 85,918 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
from collections import defaultdict
import sys
input = sys.stdin.readline
class UF:
def __init__(self, N):
self.par = list(range(N))
self.sz = [1] * N
def find(self, x):
if self.par[x] != x:
self.par[x] = self.find(self.par[x])
return self.par[x]
def union(self, x, y):
xr, yr = self.find(x), self.find(y)
if xr == yr:
return False
if self.sz[xr] < self.sz[yr]:
xr, yr = yr, xr
self.par[yr] = xr
self.sz[xr] += self.sz[yr]
return True
def size(self, x):
return self.sz[self.find(x)]
def connected(self, x, y):
return self.find(x) == self.find(y)
n,m = list(map(int, input().split(' ')))
cur_count = 1
cur_lst = []
uf = UF(m+2)
for i in range(n):
bit_lst = list(map(int, input().split(' ')))
bit1 = bit_lst[1]
bit2 = m+1
if bit_lst[0] == 2:
bit2 = bit_lst[2]
if uf.union(bit1, bit2):
cur_lst.append(str(i+1))
cur_count *= 2
cur_count %= 10**9 + 7
print(cur_count, len(cur_lst))
print(" ".join(cur_lst))
```
| 85,919 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
import sys
input = iter(sys.stdin.read().splitlines()).__next__
class UnionFind: # based on submission 102831279
def __init__(self, n):
""" elements are 0, 1, 2, ..., n-1 """
self.parent = list(range(n))
def find(self, x):
found = x
while self.parent[found] != found:
found = self.parent[found]
while x != found:
y = self.parent[x]
self.parent[x] = found
x = y
return found
def union(self, x, y):
self.parent[self.find(x)] = self.find(y)
n, m = map(int, input().split())
S_prime = []
# redundant (linearly dependent) vectors would be part of cycle
uf = UnionFind(m+1)
for index in range(1, n+1):
# one-hot vectors become (x_1, m)
vector_description = [int(i)-1 for i in input().split()] + [m]
u, v = vector_description[1:3]
if uf.find(u) == uf.find(v):
continue
S_prime.append(index)
uf.union(u, v)
# 2**|S'| different sums among |S'| linearly independent vectors
T_size = pow(2, len(S_prime), 10**9+7)
print(T_size, len(S_prime))
# print(S_prime)
print(*sorted(S_prime))
```
| 85,920 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
#######
n,m=[int(x) for x in input().split()]
uf=UnionFind(m+1)
hasOne=[False for _ in range(m+1)] #hasOne[parent]
#a tree cannot have cycles
#a tree can have at most vector with 1 "1"
sPrime=[]
for i in range(n):
inp=[int(x) for x in input().split()]
if inp[0]==1:#vector has 1 "1"
parent=uf.find(inp[1])
if hasOne[parent]==False:#take this vector
sPrime.append(i+1)
hasOne[parent]=True
else:
parent1,parent2=uf.find(inp[1]),uf.find(inp[2])
if parent1!=parent2: #no cycle. will join 2 trees
if not (hasOne[parent1] and hasOne[parent2]):#take this vector
sPrime.append(i+1)
uf.union(inp[1],inp[2])
newParent=uf.find(inp[1])
hasOne[newParent]=hasOne[parent1] or hasOne[parent2]
S_magnitude=len(sPrime)
T_magnitude=pow(2,S_magnitude,10**9+7)
print('{} {}'.format(T_magnitude,S_magnitude))
oneLineArrayPrint(sPrime)
```
| 85,921 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
import sys
readline = sys.stdin.readline
class UF():
def __init__(self, num):
self.par = [-1]*num
self.color = [0]*num
def find(self, x):
if self.par[x] < 0:
return x
else:
stack = []
while self.par[x] >= 0:
stack.append(x)
x = self.par[x]
for xi in stack:
self.par[xi] = x
return x
def col(self, x):
return self.color[self.find(x)]
def paint(self, x):
self.color[self.find(x)] = 1
def union(self, x, y):
rx = self.find(x)
ry = self.find(y)
if rx != ry:
if self.par[rx] > self.par[ry]:
rx, ry = ry, rx
self.par[rx] += self.par[ry]
self.par[ry] = rx
self.color[rx] |= self.color[ry]
return True
return False
N, M = map(int, readline().split())
MOD = 10**9+7
ans = []
T = UF(M)
for m in range(N):
k, *x = map(int, readline().split())
if k == 1:
u = x[0]-1
if not T.col(u):
ans.append(m+1)
T.paint(u)
else:
u, v = x[0]-1, x[1]-1
if T.col(u) and T.col(v):
continue
if T.union(u, v):
ans.append(m+1)
print(pow(2, len(ans), MOD), len(ans))
print(' '.join(map(str, ans)))
```
| 85,922 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
mod=1000000007
n,m=map(int,input().split())
ans=[]
groupi=[-1]*(m+1)
groups=[2]*m
for i in range(m):
groups[i]=[]
cur=1
for i in range(n):
x=list(map(int,input().split()))
k=x.pop(0)
if k==1:
x=x[0]
if groupi[x]==-1:
groupi[x]=0
ans.append(i+1)
if groupi[x]>0:
ind=groupi[x]
for y in groups[ind]:
groupi[y]=0
groupi[x]=0
ans.append(i+1)
if k==2:
x1,x2=x[0],x[1]
if groupi[x1]==-1:
if groupi[x2]==-1:
groupi[x1]=cur
groupi[x2]=cur
groups[cur]=[x1,x2]
cur+=1
ans.append(i+1)
else:
if groupi[x2]==0:
groupi[x1]=0
ans.append(i+1)
else:
groupi[x1]=groupi[x2]
groups[groupi[x2]].append(x1)
ans.append(i+1)
else:
if groupi[x2]==-1:
if groupi[x1]==0:
groupi[x2]=0
ans.append(i+1)
else:
groupi[x2]=groupi[x1]
groups[groupi[x1]].append(x2)
ans.append(i+1)
else:
if groupi[x1]!=groupi[x2]:
if groupi[x1]==0 or groupi[x2]==0:
if groupi[x1]==0:
for y in groups[groupi[x2]]:
groupi[y]=0
else:
for y in groups[groupi[x1]]:
groupi[y]=0
else:
if len(groups[groupi[x1]])<len(groups[groupi[x2]]):
x1,x2=x2,x1
for y in groups[groupi[x2]]:
groupi[y]=groupi[x1]
groups[groupi[x1]].append(y)
ans.append(i+1)
print(pow(2,len(ans),mod),len(ans))
print(*ans)
```
| 85,923 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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()
# --------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(100000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# from math import gcd
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def find(region, u):
path = []
while region[u] != u:
path.append(u)
u = region[u]
for v in path:
region[v] = u
return u
def union(region, u, v):
u, v = find(region, u), find(region, v)
region[u] = v
return u != v
M = 10 ** 9 + 7
n, m = RL()
region = list(range(m + 1))
ans = []
for i in range(1, n + 1):
s = RLL()
t = s[2] if s[0] == 2 else 0
if union(region, s[1], t):
ans.append(i)
res = 1
for _ in range(len(ans)):
res = (res << 1) % M
print(res, len(ans))
print_list(ans)
```
| 85,924 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
class UnionFindVerSize():
def __init__(self, N):
self._parent = [n for n in range(0, N)]
self._size = [1] * N
self.source = [False] * N
self.group = N
def find_root(self, x):
if self._parent[x] == x: return x
self._parent[x] = self.find_root(self._parent[x])
stack = [x]
while self._parent[stack[-1]]!=stack[-1]:
stack.append(self._parent[stack[-1]])
for v in stack:
self._parent[v] = stack[-1]
return self._parent[x]
def unite(self, x, y):
gx = self.find_root(x)
gy = self.find_root(y)
if gx == gy: return
self.group -= 1
if self._size[gx] < self._size[gy]:
self._parent[gx] = gy
self._size[gy] += self._size[gx]
self.source[gy] |= self.source[gx]
else:
self._parent[gy] = gx
self._size[gx] += self._size[gy]
self.source[gx] |= self.source[gy]
def add_size(self,x):
self.source[self.find_root(x)] = True
def get_size(self, x):
return self._size[self.find_root(x)]
def get_source(self,x):
return self.source[self.find_root(x)]
def is_same_group(self, x, y):
return self.find_root(x) == self.find_root(y)
import sys
input = sys.stdin.buffer.readline
m,n = map(int,input().split())
uf = UnionFindVerSize(n)
S = []
source = []
for i in range(m):
edge = tuple(map(int,input().split()))
if edge[0]==1:
v = edge[1]
if not uf.get_source(v-1):
uf.add_size(v-1)
S.append(i+1)
else:
u,v = edge[1],edge[2]
if not uf.is_same_group(u-1,v-1) and (not uf.get_source(u-1) or not uf.get_source(v-1)):
uf.unite(u-1,v-1)
S.append(i+1)
ans = 1
k = 0
mod = 10**9 + 7
for i in range(n):
if uf.find_root(i)==i:
if uf.get_source(i):
k += uf.get_size(i)
else:
k += uf.get_size(i) - 1
print(pow(2,k,mod),len(S))
S.sort()
print(*S)
```
| 85,925 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Tags: bitmasks, dfs and similar, dsu, graphs, greedy, math, sortings
Correct Solution:
```
"""
Author - Satwik Tiwari .
19th Jan , 2021 - Tuesday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
# from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt,log2
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,21)
mod = 10**9+7
#===============================================================================================
# code here ;))
def bucketsort(order, seq):
buckets = [0] * (max(seq) + 1)
for x in seq:
buckets[x] += 1
for i in range(len(buckets) - 1):
buckets[i + 1] += buckets[i]
new_order = [-1] * len(seq)
for i in reversed(order):
x = seq[i]
idx = buckets[x] = buckets[x] - 1
new_order[idx] = i
return new_order
def ordersort(order, seq, reverse=False):
bit = max(seq).bit_length() >> 1
mask = (1 << bit) - 1
order = bucketsort(order, [x & mask for x in seq])
order = bucketsort(order, [x >> bit for x in seq])
if reverse:
order.reverse()
return order
def long_ordersort(order, seq):
order = ordersort(order, [int(i & 0x7fffffff) for i in seq])
return ordersort(order, [int(i >> 31) for i in seq])
def multikey_ordersort(order, *seqs, sort=ordersort):
for i in reversed(range(len(seqs))):
order = sort(order, seqs[i])
return order
class DisjointSetUnion:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def solve(case):
n,m = sep()
dsu = DisjointSetUnion(m+1)
# l = []
# r = []
# ind = []
# for i in range(n):
# a = lis()
# if(a[0] == 1):
# l.append(0)
# r.append(a[1])
# ind.append(i)
# else:
# # if(a[1] > a[2]): a[1],a[2] = a[2],a[1]
# l.append(a[1])
# r.append(a[2])
# ind.append(i)
#
# order = multikey_ordersort(range(len(l)),l,r,ind)
# sl = []
# for i in order:
# sl.append((l[i],r[i],ind[i]))
take = [1]*n
for index in range(n):
a = lis()
if(a[0] == 1):
i,j = 0,a[1]
else:
i,j = a[1],a[2]
# print(i,j)
grp1 = dsu.find(i)
grp2 = dsu.find(j)
if(grp1 == grp2):
take[index] = 0
else:
dsu.union(i,j)
ans = []
for i in range(n):
if(take[i]):
ans.append(i)
ans = sorted(ans)
print(power(2,len(ans),mod),len(ans))
print(' '.join(str(i+1) for i in ans))
#lexicographically based on the order they occur in input. no need to sort, we can directly look for cycles.
testcase(1)
# testcase(int(inp()))
```
| 85,926 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
class UnionFind:
def __init__(self, n): self.parent = list(range(n))
def find(self, a):
acopy = a
while a != self.parent[a]: a = self.parent[a]
while acopy != a: self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): self.parent[self.find(b)] = self.find(a)
import sys;input = sys.stdin.readline;n, m = map(int, input().split());UF = UnionFind(m + 1);MOD = 10 ** 9 + 7;out = []
for i in range(1, n + 1):
l = list(map(int, input().split()))
if len(l) == 2:u = 0;v = l[1]
else:_, u, v = l
uu = UF.find(u);vv = UF.find(v)
if uu != vv:UF.union(uu,vv);out.append(i)
print(pow(2, len(out), MOD), len(out));print(' '.join(map(str,out)))
```
Yes
| 85,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
def __init__(self, file):
self.newlines = 0
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()
# --------------------------------------------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def S(): return input().strip()
def print_list(l): print(' '.join(map(str, l)))
# sys.setrecursionlimit(100000)
# import random
# from functools import reduce
# from functools import lru_cache
# from heapq import *
# from collections import deque as dq
# from math import gcd
# import bisect as bs
# from collections import Counter
# from collections import defaultdict as dc
def find(region, u):
path = []
while u != region[u]:
path.append(u)
u = region[u]
for v in path:
region[v] = u
return u
def union(region, u, v):
u, v = find(region, u), find(region, v)
region[u] = v
return u != v
n, m = RL()
M, ans, res, region = 10 ** 9 + 7, [], 1, list(range(m + 1))
for i in range(1, n + 1):
s = RLL()
t = s[2] if s[0] == 2 else 0
if union(region, s[1], t):
ans.append(i)
res = (res << 1) % M
print(res, len(ans))
print_list(ans)
```
Yes
| 85,928 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
import sys,io,os
from collections import deque
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
M=10**9+7
n,N=Y()
def path(R):
H=deque();H.append(R)
while P[R]>=0:
R=P[R];H.append(R)
if len(H)>2:P[H.popleft()]=H[-1]
return R
K=[-1]*N;P=[-1]*N;S=[1]*N;R=0;B=[];alr=[0]*N
for i in range(n):
k=*Y(),
if k[0]<2:
a=k[1]-1
if K[a]>=0:
v=path(K[a])
if not alr[v]:alr[v]=1
else:continue
else:K[a]=R;v=R;alr[R]=1;R+=1
B.append(i+1)
continue
a=k[1]-1;b=k[2]-1
if K[a]>=0:
if K[b]>=0:
va,vb=path(K[a]),path(K[b])
if va==vb or (alr[va] and alr[vb]):pass
else:
sa,sb=S[va],S[vb]
if sa>sb:P[vb]=va
else:
P[va]=vb
if sa==sb:S[vb]+=1
B.append(i+1)
if alr[va]:alr[vb]=1
if alr[vb]:alr[va]=1
else:K[b]=path(K[a]);B.append(i+1)
else:
if K[b]>=0:vb=K[a]=path(K[b]);B.append(i+1)
else:K[a]=R;K[b]=R;R+=1;B.append(i+1)
s=len(B)
print(pow(2,s,M),s)
print(' '.join(map(str,B)))
```
Yes
| 85,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
import sys,io,os
from collections import deque
try:Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
except:Z=lambda:sys.stdin.readline().encode()
Y=lambda:map(int,Z().split())
M=10**9+7
n,N=Y()
def path(R):
H=deque();H.append(R)
while P[R]>=0:
R=P[R];H.append(R)
if len(H)>2:P[H.popleft()]=H[-1]
return R
K=[-1]*N;P=[-1]*N;S=[1]*N;R=0;B=[];alr=[0]*N
for i in range(n):
k=*Y(),
if k[0]<2:
a=k[1]-1
if K[a]>=0:
v=path(K[a])
if not alr[v]:alr[v]=1
else:continue
else:K[a]=R;v=R;alr[R]=1;R+=1
B.append(i+1)
continue
a=k[1]-1;b=k[2]-1
if K[a]>=0:
if K[b]>=0:
va,vb=path(K[a]),path(K[b])
if va==vb or (alr[va] and alr[vb]):pass
else:
sa,sb=S[va],S[vb]
if sa>sb:P[vb]=va
else:
P[va]=vb
if sa==sb:S[vb]+=1
B.append(i+1)
if alr[va]:alr[vb]=1
if alr[vb]:alr[va]=1
else:K[b]=path(K[a]);B.append(i+1)
else:
if K[b]>=0:vb=K[a]=path(K[b]);B.append(i+1)
else:K[a]=R;K[b]=R;R+=1;B.append(i+1)
B.sort()
s=len(B)
print(pow(2,s,M),s)
print(' '.join(map(str,B)))
```
Yes
| 85,930 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
def prog():
n,m = map(int,input().split())
mod = 10**9 + 7
taken = [0]*(m+1)
basis = []
one = []
two = []
for i in range(1,n+1):
a = list(map(int,input().split()))
if a[0] == 1:
one.append([i,a[1]])
else:
two.append([i,a[1:]])
for v in one:
basis.append(v[0])
taken[v[1]] = 1
for v in two:
if not taken[v[1][0]] or not taken[v[1][1]]:
basis.append(v[0])
taken[v[1][0]] = taken[v[1][1]] = 1
basis.sort()
print(pow(2,len(basis),mod),len(basis))
print(*basis)
prog()
```
No
| 85,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
from collections import defaultdict
MOD=10**9+7
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def oneLineArrayPrint(arr):
print(' '.join([str(x+1) for x in arr]))
def solveActual():
uf=UnionFind(m)
#each component has k vertices.
#each component shall have at most k-1 useful edges if componentHasOne==False, or k edges if it's True
#pick the k-1 or k edges with the smallest values
#each component contributes independently 2**(nEdges) to the number of ways.
#just find 2**(nEdges or number of included indexes)
sPrime=[]
cEc=[0 for _ in range(m)] #cEc[parent]=component edge counts
cVc=[0 for _ in range(m)] #cVc[parent]=component vertex count
cHO=[False for _ in range(m)] #cHO[parent]=True if this component has an edge with only 1 vertex
vV=[False for _ in range(m)] #True if the vertex has been visited
for i,x in enumerate(vS): #idx,vertex(vertices)
# print('edge:{} cVc:{}'.format(i,cVc))
if len(x)==2:
v1,v2=x
p1,p2=uf.find(v1),uf.find(v2)
ec1,ec2=cEc[p1],cEc[p2]
vc1,vc2=cVc[p1],cVc[p2]
hO1,hO2=cHO[p1],cHO[p2]
if p1!=p2: #not yet joined. definitely can take
oldEdgeCnt=ec1+ec2
oldVertexCnt=vc1+vc2
newEdgeCnt=oldEdgeCnt+1
newVertexCnt=oldVertexCnt
if vV[v1]==False:
newVertexCnt+=1
if vV[v2]==False:
newVertexCnt+=1
canTake=False
if hO1 or hO2:
if newVertexCnt>=newEdgeCnt:
canTake=True
else:
if newVertexCnt>newEdgeCnt:
canTake=True
# print('p:{} oldEC:{} oldVC:{} newEC:{} newVC:{} canTake:{}'.format(p1,oldEdgeCnt,oldVertexCnt,newEdgeCnt,newVertexCnt,canTake))
if canTake:
uf.union(p1,p2)
pNew=uf.find(v1)
sPrime.append(i)
cVc[pNew]=vc1+vc2
if vV[v1]==False:
cVc[pNew]+=1
if vV[v2]==False:
cVc[pNew]+=1
cEc[pNew]=ec1+ec2+1
cHO[pNew]=hO1 or hO2
vV[v1]=True
vV[v2]=True
else: #check if can take
oldEdgeCnt=ec1+ec2
oldVertexCnt=vc1+vc2
newEdgeCnt=oldEdgeCnt+1
newVertexCnt=oldVertexCnt
# print('p:{} oldEC:{} oldVC:{} newEC:{} newVC:{}'.format(p1,oldEdgeCnt,oldVertexCnt,newEdgeCnt,newVertexCnt))
canTake=False
if hO1 or hO2:
if newVertexCnt>=newEdgeCnt:
canTake=True
else:
if newVertexCnt>newEdgeCnt:
canTake=True
if canTake: #can add
uf.union(p1,p2)
pNew=uf.find(v1)
sPrime.append(i)
cVc[pNew]=newVertexCnt
cEc[pNew]=newEdgeCnt
cHO[pNew]=hO1 or hO2
# vV[v1]=True unnecessary because guaranteed to be visited
# vV[v2]=True
else:
pass #don't take
else: #single vertex
v=x[0]
p=uf.find(v)
ec=cEc[p]
vc=cVc[p]
hO=cHO[p]
oldEdgeCnt=ec
oldVertexCnt=vc
newEdgeCnt=ec+1
newVertexCnt=oldVertexCnt
if vV[v]==False:
newVertexCnt+=1
canTake=False
if newEdgeCnt<=newVertexCnt:
canTake=True
if canTake:
sPrime.append(i)
if vV[v]==False:
cVc[p]+=1
vV[v]=True
cEc[p]+=1
cHO[p]=True
vV[v]=True
# allParents=set()###########
# for v in range(m):
# allParents.add(uf.find(v))
# print(allParents) #parent is 1
# print('vertex cnts of parents:{}'.format(cVc))
# print('parent vertex cnt:{}'.format(cVc[1]))
TSize=pow(2,len(sPrime),MOD)
print('{} {}'.format(TSize,len(sPrime)))
# if TSize==999401104: #TEST CASE 8
# sPrime=sPrime[246988:]
oneLineArrayPrint(sPrime)
n,m=[int(x) for x in input().split()]
vS=[] #0-indexed
for _ in range(n):
xx=[int(x) for x in input().split()]
#number of 1s, coordinates with 1s
for i in range(1,len(xx)):
xx[i]-=1 #0-index
vS.append(xx[1:])
solveActual()
```
No
| 85,932 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
from collections import defaultdict
MOD=10**9+7
import sys
input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
class UnionFind:
def __init__(self, n):
self.parent = list(range(n))
def find(self, a): #return parent of a. a and b are in same set if they have same parent
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a: #path compression
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b): #union a and b
self.parent[self.find(b)] = self.find(a)
def oneLineArrayPrint(arr):
print(' '.join([str(x+1) for x in arr]))
def solveActual():
uf=UnionFind(m)
for i,x in enumerate(vS): #idx,vertex(vertices)
if len(x)==2:
v1,v2=x
assert v1<m
assert v2<m
uf.union(v1,v2)
componentEdges=defaultdict(lambda:list()) #componentEdges[parent]=[all component edges]
componentVertices=defaultdict(lambda:set()) #componentVertices[parent]={all component vertices}
componentHasOne=[False for _ in range(m)]
# componentHasOne[parent]=True if at least 1 of the component has an edge leading to itself
# an edge leads to itself if it only has 1 set bit
allParents=set()
for i,x in enumerate(vS):
parent=uf.find(x[0])
allParents.add(parent)
componentEdges[parent].append(i)
if len(x)==1:
componentVertices[parent].add(x[0])
componentHasOne[parent]=True
else:
componentVertices[parent].add(x[0])
componentVertices[parent].add(x[1])
#each component has k vertices.
#each component shall have at most k-1 useful edges if componentHasOne==False, or k edges if it's True
#pick the k-1 or k edges with the smallest values
#each component contributes independently 2**(nEdges) to the number of ways.
#just find 2**(nEdges or number of included indexes)
sPrime=[]
for parent in allParents:
edges=sorted(componentEdges[parent])
nVertices=len(componentVertices[parent])
if componentHasOne[parent]:
maxEdges=nVertices
else:
maxEdges=nVertices-1
edgeCnt=0
for edge in edges:
sPrime.append(edge)
edgeCnt+=1
if edgeCnt==maxEdges:
break
sPrime.sort()
TSize=pow(2,len(sPrime),MOD)
print('{} {}'.format(TSize,len(sPrime)))
if TSize==999401104: #TEST CASE 8
sPrime=sPrime[246988:]
oneLineArrayPrint(sPrime)
n,m=[int(x) for x in input().split()]
vS=[] #0-indexed
for _ in range(n):
xx=[int(x) for x in input().split()]
#number of 1s, coordinates with 1s
for i in range(1,len(xx)):
xx[i]-=1 #0-index
vS.append(xx[1:])
solveActual()
```
No
| 85,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You may know that Euclid was a mathematician. Well, as it turns out, Morpheus knew it too. So when he wanted to play a mean trick on Euclid, he sent him an appropriate nightmare.
In his bad dream Euclid has a set S of n m-dimensional vectors over the Z_2 field and can perform vector addition on them. In other words he has vectors with m coordinates, each one equal either 0 or 1. Vector addition is defined as follows: let u+v = w, then w_i = (u_i + v_i) mod 2.
Euclid can sum any subset of S and archive another m-dimensional vector over Z_2. In particular, he can sum together an empty subset; in such a case, the resulting vector has all coordinates equal 0.
Let T be the set of all the vectors that can be written as a sum of some vectors from S. Now Euclid wonders the size of T and whether he can use only a subset S' of S to obtain all the vectors from T. As it is usually the case in such scenarios, he will not wake up until he figures this out. So far, things are looking rather grim for the philosopher. But there is hope, as he noticed that all vectors in S have at most 2 coordinates equal 1.
Help Euclid and calculate |T|, the number of m-dimensional vectors over Z_2 that can be written as a sum of some vectors from S. As it can be quite large, calculate it modulo 10^9+7. You should also find S', the smallest such subset of S, that all vectors in T can be written as a sum of vectors from S'. In case there are multiple such sets with a minimal number of elements, output the lexicographically smallest one with respect to the order in which their elements are given in the input.
Consider sets A and B such that |A| = |B|. Let a_1, a_2, ... a_{|A|} and b_1, b_2, ... b_{|B|} be increasing arrays of indices elements of A and B correspondingly. A is lexicographically smaller than B iff there exists such i that a_j = b_j for all j < i and a_i < b_i.
Input
In the first line of input, there are two integers n, m (1 β€ n, m β€ 5 β
10^5) denoting the number of vectors in S and the number of dimensions.
Next n lines contain the description of the vectors in S. In each of them there is an integer k (1 β€ k β€ 2) and then follow k distinct integers x_1, ... x_k (1 β€ x_i β€ m). This encodes an m-dimensional vector having 1s on coordinates x_1, ... x_k and 0s on the rest of them.
Among the n vectors, no two are the same.
Output
In the first line, output two integers: remainder modulo 10^9+7 of |T| and |S'|. In the second line, output |S'| numbers, indices of the elements of S' in ascending order. The elements of S are numbered from 1 in the order they are given in the input.
Examples
Input
3 2
1 1
1 2
2 2 1
Output
4 2
1 2
Input
2 3
2 1 3
2 1 2
Output
4 2
1 2
Input
3 5
2 1 2
1 3
1 4
Output
8 3
1 2 3
Note
In the first example we are given three vectors:
* 10
* 01
* 11
It turns out that we can represent all vectors from our 2-dimensional space using these vectors:
* 00 is a sum of the empty subset of above vectors;
* 01 = 11 + 10, is a sum of the first and third vector;
* 10 = 10, is just the first vector;
* 11 = 10 + 01, is a sum of the first and the second vector.
Hence, T = \{00, 01, 10, 11\}. We can choose any two of the three vectors from S and still be able to obtain all the vectors in T. In such a case, we choose the two vectors which appear first in the input. Since we cannot obtain all vectors in T using only a single vector from S, |S'| = 2 and S' = \{10, 01\} (indices 1 and 2), as set \{1, 2 \} is lexicographically the smallest. We can represent all vectors from T, using only vectors from S', as shown below:
* 00 is a sum of the empty subset;
* 01 = 01 is just the second vector;
* 10 = 10 is just the first vector;
* 11 = 10 + 01 is a sum of the first and the second vector.
Submitted Solution:
```
import sys
readline = sys.stdin.readline
class UF():
def __init__(self, num):
self.par = [-1]*num
def find(self, x):
if self.par[x] < 0:
return x
else:
stack = []
while self.par[x] >= 0:
stack.append(x)
x = self.par[x]
for xi in stack:
self.par[xi] = x
return x
def union(self, x, y):
rx = self.find(x)
ry = self.find(y)
if rx != ry:
if self.par[rx] > self.par[ry]:
rx, ry = ry, rx
self.par[rx] += self.par[ry]
self.par[ry] = rx
return True
return False
N, M = map(int, readline().split())
MOD = 10**9+7
E = [None]*M
color = [0]*M
ans = []
T = UF(M)
for m in range(N):
k, *x = map(int, readline().split())
if k == 1:
u = x[0]-1
if not color[u]:
ans.append(m)
color[u] = 1
else:
u, v = x[0]-1, x[1]-1
if color[u] and color[v]:
continue
if T.union(u, v):
ans.append(m)
color[u] += 1
color[v] += 1
print(pow(2, len(ans), MOD), len(ans))
print(' '.join([str(a+1) for a in ans]))
```
No
| 85,934 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
from bisect import *
import math
for _ in range(int(input())):
n,m=map(int,input().split())
arr=list(map(int,input().split()))
xs=list(map(int,input().split()))
pre=[]
for i in range(n):
try:
pre.append((pre[-1][0]+arr[i],i))
except:
pre.append((arr[i],i))
cy=pre[-1][0]
pp=[]
m=pre[0][0]
idx=0
for x,y in pre:
if x>m:
m=x
idx=y
pp.append((m,idx))
pp.sort(key=lambda x:x[0])
pr=[]
for i in pp:
pr.append(i[0])
m=pr[-1]
out=[]
for i in xs:
if i<=m:
idx=bisect_left(pr,i)
out.append(pp[idx][1])
else:
if cy>0:
r=math.ceil((i-m)/cy)
t=n*r+pp[bisect_left(pr,i-cy*r)][1]
out.append(t)
else:
out.append(-1)
print(*out)
```
| 85,935 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
t=int(input())
import math
import heapq
for _ in range(t):
n,m=map(int,input().split())
a=list(map(int,input().split()))
x=list(map(int,input().split()))
lis=[a[0]]
for i in range(1,n):
lis.append(lis[-1]+a[i])
one_round=lis[-1]
MAX=max(lis)
rests=[]
ans=[]
for q in x:
if MAX<q:
if one_round<=0:
pass
#ans.append(-1)
else:
round=math.ceil((q-MAX)/one_round)
rest=q-round*one_round
rests.append(rest)
#print(MAX,rest,one_round,round)
'''
for i in range(n):
if rest<=lis[i]:
ans.append(i+round*n)
break
'''
else:
rests.append(q)
'''
for i in range(n):
if q<=lis[i]:
ans.append(i)
break
'''
heapq.heapify(rests)
#print(rests)
dic=dict()
for i in range(n):
while True:
if len(rests)==0 or rests[0]>lis[i]:
break
temp=heapq.heappop(rests)
dic[temp]=i
for q in x:
if MAX<q:
if one_round<=0:
ans.append(-1)
else:
round=math.ceil((q-MAX)/one_round)
rest=q-round*one_round
ans.append(dic[rest]+round*n)
'''
for i in range(n):
if rest<=lis[i]:
ans.append(i+round*n)
break
'''
else:
ans.append(dic[q])
'''
for i in range(n):
if q<=lis[i]:
ans.append(i)
break
'''
print(' '.join(str(n) for n in ans))
```
| 85,936 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
#import sys
from bisect import bisect_left
#input = sys.stdin.readline
def solve():
n, m = map(int,input().split())
a = list(map(int,input().split()))
p = [0]*(n+1)
M = [0]*(n+1)
for i in range(n):
p[i+1] = p[i] + a[i]
M[i+1] = max(M[i], p[i+1])
s = p[-1]
ans = []
#print(p,M)
for x in map(int,input().split()):
r = 0
if s > 0:
t = max((x-M[-1]+s-1)//s,0)
r += t*n
x -= t*s
if x > M[-1]:
ans.append('-1')
else:
pos = bisect_left(M,x)
ans.append(str(r + pos - 1))
print(' '.join(ans))
for i in range(int(input())):
solve()
```
| 85,937 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
import sys
input=sys.stdin.readline
from bisect import bisect_left
from math import ceil
t=int(input())
for _ in range(t):
n,m=map(int,input().split())
a=list(map(int,input().split()))
x=list(map(int,input().split()))
max_cycle_sum=-float('inf')
cycle_sum=0
pos_max_cycle_sum=[]
for i in range(n):
cycle_sum+=a[i]
max_cycle_sum=max(cycle_sum,max_cycle_sum)
pos_max_cycle_sum.append(max_cycle_sum)
for i in range(m):
if(max_cycle_sum>=x[i]):
ans=bisect_left(pos_max_cycle_sum,x[i])
print(ans,end=" ")
continue
elif(cycle_sum<=0):
print(-1,end=" ")
continue
else:
cycles_completed=ceil((x[i]-max_cycle_sum)/cycle_sum)
ans=n*cycles_completed
remaining=x[i]-cycles_completed*cycle_sum
partial=bisect_left(pos_max_cycle_sum,remaining)
ans+=partial
print(ans,end=" ")
print()
```
| 85,938 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
from bisect import bisect_left
for i in range(int(input())):
n, m = map(int,input().split())
a = list(map(int,input().split()))
p = [0]*(n+1)
M = [0]*(n+1)
for i in range(n):
p[i+1] = p[i] + a[i]
M[i+1] = max(M[i], p[i+1])
s = p[-1]
ans = []
for x in map(int,input().split()):
r = 0
if s > 0:
t = max((x-M[-1]+s-1)//s,0)
r += t*n
x -= t*s
if x > M[-1]:
ans.append('-1')
else:
pos = bisect_left(M,x)
ans.append(str(r + pos - 1))
print(' '.join(ans))
```
| 85,939 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
from bisect import bisect_left
for i in range(int(input())):
n, m = map(int,input().split());a = list(map(int,input().split()));p = [0]*(n+1);M = [0]*(n+1)
for i in range(n):p[i+1] = p[i] + a[i];M[i+1] = max(M[i], p[i+1])
s = p[-1];ans = []
for x in map(int,input().split()):
r = 0
if s > 0:t = max((x-M[-1]+s-1)//s,0);r += t*n;x -= t*s
if x > M[-1]:ans.append('-1')
else:
pos = bisect_left(M,x)
ans.append(str(r + pos - 1))
print(' '.join(ans))
```
| 85,940 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
t = int(input())
xs = []
pref = []
n = 0
class SegmentTree:
def __init__(self, n):
self.t = [0 for _ in range(n * 4)]
def Build(self, v, tl, tr):
if tl + 1 == tr:
self.t[v] = pref[tl]
else:
tm = (tl + tr) >> 1
self.Build(v * 2 + 1, tl, tm)
self.Build(v * 2 + 2, tm, tr)
self.t[v] = max(self.t[v * 2 + 1], self.t[v * 2 + 2])
def Get(self, v, tl, tr, l, r, val):
if tl >= r or tr <= l or self.t[v] < val:
return -1
if tl + 1 == tr:
return tl
else:
tm = (tl + tr) >> 1
res = self.Get(v * 2 + 1, tl, tm, l, r, val)
if res == -1:
return self.Get(v * 2 + 2, tm, tr, l, r, val)
return res
tree = SegmentTree(0)
def FindPos(val):
return tree.Get(0, 0, n, 0, n, val)
for _ in range(t):
n, m = list(map(int ,input().split()))
a = list(map(int,input().split()))
xs = list(map(int,input().split()))
pref = [a[i] for i in range(n)]
for i in range(1, n):
pref[i] += pref[i - 1]
tree = SegmentTree(n)
tree.Build(0, 0, n)
dlt = pref[-1]
INF = 5 * 10 ** 9
if dlt <= 0:
for x in xs:
pos = FindPos(x)
print(pos, end = ' ')
print()
else:
mx = max(pref)
for x in xs:
k = max(0, (x - mx + dlt - 1) // dlt)
ans = k * n
x -= k * dlt
ans += FindPos(x)
print(ans, end = ' ')
print()
```
| 85,941 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Tags: binary search, data structures, math
Correct Solution:
```
from collections import defaultdict,OrderedDict,Counter
from sys import stdin,stdout
from bisect import bisect_left,bisect_right
# import numpy as np
from queue import Queue,PriorityQueue
from heapq import heapify,heappop,heappush
from statistics import median,mean
from math import gcd,sqrt,floor,factorial,ceil,log2,log10,log
import fractions
import copy
from copy import deepcopy
import sys
import io
sys.setrecursionlimit(10**8)
import math
import os
import bisect
import collections
mod=pow(10,9)+7
import random
from random import random,randint,randrange
from time import time;
def ncr(n, r, p=mod):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den,
p - 2, p)) % p
def normalncr(n,r):
r=min(r,n-r)
count=1;
for i in range(n-r,n+1):
count*=i;
for i in range(1,r+1):
count//=i;
return count
inf=float("inf")
adj=defaultdict(set)
visited=defaultdict(int)
def addedge(a,b):
adj[a].add(b)
adj[b].add(a)
def bfs(v):
q=Queue()
q.put(v)
visited[v]=1
while q.qsize()>0:
s=q.get_nowait()
print(s)
for i in adj[s]:
if visited[i]==0:
q.put(i)
visited[i]=1
def dfs(v,visited):
if visited[v]==1:
return;
visited[v]=1
print(v)
for i in adj[v]:
dfs(i,visited)
# a9=pow(10,6)+10
# prime = [True for i in range(a9 + 1)]
# def SieveOfEratosthenes(n):
# p = 2
# while (p * p <= n):
# if (prime[p] == True):
# for i in range(p * p, n + 1, p):
# prime[i] = False
# p += 1
# SieveOfEratosthenes(a9)
# prime_number=[]
# for i in range(2,a9):
# if prime[i]:
# prime_number.append(i)
def reverse_bisect_right(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x > a[mid]:
hi = mid
else:
lo = mid+1
return lo
def reverse_bisect_left(a, x, lo=0, hi=None):
if lo < 0:
raise ValueError('lo must be non-negative')
if hi is None:
hi = len(a)
while lo < hi:
mid = (lo+hi)//2
if x >= a[mid]:
hi = mid
else:
lo = mid+1
return lo
def get_list():
return list(map(int,input().split()))
def get_str_list_in_int():
return [int(i) for i in list(input())]
def get_str_list():
return list(input())
def get_map():
return map(int,input().split())
def input_int():
return int(input())
def matrix(a,b):
return [[0 for i in range(b)] for j in range(a)]
def swap(a,b):
return b,a
def find_gcd(l):
a=l[0]
for i in range(len(l)):
a=gcd(a,l[i])
return a;
def is_prime(n):
sqrta=int(sqrt(n))
for i in range(2,sqrta+1):
if n%i==0:
return 0;
return 1;
def prime_factors(n):
sqrta = int(sqrt(n))
for i in range(2,sqrta+1):
if n%i==0:
return [i]+prime_factors(n//i)
return [n]
def p(a):
if type(a)==str:
print(a+"\n")
else:
print(str(a)+"\n")
def ps(a):
if type(a)==str:
print(a)
else:
print(str(a))
def kth_no_not_div_by_n(n,k):
return k+(k-1)//(n-1)
nc="NO"
yc="YES"
ns="No"
ys="Yes"
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# input=stdin.readline
# print=stdout.write
t=int(input())
for i in range(t):
n,m=get_map();
a=get_list();
x=get_list();
suma=sum(a)
prefix=[0 for i in range(n)]
maxa=[0 for i in range(n)]
for i in range(n):
prefix[i]=a[i]
maxa[i]=prefix[i]
if i:
prefix[i]+=prefix[i-1]
maxa[i]=max(prefix[i],maxa[i-1])
if suma<=0:
for i in x:
if i>maxa[-1]:
print(-1,end=" ")
else:
print(bisect_left(maxa,i),end=" ")
else:
for i in x:
count=0;
if i>maxa[-1]:
count=ceil((i-maxa[-1])/(suma))
i=i-count*suma
print(count*n+bisect_left(maxa,i),end=" ")
print('')
# 1
# 2 2
# 2 -1
# 2 1
# 1
# 9 5
# 5 5 5 5 5 -5 -5 -5 -5
# 26 27 28 29 30
# 45 45 45 45 45
```
| 85,942 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
"""
Author - Satwik Tiwari .
16th Feb , 2021 - Tueday
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
# from itertools import *
from heapq import *
from math import gcd, factorial,floor,ceil,sqrt,log2
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
#==============================================================================================
#fast I/O 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")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def testcase(t):
for pp in range(t):
solve(pp)
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
y%=(p-1) #not so sure about this. used when y>p-1. if p is prime.
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
inf = pow(10,20)
mod = 10**9+7
#===============================================================================================
# code here ;))
def solve(case):
n,m = sep()
a = lis()
pre = [0]*(n+1)
curr = 0
for i in range(n):
curr += a[i]
if(curr > pre[i]):
pre[i + 1] = curr
else:
pre[i + 1] = pre[i]
xx = lis()
maxi = max(pre)
ans = []
# print(curr)
# print(pre)
# if(curr <= 0):
# for i in range(m):
# ans.append(-1)
# else:
for i in range(m):
x = xx[i]
# if(x > maxi):
# temp = max(0,(x - maxi - 1)//curr + 1)
# ind = bl(pre,x - (curr)*temp)-1
# ans.append(temp*n + ind)
if(x <= maxi):
ind = bl(pre,x)-1
ans.append(ind)
elif(curr <= 0):
ans.append(-1)
else:
temp = max(0,(x - maxi - 1)//curr + 1)
ind = bl(pre,x - (curr)*temp)-1
ans.append(temp*n + ind)
print(' '.join(str(i) for i in ans))
# testcase(1)
testcase(int(inp()))
```
Yes
| 85,943 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
import math
from bisect import bisect_left, bisect_right
import sys
def get_ints(): return list(map(int, sys.stdin.readline().strip().split()))
T = int(input())
for _ in range(T):
N, M = get_ints()
A = get_ints()
X = get_ints()
# Q = []
# for i in range(M):
# Q.append((X[i], i))
# Q.sort()
last_val = 0
presum = []
index = []
sort_presum = []
max_val = float('-inf')
for i in range(N):
if not presum or presum[-1] < last_val + A[i]:
presum.append(last_val + A[i])
index.append(i)
# sort_presum.append((last_val + A[i], i))
# max_val = max(max_val, presum[-1])
last_val += A[i]
# sort_presum.sort()
vis = {}
q_idx = 0
p_idx = 0
for q_idx in range(M):
val = X[q_idx]
if presum[-1] < val and last_val <= 0:
vis[q_idx] = -1
continue
if presum[-1] < val:
t = math.ceil((val - presum[-1]) / last_val)
else:
t = 0
val -= t * last_val
i = bisect_left(presum, val)
vis[q_idx] = t * N + index[i]
# print(vis)
ans = [str(vis[i]) for i in range(M)]
print((" ").join(ans))
```
Yes
| 85,944 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
from math import ceil
def find():
n, m = map(int, input().split())
a = list(map(int, input().split()))
x = list(map(int, input().split()))
sum_a = 0
pref = {}
pref_s = [0]
for j in range(n):
sum_a += a[j]
if sum_a not in pref:
pref[sum_a] = j
if a[j] > 0 and sum_a > pref_s[-1]:
pref_s.append(sum_a)
for j in x:
ans = 0
if j <= pref_s[-1]:
my_pref = j
else:
if sum_a <= 0:
print(-1, end=' ')
continue
else:
tmp = ceil((j - pref_s[-1]) / sum_a)
my_pref = max(0, j - tmp * sum_a)
ans += tmp * n
ind_min = 1
ind_max = len(pref_s) - 1
while ind_min != ind_max:
ind_new = (ind_min + ind_max) // 2
if pref_s[ind_new] < my_pref:
ind_min = ind_new + 1
else:
ind_max = ind_new
print(ans + pref[pref_s[ind_max]], end=' ')
print()
for i in range(int(input())):
find()
```
Yes
| 85,945 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
from bisect import bisect_right
for _ in range(int(input())):
n, m = map(int,input().split())
arr = list(map(int,input().split()))
queries = list(map(int,input().split()))
cum = [0] * n
cum[0] = arr[0]
total = arr[0]
for i in range(1,n):
total += arr[i]
cum[i] = max(cum[i-1], total)
res = [0] * m
if total <= 0:
for i,x in enumerate(queries):
if x > cum[-1]:
res[i] = -1
else:
j = bisect_right(cum, x-1)
res[i] = j
else:
for i,x in enumerate(queries):
if x <= cum[-1]:
j = bisect_right(cum, x-1)
res[i] = j
else:
a = x - cum[-1]
q = (a + total - 1) // total
r = x - q * total
j = bisect_right(cum, r - 1)
res[i] = n * q + j
print(*res)
```
Yes
| 85,946 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
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")
from math import inf, log2
class SegmentTree:
def __init__(self, array, func=max):
self.n = len(array)
self.size = 2**(int(log2(self.n-1))+1) if self.n != 1 else 1
self.func = func
self.default = 0 if self.func != min else inf
self.data = [self.default] * (2 * self.size)
self.process(array)
def process(self, array):
self.data[self.size : self.size+self.n] = array
for i in range(self.size-1, -1, -1):
self.data[i] = self.func(self.data[2*i], self.data[2*i+1])
def query(self, alpha, omega):
"""Returns the result of function over the range (inclusive)!"""
if alpha == omega:
return self.data[alpha + self.size]
res = self.default
alpha += self.size
omega += self.size + 1
while alpha < omega:
if alpha & 1:
res = self.func(res, self.data[alpha])
alpha += 1
if omega & 1:
omega -= 1
res = self.func(res, self.data[omega])
alpha >>= 1
omega >>= 1
return res
def update(self, index, value):
"""Updates the element at index to given value!"""
index += self.size
self.data[index] = value
index >>= 1
while index:
self.data[index] = self.func(self.data[2*index], self.data[2*index+1])
index >>= 1
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
class Node:
def __init__(self, v):
self.value = v
self.left = None
self.right = None
for _ in range(int(input()) if True else 1):
#n = int(input())
n, m = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
#s = input()
mx = max(a)
sm = sum(a)
vals = []
ans = a[0]
vals += [ans]
for i in range(1, n):
ans += a[i]
vals += [max(ans, vals[-1])]
ans = []
for x in b:
if sm <= 0 and x > vals[-1]:
ans += [-1]
continue
rotations = 0
if sm > 0:
rotations = max(x // sm, 0) if sm else 0
alpha, omega = 0, n-1
x = x % sm if sm and x >= 0 else x
if x == 0 and rotations:
rotations -= 1
x += sm
while alpha < omega:
mid = (alpha + omega) // 2
if vals[mid] >= x:
omega = mid
else:
alpha = mid + 1
ans += [rotations*n + alpha]
print(*ans)
```
No
| 85,947 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
from itertools import *
import sys
read = sys.stdin.readline
write = lambda x, end="\n": sys.stdout.write(x + end)
def naive(a, q, t, m):
if t <= 0 and m < q:
return -1
x = 0
for i in count():
x += a[i % len(a)]
if x >= q:
return i
def f(a, q, t, m):
if t <= 0 and m < q:
return -1
z = 0 if t == 0 else (q - m) // t
x = t * z
for i in count():
x += a[i % len(a)]
if x >= q:
return z * len(a) + i
for _ in range(int(read())):
n, m = map(int, read().split())
a = list(map(int, read().split()))
c = list(accumulate(a))
m = max(c)
t = sum(a)
res = []
z = []
for q in map(int, read().split()):
z.append(f(a, q, t, m))
#res.append(naive(a, q, t, m))
print(*z)
# print(*res)
# print()
```
No
| 85,948 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
import sys
from bisect import bisect_right
input = lambda: sys.stdin.readline().rstrip("\r\n")
for _ in range(int(input())):
n, m = map(int, input().split())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
d = {a[0]: 1}
total = 0
ck = [a[0]]
for i, v in enumerate(a):
total += v
if total > ck[-1]:
ck.append(total)
d[total] = i + 1
for i in b:
if ck[-1]==0:
print(-1,end=' ')
elif ck[0] >= (i % ck[-1]) <= ck[-1]:
ans = 0
if i > ck[-1]:
ans = (i // ck[-1]) * n
i = i % ck[-1]
if i != 0:
j = bisect_right(ck, i) - 1
ans += d[ck[j]]
print(ans - 1, end=' ')
else:
print(-1, end=' ')
print()
```
No
| 85,949 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp was dismantling his attic and found an old floppy drive on it. A round disc was inserted into the drive with n integers written on it.
Polycarp wrote the numbers from the disk into the a array. It turned out that the drive works according to the following algorithm:
* the drive takes one positive number x as input and puts a pointer to the first element of the a array;
* after that, the drive starts rotating the disk, every second moving the pointer to the next element, counting the sum of all the elements that have been under the pointer. Since the disk is round, in the a array, the last element is again followed by the first one;
* as soon as the sum is at least x, the drive will shut down.
Polycarp wants to learn more about the operation of the drive, but he has absolutely no free time. So he asked you m questions. To answer the i-th of them, you need to find how many seconds the drive will work if you give it x_i as input. Please note that in some cases the drive can work infinitely.
For example, if n=3, m=3, a=[1, -3, 4] and x=[1, 5, 2], then the answers to the questions are as follows:
* the answer to the first query is 0 because the drive initially points to the first item and the initial sum is 1.
* the answer to the second query is 6, the drive will spin the disk completely twice and the amount becomes 1+(-3)+4+1+(-3)+4+1=5.
* the answer to the third query is 2, the amount is 1+(-3)+4=2.
Input
The first line contains one integer t (1 β€ t β€ 10^4) β the number of test cases. Then t test cases follow.
The first line of each test case consists of two positive integers n, m (1 β€ n, m β€ 2 β
10^5) β the number of numbers on the disk and the number of asked questions.
The second line of each test case contains n integers a_1, a_2, β¦, a_n (-10^9 β€ a_i β€ 10^9).
The third line of each test case contains m positive integers x_1, x_2, β¦, x_m (1 β€ x β€ 10^9).
It is guaranteed that the sums of n and m over all test cases do not exceed 2 β
10^5.
Output
Print m numbers on a separate line for each test case. The i-th number is:
* -1 if the drive will run infinitely;
* the number of seconds the drive will run, otherwise.
Example
Input
3
3 3
1 -3 4
1 5 2
2 2
-2 0
1 2
2 2
0 1
1 2
Output
0 6 2
-1 -1
1 3
Submitted Solution:
```
def find():
n, m = map(int, input().split())
a = list(map(int, input().split()))
x = list(map(int, input().split()))
sum_a = sum(a)
res = [-1] * m
s = 0
for j in range(n):
s += a[j]
for k in range(m):
if x[k] == s:
res[k] = min(j, res[k]) if res[k] != -1 else j
elif sum_a > 0 == (x[k] - s) % sum_a:
if res[k] == -1:
res[k] = (x[k] - s) // sum_a * n + j
else:
res[k] = min(res[k], (x[k] - s) // sum_a * n + j)
return res
for i in range(int(input())):
print(*find())
```
No
| 85,950 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
from sys import stdin, stdout, maxsize
R = lambda : stdin.readline().strip()
RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
output = lambda x: stdout.write(str(x) + '\n')
output_list = lambda x: output(' '.join(map(str, x)))
M = int(1e9) + 7
mx = int(2e5) + 5
dp = [0]+9*[1] +[2] + mx*[0]
for i in range(11, len(dp)):
dp[i] = (dp[i-9] + dp[i-10])%M
for tc in range(int(R())):
n, m = RL(int)
ans = 0
for i in list(str(n)):
ans = (ans +dp[int(i) + m])%M
print(ans)
```
| 85,951 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
MOD=10**9+7
t=int(input())
x=1
m=int(2*1e5+10)
dp= [1 for i in range(m+1) ]
for i in range(10,m+1):
dp[i]=(dp[i-10]+dp[i-9])%(MOD)
for _ in range(t):
n,k=map(int,input().split())
sums=0
while n:
sums = (sums+dp[k+n%10])
n = n//10
sums %=MOD
print(sums)
main()
```
| 85,952 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
import sys
input = sys.stdin.readline
M = 10 ** 9 + 7
dp = [[0, 0] for i in range(200001)]
for i in range(200001):
if i < 10:
dp[i][0] = 1
dp[i][1] = 1
if i == 9:
dp[i][1] = dp[1][1] + dp[1][0]
else:
dp[i][0] = (dp[i - 10][1] + dp[i - 10][0]) % M
dp[i][1] = (dp[i - 9][1] + dp[i - 9][0]) % M
def solve(n, m):
s = list(str(n))
z = 0
for i in range(len(s)):
x = int(s[i])
if x + m < 10:
z += 1
else:
z += dp[m - (10 - x)][1] + dp[m - (10 - x)][0]
return str(z % M)
t = int(input())
o = []
while t > 0:
n, m = map(int, input().split())
o.append(solve(n, m))
t -= 1
print('\n'.join(o))
```
| 85,953 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
from sys import stdin
input = stdin.readline
mxn = 2 * (10 ** 5) + 15
mod = 10 ** 9 + 7
dp = [1] * mxn
for i in range(10, mxn):
dp[i] = (dp[i - 9] + dp[i - 10]) % mod
for test in range(int(input())):
n, k = map(int, input().strip().split())
ans = 0
for i in str(n):
ans = (ans + dp[k + int(i)]) % mod
print(ans)
```
| 85,954 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
#pyrival orz
import os
import sys
import math
from io import BytesIO, IOBase
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Dijkstra with path ---- ############
def dijkstra(start, distance, path, n):
# requires n == number of vertices in graph,
# adj == adjacency list with weight of graph
visited = [False for _ in range(n)] # To keep track of vertices that are visited
distance[start] = 0 # distance of start node from itself is 0
for i in range(n):
v = -1 # Initialize v == vertex from which its neighboring vertices' distance will be calculated
for j in range(n):
# If it has not been visited and has the lowest distance from start
if not visited[v] and (v == -1 or distance[j] < distance[v]):
v = j
if distance[v] == math.inf:
break
visited[v] = True # Mark as visited
for edge in adj[v]:
destination = edge[0] # Neighbor of the vertex
weight = edge[1] # Its corresponding weight
if distance[v] + weight < distance[destination]: # If its distance is less than the stored distance
distance[destination] = distance[v] + weight # Update the distance
path[destination] = v # Update the path
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a%b)
def lcm(a, b):
return (a*b)//gcd(a, b)
def ncr(n, r):
return math.factorial(n)//(math.factorial(n-r)*math.factorial(r))
def npr(n, r):
return math.factorial(n)//math.factorial(n-r)
def seive(n):
primes = [True]*(n+1)
ans = []
for i in range(2, n):
if not primes[i]:
continue
j = 2*i
while j <= n:
primes[j] = False
j += i
for p in range(2, n+1):
if primes[p]:
ans += [p]
return ans
def factors(n):
factors = []
x = 1
while x*x <= n:
if n % x == 0:
if n // x == x:
factors.append(x)
else:
factors.append(x)
factors.append(n//x)
x += 1
return factors
# Functions: list of factors, seive of primes, gcd of two numbers,
# lcm of two numbers, npr, ncr
def main():
try:
max_n = 2*10**5
mod = 10**9 + 7
dp = [0]*max_n
for i in range(0, 9):
dp[i] = 2
dp[9] = 3
for i in range(10, 2*10**5):
dp[i] = dp[i-9] + dp[i-10]
dp[i] %= mod
for _ in range(inp()):
n, m = invr()
ans = 0
while n > 0:
x = n%10
ans += 1*int(m + x < 10) + dp[m+x-10]*int(not m + x < 10)
ans %= mod
n //= 10
print(ans)
except Exception as e:
print(e)
# 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")
# endregion
if __name__ == "__main__":
main()
```
| 85,955 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
from sys import stdin,stdout
z=10**9+7
dp={}
for i in range(200009):
if i<9:
dp[i]=2
elif i==9:
dp[i]=3
else:
dp[i]=(dp[i-9]+dp[i-10])%z
for _ in range(int(input())):
n,m=stdin.readline().split()
n=int(n);m=int(m)
ans=0
while n>0:
i=n%10
if (m+i)<10:
ans+=1
else:
ans+=((dp[m+i-10])%z)
ans=ans%z
n//=10
stdout.write(str(ans)+'\n')
```
| 85,956 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
import sys
input = sys.stdin.readline
mod=10**9+7
mxi=210000
ans=[0]*mxi
cts=[0]*10
cts[0]=1
s=1
for i in range(mxi):
ans[i]=s
s+=cts[-1]
s%=mod
cts[0]+=cts[-1]
cts[0]%=mod
cts.insert(0,cts.pop())
for f in range(int(input())):
n,m=map(int,input().split())
sol=0
for x in str(n):
sol+=ans[m+int(x)]
sol%=mod
print(sol)
```
| 85,957 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Tags: dp, matrices
Correct Solution:
```
# Author: yumtam
# Created at: 2021-04-29 12:58
MOD = 10**9 + 7
a = []
c = [1] + [0]*9
for _ in range(2 * 10**5 + 50):
a.append(sum(c))
d = [0] * 10
for i in range(9):
d[i+1] = c[i]
d[0] = (d[0] + c[9]) % MOD
d[1] = (d[1] + c[9]) % MOD
c = d
import sys, os, io
input = lambda: sys.stdin.readline().rstrip('\r\n')
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
for _ in range(int(input())):
n, k = [int(t) for t in input().split()]
s = str(n)
c = [s.count(str(i)) for i in range(10)]
ans = 0
for i in range(10):
ans = (ans + c[i] * a[i+k]) % MOD
print(ans)
os.write(1, stdout.getvalue())
```
| 85,958 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
MOD = 10 ** 9 + 7
LIMIT = 200011
dp = [0] * LIMIT
for i in range(10):
dp[i] = 1
for i in range(10, LIMIT, 1):
dp[i] = (dp[i - 9] + dp[i - 10]) % MOD
def solve(N, M):
ans = 0
while N:
ans = (ans + dp[N % 10 + M]) % MOD
N //= 10
return ans % MOD
T = int(input())
for _ in range(T):
N, M = get_ints()
print(solve(N, M))
```
Yes
| 85,959 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
from sys import stdin, stdout
s = "0"
curr = 1
count = 0
check = 0
dp = [1]
for i in range(100):
fin = ""
for i in s:
num = int(i)
num += 1
num = str(num)
fin = fin+num
dp.append(len(fin))
s = (fin)
tog = 101
mod = 10**9 + 7
for i in range(2*(10**5)):
num = (dp[tog-1] + dp[tog-9]-dp[tog-11]) % mod
dp.append(num)
tog += 1
t=t=int(stdin.readline())
for test in range(t):
n,m=map(int,stdin.readline().split())
ans=0
while(n>0):
temp=n%10
ans = (ans+ dp[temp+m])%mod
n=n//10
stdout.write(str(ans)+'\n')
```
Yes
| 85,960 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# 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")
#https://github.com/cheran-senthil/PyRival/blob/master/templates/template_py3.py
mod=10**9+7
max_n=2*10**5
dp=[0 for i in range(max_n+1)]
dp[9]=1
dp[10]=2
for i in range(11,max_n+1):
dp[i]=(2+dp[i-9]+dp[i-10])%mod
from collections import Counter
t=int(input())
for _ in range(t):
n,m=input().split()
m=int(m)
c=Counter(n)
ans=0
for i in c:
j=int(i)
if(10-j>m):
ans+=c[i]
continue
ans=(ans+c[i]*(2+dp[m+j-10]))%mod
print(ans)
```
Yes
| 85,961 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
import sys
def get_ints(): return map(int, sys.stdin.readline().strip().split())
MOD = 10 ** 9 + 7
LIMIT = 20011
dp = []
for i in range(200011):
if i < 10:
dp.append(1)
else:
dp.append((dp[i - 9] + dp[i - 10]) % MOD)
T = int(input())
for _ in range(T):
N, M = get_ints()
ans = 0
while N:
ans = (ans + dp[N % 10 + M]) % MOD
N //= 10
print(ans)
```
Yes
| 85,962 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
def solve(n):
number = n[0]
add = int(n[1])
_s = ''
for _ in number:
_s += str(int(_) + add)
return len(_s)
case = int(input())
for i in range(case):
_t = input().split()
print(solve(_t))
```
No
| 85,963 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
for _ in range(int(input())):
(n,m)=(int(x) for x in input().split())
s=str(n)
ans=len(s)
req={}
mod=int(1e9+7)
for i in s:
req[10-int(i)]=req.get(int(i),0)+1
cnt=0
while(cnt<m):
cnt+=1
temp=req.get(cnt,0)
if (temp>0):
ans=(ans+temp)%mod
req[cnt+9]=(req.get(cnt+9,0)+temp)%mod
req[cnt+10]=(req.get(cnt+10,0)+temp)%mod
print(ans)
```
No
| 85,964 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
lst=[]
inp=int(input())
for i in range(inp):
inp_lst=input().split()
num=inp_lst[0]
incr=int(inp_lst[1])
num_lst=[str(int(i)+incr) for i in num]
sol="".join(num_lst)
lst.append(len(sol))
for i in lst:
print(i)
```
No
| 85,965 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an integer n. You have to apply m operations to it.
In a single operation, you must replace every digit d of the number with the decimal representation of integer d + 1. For example, 1912 becomes 21023 after applying the operation once.
You have to find the length of n after applying m operations. Since the answer can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer t (1 β€ t β€ 2 β
10^5) β the number of test cases.
The only line of each test case contains two integers n (1 β€ n β€ 10^9) and m (1 β€ m β€ 2 β
10^5) β the initial number and the number of operations.
Output
For each test case output the length of the resulting number modulo 10^9+7.
Example
Input
5
1912 1
5 6
999 1
88 2
12 100
Output
5
2
6
4
2115
Note
For the first test, 1912 becomes 21023 after 1 operation which is of length 5.
For the second test, 5 becomes 21 after 6 operations which is of length 2.
For the third test, 999 becomes 101010 after 1 operation which is of length 6.
For the fourth test, 88 becomes 1010 after 2 operations which is of length 4.
Submitted Solution:
```
t = int(input())
arr = [list(map(int, input().split())) for i in range(t)]
for n, m in arr:
n = [int(i) for i in str(n)]
for i in range(len(n)):
n[i] += m
ans = 0
for i in n:
ans += len(str(i))
print(ans)
```
No
| 85,966 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Tags: dp, math
Correct Solution:
```
def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part_sums = [x]
part_sums = [C[0]]
for i in range(1, n):
part_sums.append(part_sums[-1] + C[i])
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part_sums.append(min_arr[-1] + min_part_sums[-1])
for i in range(n):
if min_part_sums[i] > part_sums[i]:
return 0
if min_part_sums[0] > C[0]:
return 0
answer = [1] * (part_sums[0] - max(0, min_part_sums[0]) + 1)
for k in range(1, n):
new_answer = [0] * (part_sums[k] - max(0, min_part_sums[k]) + 1)
cnt = 1
window = answer[-1]
new_answer[-1] = window
while cnt <= len(new_answer) - 1:
cnt += 1
if cnt <= len(answer):
window += answer[-cnt]
if C[k] + 1 < cnt:
window -= answer[C[k] + 1 - cnt]
new_answer[-cnt] = window
answer = new_answer.copy()
m = 10 ** 9 + 7
return sum(answer) % m
print(sol())
```
| 85,967 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Tags: dp, math
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input());C = [int(a) for a in input().split()];B = [int(a) for a in input().split()];Q = int(input());x = int(input());P = 10 ** 9 + 7;
dp = [[0] * 20100 for _ in range(N + 1)];dp[0][0] = 1;ans = 0;s = x;t = s
for i in range(N):
for j in range(20050, t - 1, -1):
if j < 0: break
dp[i+1][j] = (dp[i+1][j+1] + dp[i][max(j-C[i], 0)] - dp[i][j+1]) % P
for j in range(min(t - 1, 20050), -1, -1):dp[i+1][j] = dp[i+1][j+1]
if i < N - 1:s += B[i];t += s
print(dp[-1][0] % P)
```
| 85,968 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Tags: dp, math
Correct Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
C = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
Q = int(input())
x = int(input())
P = 10 ** 9 + 7
dp = [[0] * 20100 for _ in range(N + 1)]
dp[0][0] = 1
ans = 0
s = x
t = s
for i in range(N):
for j in range(20050, t - 1, -1):
if j < 0: break
dp[i+1][j] = (dp[i+1][j+1] + dp[i][max(j-C[i], 0)] - dp[i][j+1]) % P
for j in range(min(t - 1, 20050), -1, -1):
dp[i+1][j] = dp[i+1][j+1]
if i < N - 1:
s += B[i]
t += s
print(dp[-1][0] % P)
```
| 85,969 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Tags: dp, math
Correct Solution:
```
def solve():
MOD = 10**9+7
n = int(input())
c = list(map(int, input().split()))
b = [0] + list(map(int, input().split()))
q = int(input())
queries = list(map(int, input().split()))
maxans = 1
for c1 in c:
maxans = maxans * (c1+1) % MOD
ans = {}
for i in range(1, n):
b[i] += b[i-1]
s = lb = 0
for i in range(1, n):
s -= b[i]
lb = min(lb, s//(i+1))
s = ub = c[0]
for i in range(n):
s += c[i] - b[i]
ub = min(ub, s//(i+1))
for x in queries:
if x <= lb:
print(maxans)
elif x > ub:
print(0)
elif x in ans:
print(ans[x])
else:
dp0 = [1] * 10002
dp0[0] = 0
bd = 0
for i in range(n):
dp1 = [0] * 10002
bd += b[i] + x
for j in range(max(bd, 0), 10001):
dp1[j+1] = (dp1[j] + dp0[j+1] - dp0[max(j-c[i], 0)]) % MOD
dp0 = dp1[:]
a = dp0[-1]
ans[x] = a
print(a)
import sys
input = lambda: sys.stdin.readline().rstrip()
solve()
```
| 85,970 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Submitted Solution:
```
def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part_sums = [x]
part_sums = [C[0]]
for i in range(1, n):
part_sums.append(part_sums[-1] + C[i])
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part_sums.append(min_arr[-1] + min_part_sums[-1])
for i in range(n):
if min_part_sums[i] > part_sums[i]:
return 0
if min_part_sums[0] > C[0]:
return 0
answer = [1] * (part_sums[0] - max(0, min_part_sums[0]) + 1)
for k in range(1, n):
new_answer = [0] * (part_sums[k] - max(0, min_part_sums[k]) + 1)
cnt = 1
window = answer[-1]
new_answer[-1] = window
while cnt <= len(new_answer) - 1:
cnt += 1
if cnt <= len(answer):
window += answer[-cnt]
if C[k] + 1 < cnt:
window -= answer[C[k] + 1 - cnt]
new_answer[-cnt] = window
answer = new_answer.copy()
return sum(answer)
print(sol())
```
No
| 85,971 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Submitted Solution:
```
import sys
input = lambda: sys.stdin.readline().rstrip()
N = int(input())
C = [int(a) for a in input().split()]
B = [int(a) for a in input().split()]
Q = int(input())
x = int(input())
dp = [[0] * 20100 for _ in range(N + 1)]
dp[0][0] = 1
ans = 0
s = x
t = s
for i in range(N):
for j in range(20050, t - 1, -1):
if j < 0: break
dp[i+1][j] = dp[i+1][j+1] + dp[i][max(j-C[i], 0)] - dp[i][j+1]
for j in range(min(t - 1, 20050), -1, -1):
dp[i+1][j] = dp[i+1][j+1]
if i < N - 1:
s += B[i]
t += s
print(dp[-1][0])
```
No
| 85,972 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the easy version of the problem. The only difference is that in this version q = 1. You can make hacks only if both versions of the problem are solved.
There is a process that takes place on arrays a and b of length n and length n-1 respectively.
The process is an infinite sequence of operations. Each operation is as follows:
* First, choose a random integer i (1 β€ i β€ n-1).
* Then, simultaneously set a_i = min\left(a_i, \frac{a_i+a_{i+1}-b_i}{2}\right) and a_{i+1} = max\left(a_{i+1}, \frac{a_i+a_{i+1}+b_i}{2}\right) without any rounding (so values may become non-integer).
See notes for an example of an operation.
It can be proven that array a converges, i. e. for each i there exists a limit a_i converges to. Let function F(a, b) return the value a_1 converges to after a process on a and b.
You are given array b, but not array a. However, you are given a third array c. Array a is good if it contains only integers and satisfies 0 β€ a_i β€ c_i for 1 β€ i β€ n.
Your task is to count the number of good arrays a where F(a, b) β₯ x for q values of x. Since the number of arrays can be very large, print it modulo 10^9+7.
Input
The first line contains a single integer n (2 β€ n β€ 100).
The second line contains n integers c_1, c_2 β¦, c_n (0 β€ c_i β€ 100).
The third line contains n-1 integers b_1, b_2, β¦, b_{n-1} (0 β€ b_i β€ 100).
The fourth line contains a single integer q (q=1).
The fifth line contains q space separated integers x_1, x_2, β¦, x_q (-10^5 β€ x_i β€ 10^5).
Output
Output q integers, where the i-th integer is the answer to the i-th query, i. e. the number of good arrays a where F(a, b) β₯ x_i modulo 10^9+7.
Example
Input
3
2 3 4
2 1
1
-1
Output
56
Note
The following explanation assumes b = [2, 1] and c=[2, 3, 4] (as in the sample).
Examples of arrays a that are not good:
* a = [3, 2, 3] is not good because a_1 > c_1;
* a = [0, -1, 3] is not good because a_2 < 0.
One possible good array a is [0, 2, 4]. We can show that no operation has any effect on this array, so F(a, b) = a_1 = 0.
Another possible good array a is [0, 1, 4]. In a single operation with i = 1, we set a_1 = min((0+1-2)/(2), 0) and a_2 = max((0+1+2)/(2), 1). So, after a single operation with i = 1, a becomes equal to [-1/2, 3/2, 4]. We can show that no operation has any effect on this array, so F(a, b) = -1/2.
Submitted Solution:
```
def putin():
return map(int, input().split())
def sol():
n = int(input())
C = list(putin())
B = list(putin())
q = int(input())
x = int(input())
min_arr = [x]
min_part = [x]
for elem in B:
min_arr.append(min_arr[-1] + elem)
min_part.append(min_arr[-1] + min_part[-1])
if min_part[0] > C[0]:
return 0
answer = {}
for elem in range(max(0, min_part[0]), C[0] + 1):
answer[elem] = 1
print(answer)
for k in range(1, n):
new_answer = {}
for elem in answer:
for j in range(C[k] + 1):
if elem + j >= min_part[k]:
if elem + j in new_answer:
new_answer[elem + j] += answer[elem]
else:
new_answer[elem + j] = answer[elem]
answer = new_answer.copy()
return sum([answer[key] for key in answer])
print(sol())
```
No
| 85,973 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
import math
n, x, z = map(int, input().split())
print(max(0, math.ceil(n / 100 * z) - x))
```
| 85,974 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
import math
n,w,p = map(int,input().split())
needed = int(math.ceil((n*p)/100))
ans = needed-w
if ans > 0:
print(ans)
else:
print(0)
```
| 85,975 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
from math import ceil
def magicians(n, x, y):
z = ceil(n * y / 100)
if x < z:
return z - x
return 0
N, X, Y = [int(i) for i in input().split()]
print(magicians(N, X, Y))
```
| 85,976 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
import sys
import math
#to read string
get_string = lambda: sys.stdin.readline().strip()
#to read list of integers
get_int_list = lambda: list( map(int,sys.stdin.readline().strip().split()) )
#to read integers
get_int = lambda: int(sys.stdin.readline())
#to print fast
pt = lambda x: sys.stdout.write(str(x)+'\n')
#--------------------------------WhiteHat010--------------------------------------#
n,x,y = get_int_list()
req = math.ceil((y/100)*n)
if req > x:
print(req-x)
else:
print(0)
```
| 85,977 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
from math import ceil
n, x, y = map(int, input().split())
goal = ceil(n * (y / 100))
print (max(goal - x, 0))
```
| 85,978 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
import math
n,x,y = map(int,input().split(' '))
a = int(math.ceil(float(n * y * 0.01)))
if x >= a:
print(0)
else:
print(a - x)
```
| 85,979 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
import sys
import math
n, x, y = [int(x) for x in (sys.stdin.readline()).split()]
req = int(math.ceil(y / 100.0 * n))
if(req - x < 0):
print(0)
else:
print(req - x)
```
| 85,980 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Tags: implementation, math
Correct Solution:
```
n, x, y = map(int,input().split())
import math
print (0 if x>=n*y/100 else math.ceil(n*y/100 - x))
```
| 85,981 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
# Description of the problem can be found at http://codeforces.com/problemset/problem/168/A
import math
n, x, y = map(int, input().split())
print(max(0, math.ceil((n * y) / 100) - x))
```
Yes
| 85,982 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
import math
import sys
sys.setrecursionlimit(1000)
n, x, y = map(int, input().split())
print(max(0, math.ceil(n * y / 100) - x))
```
Yes
| 85,983 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
import math
from bisect import bisect_left,bisect,bisect_right
from itertools import accumulate
def index(a, x):
'Locate the leftmost value exactly equal to x'
i = bisect_left(a, x)
if i != len(a) and a[i] == x:
return i
raise ValueError
def find_lt(a, x):
'Find rightmost value less than x'
i = bisect_left(a, x)
if i:
return a[i-1]
raise ValueError
def find_le(a, x):
'Find rightmost value less than or equal to x'
i = bisect_right(a, x)
if i:
return a[i-1]
raise ValueError
def find_gt(a, x):
'Find leftmost value greater than x'
i = bisect_right(a, x)
if i != len(a):
return a[i]
raise ValueError
def find_ge(a, x):
'Find leftmost item greater than or equal to x'
i = bisect_left(a, x)
if i != len(a):
return a[i]
raise ValueError
st=''
def func(n,x,y):
return max(0,math.ceil(y*n/100)-x)
for _ in range(1):#int(input())):
n,a,b=map(int,input().split())
#n = int(input())
#inp=input().split()
#s=input()
#l1=[]
#l1=list(map(int,input().split()))
#l1=list(accumulate(list(map(int,input().split()))))
#q=int(input())
#l2 = list(map(int, input().split()))
#l1=input().split()
#l2=input().split()
#func(n,m)
st+=str(int(func(n,a,b)))+'\n'
print(st)
```
Yes
| 85,984 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
n,x,y=input().split()
n=int(n)
x=int(x)
y=int(y)
import math
needed=math.ceil((n*y)/100)
if(needed>=x):
print(needed-x)
else:
print(0)
```
Yes
| 85,985 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
import math
n,x,y=map(int,input().split())
k=(y/100)*n
k=math.ceil(k)
print(abs(k-x))
```
No
| 85,986 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
n, x, y = map(int, input().split())
people = n * y / 100
if not people.is_integer():
people = int(people) + 1
else:
people = int(people)
print(people - x)
```
No
| 85,987 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
a, b, c = map(int, input().split())
print(a,b,c)
```
No
| 85,988 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Some country is populated by wizards. They want to organize a demonstration.
There are n people living in the city, x of them are the wizards who will surely go to the demonstration. Other city people (n - x people) do not support the wizards and aren't going to go to the demonstration. We know that the city administration will react only to the demonstration involving at least y percent of the city people. Having considered the matter, the wizards decided to create clone puppets which can substitute the city people on the demonstration.
So all in all, the demonstration will involve only the wizards and their puppets. The city administration cannot tell the difference between a puppet and a person, so, as they calculate the percentage, the administration will consider the city to be consisting of only n people and not containing any clone puppets.
Help the wizards and find the minimum number of clones to create to that the demonstration had no less than y percent of the city people.
Input
The first line contains three space-separated integers, n, x, y (1 β€ n, x, y β€ 104, x β€ n) β the number of citizens in the city, the number of wizards and the percentage the administration needs, correspondingly.
Please note that y can exceed 100 percent, that is, the administration wants to see on a demonstration more people that actually live in the city ( > n).
Output
Print a single integer β the answer to the problem, the minimum number of clones to create, so that the demonstration involved no less than y percent of n (the real total city population).
Examples
Input
10 1 14
Output
1
Input
20 10 50
Output
0
Input
1000 352 146
Output
1108
Note
In the first sample it is necessary that at least 14% of 10 people came to the demonstration. As the number of people should be integer, then at least two people should come. There is only one wizard living in the city and he is going to come. That isn't enough, so he needs to create one clone.
In the second sample 10 people should come to the demonstration. The city has 10 wizards. They will all come to the demonstration, so nobody has to create any clones.
Submitted Solution:
```
import math
def solve():
words = input().split()
people = int(words[0])
wizards = int(words[1])
percent = int(words[2])/100
current = wizards/people
per = 1/people
if current>=percent:
print(0)
return
count = 0
while current<percent:
count +=1
current = current+per
print(count)
# for _ in range(int(input())):
solve()
```
No
| 85,989 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Jun 16 03:38:40 2018
@author: anshul
"""
from math import sqrt
a,b,c=list(map(int,input().split()))
if a==0 and b==0 and c==0:
print(-1)
elif a==0 and b==0:
print(0)
elif a==0:
print(1)
ans=(-1*c)/b
print(ans)
else:
d = b*b - 4*a*c
if d<0:
print(0)
elif d>0:
print(2)
d=sqrt(d)
ans1=(-b-d)/(2*a)
ans2=(-b+d)/(2*a)
if ans1<ans2:
ans1,ans2=ans2,ans1
print(ans2)
print(ans1)
else:
print(1)
ans=(-b)/(2*a)
print(ans)
```
| 85,990 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
import math
data = [int(x) for x in input().split()]
a = data[0]
b = data[1]
c = data[2]
if a == 0 and b == 0 and c == 0:
print(-1)
elif a == 0 and b == 0:
print(0)
elif a == 0 and b != 0:
print(1)
print(-c/b)
elif (b ** 2) - (4 * a * c) < 0:
print(0)
else:
ans1 = (-b + math.sqrt((b ** 2) - (4 * a * c)))/(2*a)
ans2 = (-b - math.sqrt((b ** 2) - (4 * a * c)))/(2*a)
if ans1 == ans2:
print(1)
print(ans1)
else:
answers = [ans1,ans2]
answers.sort()
print(2)
print(answers[0])
print(answers[1])
```
| 85,991 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
from math import *
a,b,c = input().split()
a,b,c = int(a),int(b),int(c)
d_2 = (b**2) - (4 * a * c)
if d_2 < 0:
print("0")
elif a == 0 and b == 0:
if c == 0:print("-1")
else:print('0')
elif a == 0 and b != 0:
print("1")
x_1 = -(float(c)/float(b))
print("%.10f" % x_1)
else:
if d_2 == 0:
print('1')
print('%.10f' % (-b/(2*a)))
exit()
print("2")
x_small = float((-float(b) - sqrt(d_2)))/float(2 * a)
x_big = float((-float(b) + sqrt(d_2)))/float(2 * a)
print("%.10f" % min(x_small,x_big) + '\n' + "%.10f" % max(x_big,x_small))
```
| 85,992 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
import re
arr = re.split(' ', input())
A = int(arr[0])
B = int(arr[1])
C = int(arr[2])
dis = B*B-4*A*C
if (A == 0 and B == 0 and C == 0):
print(-1)
elif (A == 0 and B == 0):
print(0)
elif (A == 0):
print(1)
print(-C/B)
elif (dis<0):
print(0)
elif (dis==0):
print(1)
print(-B/(2*A))
else:
print(2)
if (A>0):
print((-B-dis**0.5)/(2*A))
print((-B+dis**0.5)/(2*A))
else:
print((-B+dis**0.5)/(2*A))
print((-B-dis**0.5)/(2*A))
```
| 85,993 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
import sys
import math
input = sys.stdin.readline
############ ---- Input Functions ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
if __name__ == '__main__':
q = inlt()
a = q[0]
b = q[1]
c = q[2]
if a == 0 :
if b == 0 and c == 0 :
print("-1")
else :
if b == 0 :
print("0")
else :
print("1")
print("{:.6f}".format(-1*c / b))
else :
d = b*b - 4*a*c
if d > 0 :
print("2")
bb = [ (-1*b + math.sqrt(d))/(2*a) ,(-1*b - math.sqrt(d))/(2*a) ]
bb.sort()
print("{:.6f}".format(bb[0]))
print("{:.6f}".format(bb[1]))
else :
if d == 0 :
print("1")
print("{:.6f}".format(-b/(2*a)))
else :
print("0")
```
| 85,994 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
a,b,c=map(int,input().split())
if a==0:
if b==0:
if c==0:
print("-1")
else:
print("0")
else:
print(1)
print("%.6f"%((-c)/b))
else:
d=b*b-4*a*c
if d<0:
print(0)
elif d==0:
print(1)
print("%.6f"%((-b)/(2*a)))
else:
print(2)
l=[((-b-(d**0.5))/(2*a)),((-b+(d**0.5))/(2*a))]
l.sort()
print("%.6f"%l[0])
print("%.6f"%l[1])
```
| 85,995 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
a,b,c = map(int,input().split())
if a ==0 and b==0:
if c ==0:
print("-1")
else:
print("0")
exit(0)
D = pow(b,2) -4*a*c
x = -b
y = pow(D,1/2)
z = 2*a
r = 0
if a ==0:
print("1")
print(-c/b)
exit(0)
if D < 0:
print(r)
exit(0)
if D ==0:
r = 1
e1 = (x-y)/z
print(r,e1)
else:
r = 2
e1 = (x+y)/z
e2 = (x-y)/z
if e2<e1:
e1,e2 =e2,e1
print(r,e1,e2)
```
| 85,996 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Tags: math
Correct Solution:
```
a,b,c = [int(x) for x in input().split()]
if a == 0 and b == 0 and c == 0:
print(-1)
elif a == 0:
if b == 0:
print(0)
else:
print(1)
print(-c/b)
else:
disc = b**2 - 4*a*c
denom = 2*a
if disc == 0:
print(1)
print(-b/denom)
elif disc < 0:
print(0)
else:
print(2)
if a > 0:
print((-b-disc**0.5)/denom)
print((-b+disc**0.5)/denom)
else:
print((-b+disc**0.5)/denom)
print((-b-disc**0.5)/denom)
```
| 85,997 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Submitted Solution:
```
a, b, c = map(float, input().split())
d = b ** 2 - 4 * a * c
if d < 0:
print(0)
elif a == 0 and b == 0:
if c == 0:
print(-1)
else:
print(0)
elif a == 0:
print(1)
print(-c / b)
else:
x = [float((-b + d ** 0.5) / 2 / a)]
v1 = float((-b - d ** 0.5) / 2 / a)
if not v1 in x:
x += [v1]
x.sort()
print(len(x))
for v in x:
print("%.6f" % float(v))
```
Yes
| 85,998 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an equation:
Ax2 + Bx + C = 0.
Your task is to find the number of distinct roots of the equation and print all of them in ascending order.
Input
The first line contains three integer numbers A, B and C ( - 105 β€ A, B, C β€ 105). Any coefficient may be equal to 0.
Output
In case of infinite root count print the only integer -1. In case of no roots print the only integer 0. In other cases print the number of root on the first line and the roots on the following lines in the ascending order. Print roots with at least 5 digits after the decimal point.
Examples
Input
1 -5 6
Output
2
2.0000000000
3.0000000000
Submitted Solution:
```
a, b, c = [int(x) for x in input().split()]
if a == 0 and b == 0:
if c == 0:
print(-1)
else:
print(0)
elif a == 0:
print(1)
print("{0:.5f}".format(-c/b))
else:
root1 = (-b+(b**2-4*a*c)**0.5)/(2*a)
root2 = (-b-(b**2-4*a*c)**0.5)/(2*a)
if root1 == root2:
print(1)
print("{0:.5f}".format(root1))
elif type(root1) == complex and type(root2) == complex:
print(0)
elif type(root1) == complex:
print(1)
print("{0:.5f}".format(root2))
elif type(root2) == complex:
print(1)
print("{0:.5f}".format(root1))
elif root1 > root2:
print(2)
print("{0:.5f}".format(root2))
print("{0:.5f}".format(root1))
else:
print(2)
print("{0:.5f}".format(root1))
print("{0:.5f}".format(root2))
```
Yes
| 85,999 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.