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.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
arr = list(map(int, input().split()))
ans = 0
for i in range(14):
r = arr[i]//14
d = arr[i] % 14
c = 0
x = (i + 1) % 14
s = 0
temp2 = arr[i]
arr[i] = 0
while c < 14:
c += 1
temp = arr[x] + r
if d > 0:
temp += 1
d -= 1
x = (x + 1) % 14
s += (0 if temp % 2 else temp)
arr[i] = temp2
ans = max(ans, s)
print(ans)
```
Yes
| 107,600 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
a = list(map(int, input().split()))
m = 0
for i in range(len(a)):
ai = a[i]
giri = int(ai/14)
modulo = ai % 14
tmp = a[i]
a[i] = 0
s = 0
for j in range(len(a)):
if (a[j] + giri) % 2 == 0:
s += a[j] + giri
j = (i+1)%14
cont = 1
while cont <= modulo:
if (a[j] + giri) % 2 != 0:
s += a[j] + giri + 1
else:
s -= a[j] + giri
cont += 1
j = (j+1) % 14
a[i] = tmp
m = max(s, m)
print(m)
```
Yes
| 107,601 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
import sys
from math import gcd, sqrt
input = lambda: sys.stdin.readline().rstrip('\r\n')
lcm = lambda x, y: (x * y) // gcd(x, y)
a = list(map(int, input().split()))
index = []
for i in range(14):
if a[i] > 1:
index.append(i)
for idx in index:
r = a[idx]
a[idx] = 0
k = (idx + 1) % 14
for j in range(r):
a[k] += 1
k = (k + 1) % 14
res = 0
for i in a:
if i % 2 == 0:
res += i
print(res)
```
No
| 107,602 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
arr = list(map(int, input().split()))
max_ = max(arr)
i_max = arr.index(max_)
a = max_ % 14
for i in range(1, a+1):
arr[(i_max+i) % 14] += max_//14 +1
res = 0
for a in arr:
if a % 2 == 0:
res += a
print(res)
```
No
| 107,603 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
from sys import stdin,stdout
arr=[int(x) for x in stdin.readline().split()]
sum=0
for x in range(len(arr)):
if(not arr[x]): continue
a=arr[x]//13
s=arr[x]%13
ssum=0
for i in range(1,14):
val=(arr[(x+i)%14]+(1 if(s>0) else 0)+a) if (x+i)%14!=x else 0
ssum+=(val if(not val%2) else 0)
s-=1
sum=max(sum,ssum)
print(sum)
```
No
| 107,604 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mancala is a game famous in the Middle East. It is played on a board that consists of 14 holes.
<image>
Initially, each hole has a_i stones. When a player makes a move, he chooses a hole which contains a positive number of stones. He takes all the stones inside it and then redistributes these stones one by one in the next holes in a counter-clockwise direction.
Note that the counter-clockwise order means if the player takes the stones from hole i, he will put one stone in the (i+1)-th hole, then in the (i+2)-th, etc. If he puts a stone in the 14-th hole, the next one will be put in the first hole.
After the move, the player collects all the stones from holes that contain even number of stones. The number of stones collected by player is the score, according to Resli.
Resli is a famous Mancala player. He wants to know the maximum score he can obtain after one move.
Input
The only line contains 14 integers a_1, a_2, …, a_{14} (0 ≤ a_i ≤ 10^9) — the number of stones in each hole.
It is guaranteed that for any i (1≤ i ≤ 14) a_i is either zero or odd, and there is at least one stone in the board.
Output
Output one integer, the maximum possible score after one move.
Examples
Input
0 1 1 0 0 0 0 0 0 7 0 0 0 0
Output
4
Input
5 1 1 1 1 0 0 0 0 0 0 0 0 0
Output
8
Note
In the first test case the board after the move from the hole with 7 stones will look like 1 2 2 0 0 0 0 0 0 0 1 1 1 1. Then the player collects the even numbers and ends up with a score equal to 4.
Submitted Solution:
```
arr = list(map(int, input().split()))
from itertools import combinations
best = 0
select = list(filter(lambda x:arr[x] != 0, range(14)))
for items in range(len(select)):
for combination in combinations(select, items+1):
temp = [0] * 15
for index in combination:
element = arr[index]
temp[index] -= element
start = (index + 1) % 14
temp[start] += element
end = min(start+element, 14)
temp[start] += 1
temp[end] -= 1
element = element - (end - start)
if element:
print("asdas")
times = element // 14
temp[0] += times
temp[14] -= times
remaining = element % 14
temp[0] += 1
temp[remaining] -= 1
kk = 0
run_sum = 0
ans = 0
while kk < 14:
run_sum += temp[kk]
temp[kk] = run_sum + arr[kk]
if temp[kk] % 2 == 0:
ans += temp[kk]
kk += 1
best = max(best, ans)
print(best)
```
No
| 107,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
from sys import exit
n, k = map(int, input().split())
a = [list(map(int, input().split())) for q in range(4)]
d = [[-1, 0], [0, 1], [1, 0], [0, -1]]
x = y = -1
ans = []
def move(k):
global x, y, a
x += d[k][0]
y += d[k][1]
if a[x][y]:
ans.append([a[x][y], x - d[k][0] + 1, y - d[k][1] + 1])
a[x][y], a[x-d[k][0]][y-d[k][1]] = a[x-d[k][0]][y-d[k][1]], a[x][y]
if k == 2*n:
for q in range(n):
if a[1][q] == a[0][q]:
ans.append([a[1][q], 1, q+1])
a[1][q] = 0
break
else:
for q in range(n):
if a[2][q] == a[3][q]:
ans.append([a[2][q], 4, q+1])
a[2][q] = 0
break
else:
print(-1)
exit(0)
for q in range(1, 2*n+1):
if q in a[1]:
x1, y1 = 1, a[1].index(q)
elif q in a[2]:
x1, y1 = 2, a[2].index(q)
else:
continue
if q in a[0]:
x2, y2 = 0, a[0].index(q)
else:
x2, y2 = 3, a[3].index(q)
if 0 in a[1]:
x, y = 1, a[1].index(0)
else:
x, y = 2, a[2].index(0)
if x == x1 and x == 1:
move(2)
elif x == x1 and x == 2:
move(0)
while y < y1:
move(1)
while y > y1:
move(3)
if x1 == 1 and x2 == 3:
move(0)
x1 += 1
elif x1 == 2 and x2 == 0:
move(2)
x1 -= 1
if x1 == 1:
if y1 < y2:
move(1)
move(0)
move(3)
y1 += 1
while y1 < y2:
move(2)
move(1)
move(1)
move(0)
move(3)
y1 += 1
elif y1 > y2:
move(3)
move(0)
move(1)
y1 -= 1
while y1 > y2:
move(2)
move(3)
move(3)
move(0)
move(1)
y1 -= 1
else:
if y1 < y2:
move(1)
move(2)
move(3)
y1 += 1
while y1 < y2:
move(0)
move(1)
move(1)
move(2)
move(3)
y1 += 1
elif y1 > y2:
move(3)
move(2)
move(1)
y1 -= 1
while y1 > y2:
move(0)
move(3)
move(3)
move(2)
move(1)
y1 -= 1
ans.append([a[x1][y1], x2+1, y2+1])
a[x1][y1] = 0
print(len(ans))
for q in ans:
print(*q)
```
| 107,606 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
def main():
n, k = map(int, input().split())
a, b, c, d = (list(map(int, input().split())) for _ in 'abcd')
ss, tt, n2, res = [*b, *c[::-1]], [*a, *d[::-1]], n * 2, []
yx = [*[(2, i + 1) for i in range(n)], *[(3, i) for i in range(n, 0, -1)]]
def park():
for i, s, t, (y, x) in zip(range(n2), ss, tt, yx):
if s == t != 0:
ss[i] = 0
res.append(f'{s} {(1, 4)[y == 3]} {x}')
def rotate():
start = ss.index(0)
for i in range(start - n2, start - 1):
s = ss[i] = ss[i + 1]
if s:
y, x = yx[i]
res.append(f'{s} {y} {x}')
ss[start - 1] = 0
park()
if all(ss):
print(-1)
return
while any(ss):
rotate()
park()
print(len(res), '\n'.join(res), sep='\n')
if __name__ == '__main__':
main()
```
| 107,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
k, n = [int(x) for x in input().split()]
a = []
for i in range(4):
a.append([int(x) - 1 for x in input().split()])
pos = []
for i in range(k):
pos.append([1, i])
for i in range(k):
pos.append([2, k - i - 1])
lft = n
ans = []
for i in range(2 * k):
for j in range(2 * k):
if (a[pos[j][0]][pos[j][1]] != -1) and (a[pos[j][0]][pos[j][1]] == a[pos[j][0] ^ 1][pos[j][1]]):
lft -= 1
ans.append([a[pos[j][0]][pos[j][1]], pos[j][0] ^ 1, pos[j][1]])
a[pos[j][0]][pos[j][1]] = -1
if (lft == 0):
break
fst = -1
for j in range(2 * k):
if (a[pos[j][0]][pos[j][1]] != -1) and (a[pos[(j + 1) % (2 * k)][0]][pos[(j + 1) % (2 * k)][1]] == -1):
fst = j
break
if (fst == -1):
print(-1)
exit(0)
for j in range(2 * k - 1):
if (a[pos[(fst - j) % (2 * k)][0]][pos[(fst - j) % (2 * k)][1]] != -1):
a[pos[(fst - j + 1) % (2 * k)][0]][pos[(fst - j + 1) % (2 * k)][1]] = a[pos[(fst - j) % (2 * k)][0]][pos[(fst - j) % (2 * k)][1]]
a[pos[(fst - j) % (2 * k)][0]][pos[(fst - j) % (2 * k)][1]] = -1
ans.append([a[pos[(fst - j + 1) % (2 * k)][0]][pos[(fst - j + 1) % (2 * k)][1]], pos[(fst - j + 1) % (2 * k)][0], pos[(fst - j + 1) % (2 * k)][1]])
print(len(ans))
for i in ans:
print(' '.join([str(x + 1) for x in i]))
```
| 107,608 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
def all_parked(parked):
result = True
for p in parked:
result = result and p
return result
class CodeforcesTask995ASolution:
def __init__(self):
self.result = ''
self.n_k = []
self.parking = []
def read_input(self):
self.n_k = [int(x) for x in input().split(" ")]
for x in range(4):
self.parking.append([int(y) for y in input().split(" ")])
def process_task(self):
parked = [False for x in range(self.n_k[1])]
moves = []
for x in range(self.n_k[0]):
if self.parking[0][x] == self.parking[1][x] and self.parking[1][x]:
moves.append([self.parking[0][x], 1, x + 1])
self.parking[1][x] = 0
parked[self.parking[0][x] - 1] = True
if self.parking[3][x] == self.parking[2][x] and self.parking[3][x]:
moves.append([self.parking[3][x], 4, x + 1])
self.parking[2][x] = 0
parked[self.parking[3][x] - 1] = True
if sum([1 if not x else 0 for x in parked]) == self.n_k[1] and self.n_k[1] == self.n_k[0] * 2:
self.result = "-1"
else:
while not all_parked(parked):
moved = [False for x in range(self.n_k[0])]
#for p in self.parking:
# print(p)
#print("\n")
#print(moves)
if self.parking[1][0] and not self.parking[2][0]:
moves.append([self.parking[1][0], 3, 1])
self.parking[2][0] = self.parking[1][0]
self.parking[1][0] = 0
moved[0] = True
for x in range(1, self.n_k[0]):
if not self.parking[1][x - 1] and self.parking[1][x]:
moves.append([self.parking[1][x], 2, x])
self.parking[1][x - 1] = self.parking[1][x]
self.parking[1][x] = 0
if not self.parking[1][self.n_k[0] - 1] and self.parking[2][self.n_k[0] - 1] and not moved[self.n_k[0] - 1]:
moves.append([self.parking[2][self.n_k[0] - 1], 2, self.n_k[0]])
self.parking[1][self.n_k[0] - 1] = self.parking[2][self.n_k[0] - 1]
self.parking[2][self.n_k[0] - 1] = 0
for x in range(self.n_k[0] - 1):
if not self.parking[2][x + 1] and self.parking[2][x] and not moved[x]:
moves.append([self.parking[2][x], 3, x + 2])
self.parking[2][x + 1] = self.parking[2][x]
self.parking[2][x] = 0
moved[x + 1] = True
for x in range(self.n_k[0]):
if self.parking[0][x] == self.parking[1][x] and self.parking[1][x]:
moves.append([self.parking[0][x], 1, x + 1])
self.parking[1][x] = 0
parked[self.parking[0][x] - 1] = True
if self.parking[3][x] == self.parking[2][x] and self.parking[3][x]:
moves.append([self.parking[3][x], 4, x + 1])
self.parking[2][x] = 0
parked[self.parking[3][x] - 1] = True
self.result = "{0}\n{1}".format(len(moves), "\n".join([" ".join([str(x) for x in move]) for move in moves]))
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask995ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
```
| 107,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
n, k = map(int, input().split())
m = []
for _ in range(4):
m.extend(list(map(int, input().split())))
moves = []
ans = 0
zeros = 0
d = {1: 1, 2: 4}
def park():
#print("\n parking \n")
global ans, moves, m, zeros
zeros = 0
for i in range(n, 3 * n):
r = d[i // n]
if m[i] == 0:
zeros += 1
elif m[i] == m[(r - 1) * n + i % n]:
moves.append(f"{m[i]} {r} {i % n + 1}")
m[i] = 0
ans += 1
zeros += 1
def rotate():
#print("\n rotating \n") #
global ans, moves, m
t1 = m[2 * n]
zero_found = False
ls1 = []
ls2 = []
ll = [(n + i, 2) for i in range(n)] + [(3 * n - 1 - i, 3) for i in range(n)]
for i in ll:
if not zero_found and t1 != 0 and m[i[0]] == 0:
zero_found = True
moves.append(f"{t1} {i[1]} {i[0] % n + 1}")
ans += 1
elif t1 != 0:
if zero_found:
ls2.append(f"{t1} {i[1]} {i[0] % n + 1}")
else:
ls1.append(f"{t1} {i[1]} {i[0] % n + 1}")
ans += 1
t2 = m[i[0]]
m[i[0]] = t1
t1 = t2
#print('hey', ls1, ls2) #
ls1.reverse()
ls2.reverse()
#print('yo', ls1, ls2)
moves.extend(ls1 + ls2)
park()
if zeros == 0:
print(-1)
else:
while zeros != 2 * n:
rotate()
park()
#print(zeros) #
#print(m) #
print(ans)
for i in moves:
print(i)
'''print('original', m)
park()
print('parked', m)
rotate()
print('rotated', m)
park()
print('parked', m)'''
```
| 107,610 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
all_the_moves = []
parked = 0
n, k = map(int, input().split())
park = []
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
park += [[int(x) for x in input().split()]]
def add_move(car, r, c):
global all_the_moves
if car == 0:
return
all_the_moves += [(car, r, c)]
def cycle():
if len(park[1]) == 1:
if park[1][0] != 0:
add_move(park[1][0], 2, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
elif park[2][0] != 0:
add_move(park[2][0], 1, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
return
if 0 not in park[1]:
i = park[2].index(0)
park[2][i], park[1][i] = park[1][i], park[2][i]
add_move(park[2][i], 2, i)
i = park[1].index(0)
for j in range(i, 0, -1):
add_move(park[1][j - 1], 1, j)
park[1][j], park[1][j - 1] = park[1][j - 1], park[1][j]
add_move(park[2][0], 1, 0)
park[1][0], park[2][0] = park[2][0], park[1][0]
for j in range(n - 1):
add_move(park[2][j + 1], 2, j)
park[2][j], park[2][j + 1] = park[2][j + 1], park[2][j]
if i < n - 1:
add_move(park[1][n - 1], 2, n - 1)
park[1][n - 1], park[2][n - 1] = park[2][n - 1], park[1][n - 1]
for j in range(n - 2, i, -1):
add_move(park[1][j], 1, j + 1)
park[1][j], park[1][j + 1] = park[1][j + 1], park[1][j]
def cars_to_their_places():
global all_the_moves
global parked
for i in range(n):
if park[0][i] != 0 and park[0][i] == park[1][i]:
all_the_moves += [(park[0][i], 0, i)]
park[1][i] = 0
parked += 1
for i in range(n):
if park[3][i] != 0 and park[3][i] == park[2][i]:
all_the_moves += [(park[3][i], 3, i)]
park[2][i] = 0
parked += 1
cars_to_their_places()
if k == 2 * n and parked == 0:
print(-1)
else:
while parked < k:
cycle()
cars_to_their_places()
if len(all_the_moves) <= 2 * 10 ** 4:
print(len(all_the_moves))
for i, r, c in all_the_moves:
print(i, r + 1, c + 1)
else:
print(-1)
```
| 107,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
if __name__ == '__main__':
numbers = list(map(int, input().split()))
n = numbers[0]
k = numbers[1]
left = 0
left = k
table = []
x = 4
while x > 0:
table.append(list(map(int, input().split())))
x = x -1
moves = []
for i in range(n):
if table[1][i] == table[0][i] and table[1][i] != 0:
moves.append((table[1][i], 1, i + 1))
table[0][i] = table[1][i]
table[1][i] = 0
if table[2][i] == table[3][i] and table[2][i] != 0:
moves.append((table[2][i], 4, i + 1))
table[3][i] = table[2][i]
table[2][i] = 0
ok = 0
for i in range(n):
if table[1][i] == 0:
ok = 1
break
if table[2][i] == 0:
ok = 1
break
if ok == 0:
print(-1)
exit(0)
for i in range(20000):
if table[1][0] != 0 and table[2][0] == 0:
moves.append((table[1][0], 3, 1))
table[2][0] = table[1][0]
table[1][0] = 0
if n == 1:
continue
for j in range(1, n):
if table[1][j - 1] == 0 and table[1][j] != 0:
moves.append((table[1][j], 2, j))
table[1][j - 1] = table[1][j]
table[1][j] = 0
for j in range(n):
if table[1][j] == table[0][j] and table[1][j] != 0:
moves.append((table[1][j], 1, j + 1))
table[0][j] = table[1][j]
table[1][j] = 0
if table[2][j] == table[3][j] and table[2][j] != 0:
moves.append((table[2][j], 4, j + 1))
table[3][j] = table[2][j]
table[2][j] = 0
if table[1][n - 1] == 0 and table[2][n - 1] != 0:
moves.append((table[2][n - 1], 2, n))
table[1][n-1] = table[2][n-1]
table[2][n-1] = 0
for j in range(n - 2, -1, -1):
if table[2][j + 1] == 0 and table[2][j] != 0:
moves.append((table[2][j], 3, j + 2))
table[2][j + 1] = table[2][j]
table[2][j] = 0
for j in range(n):
if table[1][j] == table[0][j] and table[1][j] != 0:
moves.append((table[1][j], 1, j + 1))
table[0][j] = table[1][j]
table[1][j] = 0
if table[2][j] == table[3][j] and table[2][j] != 0:
moves.append((table[2][j], 4, j + 1))
table[3][j] = table[2][j]
table[2][j] = 0
if len(moves) > 20000:
print(-1)
exit(0)
print(len(moves))
# for j in range(len(moves)):
# print(moves[j])
for j in moves:
print(*j)
```
| 107,612 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Tags: constructive algorithms, implementation
Correct Solution:
```
import os,sys
n,k = list(map(int, input().split()))
p0 = list(map(int, input().split()))
b0 = list(map(int, input().split()))
b1 = list(map(int, input().split()))
p1 = list(map(int, input().split()))
ops = []
for i in range(n):
if p0[i] == 0:
p0[i] = -1
if p1[i] == 0:
p1[i] = -1
def park():
global p0, b0, b1, p1
parked = 0
for i in range(n):
if p0[i] == b0[i]:
ops.append(" ".join(map(str, (p0[i], 1, i+1))))
b0[i] = 0
parked+=1
if p1[i] == b1[i]:
ops.append(" ".join(map(str, (p1[i], 4, i+1))))
b1[i] = 0
parked+=1
return parked
def nextpos(p):
if p[0] == 0:
if p[1] < n-1:
return (0, p[1]+1)
else:
return (1, n-1)
else:
if p[1]>0:
return (1, p[1]-1)
else:
return (0,0)
def rotate():
global b0, b1, p0, p1
stpos = None
for i in range(n):
if b0[i] == 0:
stpos = (0,i)
break
if stpos is None:
for i in range(n):
if b1[i] == 0:
stpos = (1,i)
break
if stpos is None:
return False
#print('st:', stpos)
cars = []
if stpos[0] == 0:
cars = b0[:stpos[1]][::-1] + b1 + b0[stpos[1]:][::-1]
cars = list(filter(lambda x: x!=0, cars))
else:
cars = b1[stpos[1]:] + b0[::-1] + b1[:stpos[1]]
cars = list(filter(lambda x: x!=0, cars))
#print('cars:', cars)
ppos = [None] * (k+1)
for i in range(n):
if b0[i] != 0:
ppos[b0[i]] = (0, i)
if b1[i] != 0:
ppos[b1[i]] = (1, i)
#for i in range(1, k+1):
for i in cars:
if ppos[i] is not None:
np = nextpos(ppos[i])
ops.append(" ".join(map(str, (i, np[0]+2, np[1]+1))))
ppos[i] = np
b0 = [0] * n
b1 = [0] * n
for i in range(1,k+1):
if ppos[i] is not None:
if ppos[i][0] == 0:
b0[ppos[i][1]] = i
else:
b1[ppos[i][1]] = i
#print('b:', b0, b1)
return True
def checkfin():
for i in range(n):
if b0[i] != 0 or b1[i] != 0:
return False
return True
while not checkfin():
park()
if not rotate():
print(-1)
sys.exit(0)
#print(b0, b1)
print(len(ops))
print("\n".join(ops))
```
| 107,613 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
"""
http://codeforces.com/contest/996/problem/C
"""
class CarAlgorithm:
def __init__(self, n, k, parking):
self.n = n
self.k = k
self.parking = parking
self._steps = []
self._done = False
for i in range(4):
assert len(parking[i]) == n, "%s != %s" % (len(parking[i]), n)
def do(self):
"""
1) загоянем все тривиальные машины
2) ищем пробел (если нет, то нет решения)
3) для каждой машины рассчитываем минимальной путь до парковки
4) выбираем машину с минимальным расстоянием до парковки
"""
if self._done:
return self._steps
self._done = True
n, k, parking = self.n, self.k, self.parking
car_target_cells = {}
# solve trivial cars
for park_str, car_str in [(0, 1), (3, 2)]:
for i in range(n):
car_number = parking[park_str][i]
if car_number == 0:
continue
elif parking[car_str][i] == car_number:
self._move_car(parking, car_str, i, park_str, i)
else:
car_target_cells[car_number] = (park_str, i)
# car_number = parking[3][i]
# if car_number == 0:
# continue
# elif parking[2][i] == car_number:
# self.move_car(parking, 2, i, 3, i)
# else:
# car_target_cells[car_number] = (3, i)
# print(car_target_cells)
while True:
# find shortest path for all cars
# choose car with minimal shortest path
# find free cell
target_shortest_path = None
target_car_cell = None
target_dst_str, target_dst_col = None, None
free_cell = None
for j in range(1, 3):
for i in range(n):
if parking[j][i] == 0:
if not free_cell:
free_cell = j, i
else:
cur_car = parking[j][i]
target_str, target_col = car_target_cells[cur_car]
cur_shortest_path = find_path(j, i, target_str, target_col)
if target_shortest_path is None or len(cur_shortest_path) < len(target_shortest_path):
target_shortest_path = cur_shortest_path
target_car_cell = j, i
target_dst_str, target_dst_col = target_str, target_col
# if target_car_cell:
# print("choose car %s" % parking[target_car_cell[0]][target_car_cell[1]])
if target_shortest_path is None:
# car is on the road is not found
return self._steps
# print("shortest path %s" % target_shortest_path)
# move car to cell before dst cell
car_cell_str, car_cell_col = target_car_cell
for path_next_cell_str, path_next_cell_col in target_shortest_path:
if parking[path_next_cell_str][path_next_cell_col] != 0:
# move free cell to next cell from path
if not free_cell:
self._steps = -1
return self._steps
free_cell_str, free_cell_col = free_cell
# print(bool(free_cell_str == car_cell_str == path_next_cell_str))
# print(free_cell_col, car_cell_col, path_next_cell_col)
if free_cell_str == car_cell_str == path_next_cell_str and (
free_cell_col < car_cell_col < path_next_cell_col or path_next_cell_col < car_cell_col < free_cell_col
):
# .****сx or xc****.
# |_____| |_____|
# free cell can not be moved on straight line
# change free cell string
if free_cell_str == 1:
if parking[2][free_cell_col] != 0:
self._move_car(parking, 2, free_cell_col, 1, free_cell_col)
free_cell_str = 2
else: # free_cell_str == 2
if parking[1][free_cell_col] != 0:
self._move_car(parking, 1, free_cell_col, 2, free_cell_col)
free_cell_str = 1
# move free cell on horizontal straight line
free_cell_step = 1 if free_cell_col < path_next_cell_col else -1
for free_cell_next_col in range(free_cell_col + free_cell_step, path_next_cell_col + free_cell_step, free_cell_step):
if parking[free_cell_str][free_cell_next_col] != 0:
self._move_car(parking, free_cell_str, free_cell_next_col, free_cell_str, free_cell_col)
free_cell_col = free_cell_next_col
# move free cell on vertical straight line if needed
if (free_cell_str, path_next_cell_str) in [(1, 2), (2, 1)]:
self._move_car(parking, path_next_cell_str, path_next_cell_col, free_cell_str, free_cell_col)
free_cell = path_next_cell_str, path_next_cell_col
self._move_car(parking, car_cell_str, car_cell_col, path_next_cell_str, path_next_cell_col)
car_cell_str, car_cell_col = path_next_cell_str, path_next_cell_col
self._move_car(parking, car_cell_str, car_cell_col, target_dst_str, target_dst_col)
def _move_car(self, parking, from_str, from_col, to_str, to_col):
car_number = parking[from_str][from_col]
# print("%s %s %s" % (car_number, to_str, to_col))
self._steps.append((car_number, to_str+1, to_col+1))
# print("%s %s %s" % (car_number, to_str+1, to_col+1))
# print("%s %s %s %s" % (car_number, to_str+1, to_col+1, parking))
parking[to_str][to_col] = parking[from_str][from_col]
parking[from_str][from_col] = 0
class Cell:
def __init__(self, str_n: int, col_n: int):
self.str = str_n
self.col = col_n
def find_path(from_str, from_col, to_str, to_col):
"""
return internal path between from_cell and to_cell (borders are not included)
"""
str_direct = 1 if from_col < to_col else -1
path = [
(from_str, i) for i in range(
from_col + str_direct, to_col + str_direct, str_direct
)
]
if from_str == 1 and to_str == 3:
path.append((2, to_col))
elif from_str == 2 and to_str == 0:
path.append((1, to_col))
# col_direct = 1 if from_str < to_str else -1
# path.extend([
# (i, to_col) for i in range(
# from_str + col_direct, to_str + col_direct, col_direct
# )
# ])
# print(from_str, from_col, path)
return path
def do():
n, k = [int(str_i) for str_i in input().split()]
p = [
[int(str_i) for str_i in input().split()]
for _ in range(4)
]
steps = f(p)
if isinstance(steps, list):
if len(steps) > 20000:
print(-1)
else:
print(len(steps))
for s in steps:
print("%s %s %s" % s)
else:
print(steps)
def f(square: list):
assert len(square) == 4
n = len(square[0])
for s in square:
assert len(s) == n
steps = []
free_cell_str, free_cell_col = None, None
all_cars_are_parked = True
# trivial parking
for from_str, to_str in [(1, 0), (2, 3)]:
for j in range(n):
if square[from_str][j] == 0:
free_cell_str, free_cell_col = from_str, j
elif square[from_str][j] == square[to_str][j]:
move_car(steps, square, from_str, j, to_str, j)
free_cell_str, free_cell_col = from_str, j
else:
all_cars_are_parked = False
if not all_cars_are_parked and not free_cell_str and not free_cell_col:
return -1
while not all_cars_are_parked:
all_cars_are_parked = True
start_str, start_col = free_cell_str, free_cell_col
while True:
prev_str, prev_col = prev(n, free_cell_str, free_cell_col)
# print("1", prev_str, prev_col,free_cell_str, free_cell_col)
if prev_col == -1:
exit()
car_number = square[prev_str][prev_col]
# print("2", prev_str, prev_col,free_cell_str, free_cell_col)
if car_number != 0:
# move car to free cell
move_car(steps, square, prev_str, prev_col, free_cell_str, free_cell_col)
car_new_str, car_new_col = free_cell_str, free_cell_col
# check that car is opposite of his parking cell
if car_new_str == 1:
parking_str = 0
else: # car_new_str == 2
parking_str = 3
if square[parking_str][car_new_col] == car_number:
move_car(steps, square, car_new_str, car_new_col, parking_str, car_new_col)
else:
all_cars_are_parked = False
# print("3", prev_str, prev_col,free_cell_str, free_cell_col)
free_cell_str, free_cell_col = prev_str, prev_col
# print("4", prev_str, prev_col, free_cell_str, free_cell_col)
if (free_cell_str, free_cell_col) == (start_str, start_col):
break
return steps
def move_car(steps, square, from_str, from_col, to_str, to_col):
car_number = square[from_str][from_col]
# print("%s %s %s" % (car_number, to_str, to_col))
steps.append((car_number, to_str + 1, to_col + 1))
# print("%s %s %s" % (car_number, to_str+1, to_col+1))
# print("%s %s %s %s" % (car_number, to_str+1, to_col+1, parking))
square[to_str][to_col] = square[from_str][from_col]
square[from_str][from_col] = 0
def prev(n, cur_str, cur_col):
if n == 1:
return 2 if cur_str == 1 else 1, 0
elif cur_col == 0:
return 1, 0 if cur_str == 2 else 1
elif cur_col == n - 1:
return 2, n - 1 if cur_str == 1 else n - 2
else:
return cur_str, cur_col + 1 if cur_str == 1 else cur_col - 1
def test():
r = f([[1],[1],[2],[2]])
assert r == [(1,1,1), (2,4,1)], r
r = f([[1], [2], [1], [2]])
assert r == -1, r
r = f([[1,2], [2,3], [1,0], [3,0]])
assert r == [(1,3,2), (2,3,1), (3,2,1), (1,2,2), (2,3,2), (3,3,1), (3,4,1), (1,2,1), (1,1,1), (2,2,2), (2,1,2)], r
r = f([[1,2], [3,1], [0,2], [3,0]])
assert r == [(3,3,1), (3,4,1), (1,2,1), (1,1,1), (2,2,2), (2,1,2)], r
# test()
do()
```
Yes
| 107,614 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
n, k = list(map(int, input().split()))
table = []
for row in range(4):
table.append(list(map(int, input().split())))
moves = []
def make_move(start,finish):
moves.append((table[start[0]][start[1]], finish[0]+1, finish[1]+1))
table[finish[0]][finish[1]] = table[start[0]][start[1]]
table[start[0]][start[1]] = 0
def move_all_to_places():
for pos in range(n):
if (table[1][pos] == table[0][pos]) and table[1][pos]:
make_move((1,pos), (0,pos))
if (table[2][pos] == table[3][pos]) and table[2][pos]:
make_move((2,pos), (3,pos))
move_all_to_places()
found = False
for pos in range(n):
if table[1][pos] == 0:
found = True
break
if table[2][pos] == 0:
found = True
break
if not found:
print(-1)
exit()
for cnt in range(20000):
if (table[1][0] != 0) and (table[2][0] == 0) :
make_move((1,0), (2,0)) # moved down
if n == 1:
continue
for pos in range(1,n):
if (table[1][pos-1] == 0) and (table[1][pos] != 0):
make_move((1,pos), (1, pos-1))
move_all_to_places()
if (table[1][n-1] == 0) and (table[2][n-1] != 0) :
make_move((2,n-1), (1,n-1)) # moved up
for pos in range(n-2,-1, -1):
if (table[2][pos+1] == 0) and (table[2][pos] != 0):
make_move((2,pos), (2, pos+1))
move_all_to_places()
if len(moves) > 20000:
print(-1)
exit()
print(len(moves))
for m in moves:
print(*m)
```
Yes
| 107,615 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
a=[0]*4
n,k=map(int,input().split())
for i in range(4):
a[i]=list(map(int,input().split()))
for i in range(n-1,-1,-1):
a[0].append(a[3][i])
a[1].append(a[2][i])
ans=[]
def check():
global k
for i in range(2*n):
if a[0][i]==a[1][i] and a[0][i]!=0:
if i<n:
ans.append([a[1][i],0,i])
else:
ans.append([a[1][i],3,2*n-i-1])
k-=1
a[0][i]=a[1][i]=0
def fuck():
step=-1
for i in range(2*n):
if a[1][i]==0:
step=i
break
if step==-1:
return False
else:
for i in range(2*n-1):
x=(step+i)%(2*n)
y=(step+1+i)%(2*n)
if a[1][y]!=0:
a[1][x]=a[1][y]
if x==n-1 and y==n:
ans.append([a[1][y],1,n-1])
elif x==0 and y==0:
ans.append([a[1][y],2,0])
elif x<n:
ans.append([a[1][y],1,x])
else:
ans.append([a[1][y],2,2*n-x-1])
a[1][y] = 0
return True
check()
while k!=0:
if fuck()==False:
print(-1)
exit()
check()
print(len(ans))
for i in ans:
x,y,z=i
print(x,y+1,z+1)
```
Yes
| 107,616 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
#
import collections
from functools import cmp_to_key
#key=cmp_to_key(lambda x,y: 1 if x not in y else -1 )
import math
import sys
def getIntList():
return list(map(int, input().split()))
import bisect
try :
import numpy
dprint = print
dprint('debug mode')
except ModuleNotFoundError:
def dprint(*args, **kwargs):
pass
def makePair(z):
return [(z[i], z[i+1]) for i in range(0,len(z),2) ]
def memo(func):
cache={}
def wrap(*args):
if args not in cache:
cache[args]=func(*args)
return cache[args]
return wrap
@memo
def comb (n,k):
if k==0: return 1
if n==k: return 1
return comb(n-1,k-1) + comb(n-1,k)
N,K = getIntList()
z1 = getIntList()
z2 = getIntList()
z3 = getIntList()
z4= getIntList()
blank = [0 for i in range(N+2)]
zz = [ blank, [0] + z1 + [0], [0] + z2 + [0], [0] + z3 + [0], [0] + z4 + [0], blank]
res = []
def checkpark():
for x in range(2,4):
for y in range(1,N+1):
if zz[x][y] ==0: continue
if x ==2: x0 = 1
else : x0 = 4
if zz[x][y] == zz[x0][y]:
res.append( (zz[x][y], x0,y))
zz[x][y] = 0
def ifallin():
for x in range(2,4):
for y in range(1,N+1):
if zz[x][y] !=0: return False
return True
def rotate():
ex = 0
ey = 0
for x in range(2,4):
for y in range(1,N+1):
if zz[x][y] ==0:
ex = x
ey = y
break
if ex>0: break
if ex==0:
return False
tx = ex
ty = ey
def nextcircle(x,y):
if x == 2:
if y>1:
return x,y-1
return x+1,y
else:
assert x==3
if y<N:
return x,y+1
return x-1,y
tx1,ty1 = nextcircle(tx,ty)
while (tx1,ty1)!= (ex,ey) :
t = zz[tx1][ty1]
if t !=0:
res.append( (t, tx,ty) )
zz[tx][ty] = t
zz[tx1][ty1] = 0
tx,ty = tx1,ty1
tx1,ty1 = nextcircle(tx,ty)
return True
while True:
for x in range(1,5):
dprint(zz[x])
dprint()
checkpark()
ok = ifallin()
if ok:
break
ok = rotate()
if not ok:
print(-1)
sys.exit()
print(len(res))
for x in res:
print(x[0],x[1],x[2])
```
Yes
| 107,617 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
a=[0]*4
n,k=map(int,input().split())
for i in range(4):
a[i]=list(map(int,input().split()))
for i in range(n-1,-1,-1):
a[0].append(a[3][i])
a[1].append(a[2][i])
ans=[]
def check():
global k
for i in range(2*n):
if a[0][i]==a[1][i] and a[0][i]!=0:
if i<n:
ans.append([a[1][i],0,i])
else:
ans.append([a[1][i],3,2*n-i-1])
k-=1
def fuck():
step=-1
for i in range(2*n):
if a[1][i]==0:
step=i
break
if step==-1:
return False
else:
for i in range(2*n-1):
x=(step+i)%(2*n)
y=(step+1+i)%(2*n)
if a[1][y]!=0:
a[1][x]=a[1][y]
a[1][y]=0
if x==n-1 and y==n:
ans.append([a[1][y],1,n-1])
elif x==0 and y==0:
ans.append([a[1][y],2,0])
elif x<n:
ans.append([a[1][y],1,x])
else:
ans.append([a[1][y],2,2*n-x-1])
return True
check()
while k!=0:
if fuck()==False:
print(-1)
exit()
check()
print(len(ans))
for i in ans:
x,y,z=i
print(x,y+1,z+1)
```
No
| 107,618 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
n,k=map(int,input().split())
was=int(k)
m=[]
for i in range(4):
m.append(list(map(int,input().split())))
res=[]
for i in range(n):
if m[1][i] != 0:
if m[1][i] == m[0][i]:
res.append([m[1][i],1,i+1])
m[1][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if m[2][i] == m[3][i]:
res.append([m[2][i],4,i+1])
m[2][i] = 0
k-=1
if True:
while True:
for i in range(n):
if m[1][i] != 0:
if i != 0:
if m[1][i-1] == 0:
res.append([m[1][i],2,i])
m[1][i-1] = m[1][i]
m[1][i] = 0
if m[0][i-1] == m[1][i-1]:
res.append([m[1][i-1],1,i])
m[0][i-1] = m[1][i-1]
m[1][i-1] = 0
k-=1
elif i == 0:
if m[2][i] == 0:
res.append([m[1][i],3,i+1])
m[2][i] = m[1][i]
m[1][i] = 0
if m[3][i] == m[2][i]:
res.append([m[2][i],4,i+1])
m[3][i] = m[2][i]
m[2][i] = 0
k-=1
for i in range(n):
if m[2][i] != 0:
if i != n-1:
if m[2][i+1] == 0:
res.append([m[2][i],3,i+2])
m[2][i+1] = m[2][i]
m[2][i] = 0
if m[3][i+1] == m[2][i+1]:
res.append([m[2][i+1],4,i+2])
m[3][i+1] = m[2][i+1]
m[2][i+1] = 0
k-=1
else:
if m[1][i] == 0:
res.append([m[2][i],1,i+1])
m[1][i] = m[2][i]
m[2][i] = 0
if m[0][i] == m[1][i]:
res.append([m[1][i],0,i])
m[0][i]= m[1][i]
m[1][i]=0
k-=1
if k <= 0:
break
if k == was:
print(-1)
exit(0)
else:
print(-1)
exit(0)
print(len(res))
for i in res:
print(*i)
```
No
| 107,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
# -*- coding: utf-8 -*-
import bisect
import heapq
import math
import random
import sys
from collections import Counter, defaultdict
from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal
from functools import lru_cache, reduce
from itertools import combinations, combinations_with_replacement, product, permutations
sys.setrecursionlimit(10000)
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, K, S):
error_print('------')
for s in S:
error_print(s)
ans = []
for i, (p, c) in enumerate(zip(S[0], S[1])):
if c != 0 and p == c:
ans.append((c , 1, i+1))
S[1][i] = 0
for i, (p, c) in enumerate(zip(S[3], S[2])):
if c != 0 and p == c:
ans.append((c , 4, i+1))
S[2][i] = 0
while len(ans) <= 20000 and sum(S[1]) + sum(S[2]) != 0:
error_print('------')
m = len(ans)
for s in S:
error_print(s)
S1 = [c for c in S[1]]
S2 = [c for c in S[2]]
for i in range(N):
c = S[1][i]
if i == 0:
if c != 0 and S[2][0] == 0:
ans.append((c, 3, i+1))
S1[i] = 0
S2[i] = c
else:
if c != 0 and S[1][i-1] == 0:
ans.append((c, 2, i))
S1[i] = 0
S1[i-1] = c
for i in range(0, N)[::-1]:
c = S[2][i]
if i == N-1:
if c != 0 and S[1][0] == 0:
ans.append((c, 2, i+1))
S2[i] = 0
S1[i] = c
else:
if c != 0 and S[2][i+1] == 0:
ans.append((c, 3, i+2))
S2[i] = 0
S2[i+1] = c
S[1] = S1
S[2] = S2
for i, (p, c) in enumerate(zip(S[0], S[1])):
if c != 0 and p == c:
ans.append((c , 1, i+1))
S[1][i] = 0
for i, (p, c) in enumerate(zip(S[3], S[2])):
if c != 0 and p == c:
ans.append((c , 4, i+1))
S[2][i] = 0
if len(ans) == m:
break
if len(ans) > 20000:
return len(ans)
if sum(S[1]) + sum(S[2]) != 0:
return -1
error_print('------')
for s in S:
error_print(s)
return str(len(ans)) + '\n' + '\n'.join(map(lambda x: ' '.join(map(str, x)), ans))
def main():
N, K = read_int_n()
S = [read_int_n() for _ in range(4)]
print(slv(N, K, S))
if __name__ == '__main__':
main()
```
No
| 107,620 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Allen dreams of one day owning a enormous fleet of electric cars, the car of the future! He knows that this will give him a big status boost. As Allen is planning out all of the different types of cars he will own and how he will arrange them, he realizes that he has a problem.
Allen's future parking lot can be represented as a rectangle with 4 rows and n (n ≤ 50) columns of rectangular spaces, each of which can contain at most one car at any time. He imagines having k (k ≤ 2n) cars in the grid, and all the cars are initially in the second and third rows. Each of the cars also has a different designated parking space in the first or fourth row. Allen has to put the cars into corresponding parking places.
<image> Illustration to the first example.
However, since Allen would never entrust his cars to anyone else, only one car can be moved at a time. He can drive a car from a space in any of the four cardinal directions to a neighboring empty space. Furthermore, Allen can only move one of his cars into a space on the first or fourth rows if it is the car's designated parking space.
Allen knows he will be a very busy man, and will only have time to move cars at most 20000 times before he realizes that moving cars is not worth his time. Help Allen determine if he should bother parking his cars or leave it to someone less important.
Input
The first line of the input contains two space-separated integers n and k (1 ≤ n ≤ 50, 1 ≤ k ≤ 2n), representing the number of columns and the number of cars, respectively.
The next four lines will contain n integers each between 0 and k inclusive, representing the initial state of the parking lot. The rows are numbered 1 to 4 from top to bottom and the columns are numbered 1 to n from left to right.
In the first and last line, an integer 1 ≤ x ≤ k represents a parking spot assigned to car x (you can only move this car to this place), while the integer 0 represents a empty space (you can't move any car to this place).
In the second and third line, an integer 1 ≤ x ≤ k represents initial position of car x, while the integer 0 represents an empty space (you can move any car to this place).
Each x between 1 and k appears exactly once in the second and third line, and exactly once in the first and fourth line.
Output
If there is a sequence of moves that brings all of the cars to their parking spaces, with at most 20000 car moves, then print m, the number of moves, on the first line. On the following m lines, print the moves (one move per line) in the format i r c, which corresponds to Allen moving car i to the neighboring space at row r and column c.
If it is not possible for Allen to move all the cars to the correct spaces with at most 20000 car moves, print a single line with the integer -1.
Examples
Input
4 5
1 2 0 4
1 2 0 4
5 0 0 3
0 5 0 3
Output
6
1 1 1
2 1 2
4 1 4
3 4 4
5 3 2
5 4 2
Input
1 2
1
2
1
2
Output
-1
Input
1 2
1
1
2
2
Output
2
1 1 1
2 4 1
Note
In the first sample test case, all cars are in front of their spots except car 5, which is in front of the parking spot adjacent. The example shows the shortest possible sequence of moves, but any sequence of length at most 20000 will be accepted.
In the second sample test case, there is only one column, and the cars are in the wrong order, so no cars can move and the task is impossible.
Submitted Solution:
```
n, k = map(int, input().split())
grid = [
list(map(int, input().split()))
for _ in range(4)
]
possible = True
if all(c != 0 for cars in (grid[1], grid[2]) for c in cars):
if all(a != b for (a, b) in zip(grid[0], grid[1])):
if all(a != b for (a, b) in zip(grid[3], grid[2])):
possible = False
print(-1)
if possible:
while True:
# Park cars where possible
for col in range(n):
if grid[1][col] != 0 and grid[1][col] == grid[0][col]:
# Move car to space
print(grid[1][col], 1, col+1)
grid[1][col] = 0
k -= 1
if grid[2][col] != 0 and grid[2][col] == grid[3][col]:
# Move car to space
print(grid[2][col], 4, col+1)
grid[2][col] = 0
k -= 1
if k == 0:
break
# Rotate cars
row = None
col = None
while True:
if grid[2][0] != 0 and grid[1][0] == 0:
# Can rotate clockwise starting with first car in second row
row = 2
col = 0
break
if grid[1][n-1] != 0 and grid[2][n-1] == 0:
# Can rotate clockwise starting with last car in first row
row = 1
col = n-1
break
for idx in range(n-1):
if grid[1][idx] != 0 and grid[1][idx+1] == 0:
row = 1
col = idx
break
if col is not None:
break
for idx in range(n-1):
if grid[2][idx] == 0 and grid[2][idx+1] != 0:
row = 2
col = idx+1
break
break
# Rotate all cars one spot clockwise
for _ in range(k):
# Rotate car
if row == 1 and col == n-1:
#print("Move down")
print(grid[row][col], 3, n)
grid[2][col] = grid[row][col]
grid[row][col] = 0
elif row == 2 and col == 0:
#print("Move up")
print(grid[row][col], 2, 1)
grid[1][col] = grid[row][col]
grid[row][col] = 0
elif row == 2:
#print("Move left")
print(grid[row][col], row+1, col)
grid[row][col-1] = grid[row][col]
grid[row][col] = 0
else:
#print("Move right")
print(grid[row][col], row+1, col+2)
grid[row][col+1] = grid[row][col]
grid[row][col] = 0
# Go to next car
while True:
if row == 1 and col == 0:
row = 2
elif row == 2 and col == n-1:
row = 1
elif row == 2:
col += 1
else:
col -= 1
if grid[row][col] != 0:
break
```
No
| 107,621 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x,y = map(int, input().split())
print("Yes" if y <= (4*x) and y >= 2*x and y&1!=1 else "No")
```
| 107,622 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x,y=map(int,input().split())
if y>=2*x and 4*x>=y and y%2==0:
print('Yes')
else:
print('No')
```
| 107,623 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
X, Y = map(int, input().split())
if 2*X <= Y <= 4*X and Y%2 == 0:
print('Yes')
else:
print('No')
```
| 107,624 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x,y=map(int,input().split())
#x匹でy本
if y<2*x or 4*x<y or y%2==1:
print("No")
else:
print("Yes")
```
| 107,625 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x,y = map(int,input().split())
print('Yes' if x*2 <= y <= x*4 and y % 2 == 0 else 'No')
```
| 107,626 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x, y = map(int, input().split())
if x*2<=y and y<=x*4 and y%2==0:
print('Yes')
else:
print('No')
```
| 107,627 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x, y = map(int, input().split())
print("Yes" if x*2 <= y <= x*4 and y%2 == 0 else "No")
```
| 107,628 |
Provide a correct Python 3 solution for this coding contest problem.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
"Correct Solution:
```
x,y=map(int,input().split())
if y%2==0 and y/x<=4 and y/x>=2:
print("Yes")
else:
print("No")
```
| 107,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
a,b = list(map(int,input().split()))
if a*2 <= b <= a*4 and b%2 == 0:
print("Yes")
else:
print("No")
```
Yes
| 107,630 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
X,Y=map(int,input().split())
if(Y%2==0 and X*4>=Y and X*2<=Y):
print('Yes')
else:
print('No')
```
Yes
| 107,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
#b
x,y=map(int, input().split())
if x*2 <= y <=x*4 and y%2 == 0:
print("Yes")
else:
print("No")
```
Yes
| 107,632 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
a, b = map(int, input().split())
print("Yes" if b%2==0 and 2*a<=b<=4*a else "No")
```
Yes
| 107,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
X, Y = map(int, input().split())
a = "NO"
for i in range(1, X+1):
if i*2 + (X - i)*4 == Y:
a = "YES"
break
else:
continue
print(a)
```
No
| 107,634 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
X,Y = map(int, input().split())
if X == 1 and (Y == 4 or Y == 2):
print("Yes")
exit(0)
for i in range(X):
idx=i+1
if (2*idx + (X-idx)*4 == Y):
print('Yes')
exit(0)
print('No')
```
No
| 107,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
x, y = map(int, input().split())
if y >= 2*x and y <= 4*x and y % 2 == 0
print("Yes")
else:
print("No")
```
No
| 107,636 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are some animals in a garden. Each of them is a crane with two legs or a turtle with four legs.
Takahashi says: "there are X animals in total in the garden, and they have Y legs in total." Determine whether there is a combination of numbers of cranes and turtles in which this statement is correct.
Constraints
* 1 \leq X \leq 100
* 1 \leq Y \leq 100
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X Y
Output
If there is a combination of numbers of cranes and turtles in which the statement is correct, print `Yes`; otherwise, print `No`.
Examples
Input
3 8
Output
Yes
Input
2 100
Output
No
Input
1 2
Output
Yes
Submitted Solution:
```
x,y = map(int,input().split())
a = 4 * x - y
if a/2 == a//2:
print('Yes')
else:
print('No')
```
No
| 107,637 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
def i1():
return int(input())
def i2():
return [int(i) for i in input().split()]
[k,q]=i2()
d=i2()
for i in range(q):
[n,x,m]=i2()
di=[]
dz=[]
for i in d:
di.append(i%m)
if i%m==0:
dz.append(1)
else:
dz.append(0)
x=((n-1)//k)*sum(di[:k])+x%m
if (n-1)%k:
x+=sum(di[:(n-1)%k])
ans=n-1-x//m-((n-1)//k)*sum(dz[:k])
if (n-1)%k:
ans-=sum(dz[:(n-1)%k])
print(ans)
```
| 107,638 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
K, Q = map(int, input().split())
D = [int(a) for a in input().split()]
for _ in range(Q):
N, X, M = map(int, input().split())
if N <= K + 1:
A = [0] * N
A[0] = X % M
ans = 0
for i in range(N-1):
A[i+1] = (A[i] + D[i]) % M
if A[i+1] > A[i]:
ans += 1
print(ans)
continue
ans = N - 1
t = X%M
for i in range(K):
d = (D[i]-1) % M + 1
a = (N-i-2) // K + 1
t += d * a
ans -= t // M
print(ans)
```
| 107,639 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
k, q = map(int, (input().split()))
d = list(map(int, (input().split())))
for qi in range(q):
n, x, m = map(int, input().split())
last = x
eq = 0
for i in range(k):
num = ((n-1-i)+(k-1))//k
last += (d[i]%m) * num
if d[i]%m == 0: eq += num
ans = (n-1) - (last//m - x//m) - eq
print(ans)
```
| 107,640 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
K, Q = map(int, input().split())
*D, = map(int, input().split())
for q in range(Q):
n, x, m = map(int, input().split())
r = (n - 1) % K
D1r_count0 = 0
D1_count0 = 0
D1_sum = 0
D1r_sum = 0
for k in range(K):
if k < r:
if D[k] % m == 0:
D1r_count0 += 1
D1r_sum += D[k] % m
if D[k] % m == 0:
D1_count0 += 1
D1_sum += D[k] % m
cnt_0 = D1_count0 * ((n - 1) // K) + D1r_count0
a = x
# 第n-1項を求める
b = a + D1_sum * ((n - 1) // K) + D1r_sum
# 繰り上がりの回数
cnt_p = b // m - a // m
cnt_n = (n - 1) - cnt_0 - cnt_p
print(cnt_n)
```
| 107,641 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
import math
import bisect
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor
from operator import mul
from functools import reduce
import pprint
sys.setrecursionlimit(10 ** 9)
INF = 10 ** 13
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def I(): return int(sys.stdin.buffer.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): return [S() for i in range(n)]
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
mod = 1000000007
k, q = LI()
D = LI()
for _ in range(q):
n, x, m = LI()
ret = x
D_m = [d % m for d in D]
zero_or_one = list(accumulate([1 if d == 0 else 0 for d in D_m]))
Dm_acc = list(accumulate(D_m))
ret = x + (n - 1) // k * Dm_acc[-1]
zero_ret = (n - 1) // k * zero_or_one[-1]
if (n - 1) % k:
ret += Dm_acc[(n - 1) % k - 1]
zero_ret += zero_or_one[(n - 1) % k - 1]
print(n - 1 - (ret // m - x // m) - zero_ret)
```
| 107,642 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
K, Q = map(int, input().split())
D = list(map(int, input().split()))
NXM = [list(map(int, input().split())) for _ in range(Q)]
for N, X, M in NXM:
E = [d % M for d in D]
cnt0 = 0
tmp0 = 0
for e in E:
if e > 0:
cnt0 += 1
tmp0 += e
cnt = ((N - 1) // K) * cnt0
tmp = ((N - 1) // K) * tmp0
for i in range((N - 1) % K):
if E[i] > 0:
cnt += 1
tmp += E[i]
tmp += X % M
print(cnt - tmp // M)
```
| 107,643 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
K, Q = map(int, input().split())
D = list(map(int, input().split()))
NXM = [list(map(int, input().split())) for _ in range(Q)]
for N, X, M in NXM:
E = [d % M for d in D]
cnt, tmp = 0, 0
for e in E:
if e > 0:
cnt += 1
tmp += e
cnt *= ((N - 1) // K)
tmp *= ((N - 1) // K)
for i in range((N - 1) % K):
if E[i] > 0:
cnt += 1
tmp += E[i]
tmp += X % M
print(cnt - tmp // M)
```
| 107,644 |
Provide a correct Python 3 solution for this coding contest problem.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
"Correct Solution:
```
import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")
def getlist():
return list(map(int, input().split()))
#処理内容
def main():
K, Q = getlist()
D = getlist()
for _ in range(Q):
N, X, M = getlist()
X %= M
d = [0] * K
zeroCount = 0
for i in range(K):
var = D[i] % M
d[i] = var
if var == 0:
zeroCount += 1
Dsum = sum(d)
p = int((N - 1) // K)
q = (N - 1) % K
An = X + Dsum * p
# print(p, q)
# print(An)
# print(d)
zero = 0
for i in range(q):
An += d[i]
if d[i] == 0:
zero += 1
# print(X, An)
# print(zeroCount * p + zero)
# print(int(An // M) - int((X + M - 1) // M))
ans = N - 1 - (zeroCount * p + zero) - (int(An // M) - int(X // M))
print(ans)
if __name__ == '__main__':
main()
```
| 107,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
import sys
input = sys.stdin.readline
K, Q = map(int, input().split())
d = list(map(int, input().split()))
for _ in range(Q):
n, x, m = map(int, input().split())
x %= m
dq = [y % m for y in d]
for i in range(K): dq[i] += (dq[i] == 0) * m
res = (sum(dq) * ((n - 1) // K) + sum(dq[: (n - 1) % K]) + x) // m
print(n - 1 - res)
```
Yes
| 107,646 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
import sys
def main():
K, Q = map(int, input().split())
D = list(map(int, input().split()))
for _ in range(Q):
n, x, m = map(int, input().split())
md = [D[i] % m for i in range(K)]
smda = 0
mda0 = 0
for i in range((n - 1) % K):
if md[i] == 0:
mda0 += 1
smda += md[i]
smd = smda
md0 = mda0
for i in range((n - 1) % K, K):
if md[i] == 0:
md0 += 1
smd += md[i]
roop = (n - 1) // K
res = n - 1 - (x % m + smd * roop + smda) // m - md0 * roop - mda0
print(res)
main()
```
Yes
| 107,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
#!/usr/bin/env python3
import sys
debug = False
def solve(ds, n, x, m):
ds = [d % m for d in ds]
nr_loop = (n - 1) // len(ds)
lastloop_remaining = (n - 1) % len(ds)
a_n = x
cnt_zero = 0
for i in range(0, len(ds)):
dmod = ds[i] % m
a_n += (dmod) * nr_loop
if dmod == 0:
cnt_zero += nr_loop
if i < lastloop_remaining:
a_n += dmod
if dmod == 0:
cnt_zero += 1
cnt_decrease = a_n // m - x // m
return n - 1 - cnt_decrease - cnt_zero
def read_int_list(sep = " "):
return [int(s) for s in sys.stdin.readline().split(sep)]
def dprint(*args, **kwargs):
if debug:
print(*args, **kwargs)
return
def main():
k, q = read_int_list()
d = read_int_list()
for _ in range(0, q):
n, x, m = read_int_list()
print(str(solve(d, n, x, m)))
if __name__ == "__main__":
main()
```
Yes
| 107,648 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
def f_modularness():
K, Q = [int(i) for i in input().split()]
D = [int(i) for i in input().split()]
Queries = [[int(i) for i in input().split()] for j in range(Q)]
def divceil(a, b):
return (a + b - 1) // b
ans = []
for n, x, m in Queries:
last, eq = x, 0 # 末項、D_i % m == 0 となる D_i の数
for i,d in enumerate(D):
num = divceil(n - 1 - i, K) # D_i を足すことは何回起きるか?
last += (d % m) * num
if d % m == 0:
eq += num
ans.append((n - 1) - (last // m - x // m) - eq)
return '\n'.join(map(str, ans))
print(f_modularness())
```
Yes
| 107,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
#!/usr/bin/env python3
import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
sys.setrecursionlimit(2147483647)
from heapq import heappush, heappop,heappushpop
from collections import defaultdict
from itertools import accumulate
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10**9 + 7
inf = float('inf')
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
k,q = LI()
d = LI()
nxm = [LI() for _ in range(q)]
for n,x,m in nxm:
e = list(map(lambda x:x%m,d))
zero = e.count(0)
zero = zero*((n-1)//k)
for i in range((n-1)%k+1):
if e[i] == 0:
zero += 1
f = list(accumulate(e))
s = f[-1] * ((n-1)//k)
if (n-1)%k != 0:
s += f[(n-1)%k-1]
tmp = (s+x%m)//m
print(n-1-zero-tmp)
```
No
| 107,650 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
import numpy as np
k, q = map(int, input().split())
d = np.array(input().split(), dtype=np.int)
for _ in range(q):
n, x, m = map(int, input().split())
quot = (n-1) // k
rest = (n-1) % k
dmod = d % m
same = (k - dmod.count_nonzero()) * quot + rest - dmod[:rest].count_nonzero()
a_last = x % m + dmod.sum() * quot + dmod[:rest].sum()
beyond = a_last // m
print(n - 1 - same - beyond)
```
No
| 107,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
k, q = map(int, input().split())
d = list(map(int, input().split()))
nxm = [map(int, input().split()) for _ in range(q)]
for n, x, m in nxm:
dd = [e % m for e in d]
ans = n - 1
divq, divr = divmod(n - 1, k)
dd_r = dd[:divr]
ans -= dd.count(0) * divq
ans -= dd_r.count(0)
last = x + sum(dd) * divq + sum(dd_r)
ans -= last // m - x // m
print(ans)
```
No
| 107,652 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a sequence of k numbers: d_0,d_1,...,d_{k - 1}.
Process the following q queries in order:
* The i-th query contains three integers n_i, x_i, and m_i. Let a_0,a_1,...,a_{n_i - 1} be the following sequence of n_i numbers: \begin{eqnarray} a_j = \begin{cases} x_i & ( j = 0 ) \\\ a_{j - 1} + d_{(j - 1)~\textrm{mod}~k} & ( 0 < j \leq n_i - 1 ) \end{cases}\end{eqnarray} Print the number of j~(0 \leq j < n_i - 1) such that (a_j~\textrm{mod}~m_i) < (a_{j + 1}~\textrm{mod}~m_i).
Here (y~\textrm{mod}~z) denotes the remainder of y divided by z, for two integers y and z~(z > 0).
Constraints
* All values in input are integers.
* 1 \leq k, q \leq 5000
* 0 \leq d_i \leq 10^9
* 2 \leq n_i \leq 10^9
* 0 \leq x_i \leq 10^9
* 2 \leq m_i \leq 10^9
Input
Input is given from Standard Input in the following format:
k q
d_0 d_1 ... d_{k - 1}
n_1 x_1 m_1
n_2 x_2 m_2
:
n_q x_q m_q
Output
Print q lines.
The i-th line should contain the response to the i-th query.
Examples
Input
3 1
3 1 4
5 3 2
Output
1
Input
7 3
27 18 28 18 28 46 1000000000
1000000000 1 7
1000000000 2 10
1000000000 3 12
Output
224489796
214285714
559523809
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
k,q=map(int,readline().split())
D=list(map(int,readline().split()))
NXM = map(int, read().split())
NXM=iter(NXM)
NXM=zip(NXM,NXM,NXM)
for n,x,m in NXM:
tmpD=list(map(lambda x:x%m,D))
SD=[0]+tmpD
n-=1
for i in range(1,k):
SD[i+1]+=SD[i]
x=x%m
x+=SD[-1]*(n//k)
x+=SD[n%k]
count=tmpD.count(0)*(n//k)
count+=tmpD[:n%k].count(0)
ans=n-x//m-count
print(ans)
```
No
| 107,653 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
input = sys.stdin.readline
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
mod=998244353
N=I()
A=LI()
MA=max(A)
x=[0]*(MA+1)
#数列x[i]はi*(iの個数)
for i in range(N):
x[A[i]]+=A[i]
#print(x)
#上位集合のゼータ変換
for k in range(1,MA+1):
for s in range(k*2,MA+1,k):#sが2kからkずつ増える=>sはkの倍数(自分自身を数えないため,2kから)
x[k]=(x[k]+x[s])%mod
#print(x)
#この段階でx[i]はiを約数に持つやつの和(個数も加味している)
#積演算
for i in range(MA+1):
x[i]=(x[i]*x[i])%mod
#print(x)
#メビウス変換で戻す
for k in range(MA,0,-1):
for s in range(k*2,MA+1,k):
x[k]=(x[k]-x[s])%mod
#この段階でx[i]はiをgcdに持つもの同士をかけたものの和
#print(x)
#gcdでわる
ans=0
for i in range(1,MA+1):
if x[i]!=0:
x[i]=(x[i]*pow(i,mod-2,mod))%mod
ans=(ans+x[i])%mod
#この段階でx[i]はiをgcdに持つもの同士のlcaの和
#print(x)
ans=(ans-sum(A))%mod
#A[i],A[i]の組を除去する.A[i]動詞のくみはlcaがA[i]になる
"""
ans=(ans*pow(2,mod-2,mod))%mod#A[i]*A[j] と A[j]*A[i]の被り除去
print(pow(2,mod-2,mod))=499122177
"""
ans=(ans*499122177)%mod
print(ans)
main()
```
| 107,654 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
MOD = 998244353
max_a = max(a)
c = [0] * (max_a + 1)
for i in range(1, max_a + 1):
c[i] = pow(i, MOD - 2, MOD)
for i in range(1, max_a):
j = i
while True:
j += i
if j <= max_a:
c[j] -= c[i]
c[j] %= MOD
else:
break
cnt = [0] * (max_a + 1)
for i in range(n):
cnt[a[i]] += 1
ans = 0
for i in range(1, max_a + 1):
tmp0 = 0
tmp1 = 0
j = i
while True:
if j <= max_a:
tmp0 += cnt[j] * j
tmp1 += cnt[j] * (j ** 2)
else:
break
j += i
tmp0 *= tmp0
ans += (tmp0 - tmp1) * c[i]
ans %= MOD
print((ans * pow(2, MOD - 2, MOD)) % MOD)
```
| 107,655 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
readline = sys.stdin.readline
MOD = 998244353
N = int(readline())
A = list(map(int, readline().split()))
mA = max(A) + 1
T = [0]*mA
i2 = pow(2, MOD-2, MOD)
table = [0]*mA
table2 = [0]*mA
for a in A:
table[a] = (table[a] + a)%MOD
table2[a] = (table2[a] + a*a)%MOD
prime = [True]*mA
for p in range(2, mA):
if not prime[p]:
continue
for k in range((mA-1)//p, 0, -1):
table[k] = (table[k] + table[k*p])%MOD
table2[k] = (table2[k] + table2[k*p])%MOD
prime[k*p] = False
T = [(x1*x1-x2)*i2%MOD for x1, x2 in zip(table, table2)]
ans = 0
coeff = [0]*mA
for i in range(1, mA):
k = T[i]
l = - coeff[i] + pow(i, MOD-2, MOD)
ans = (ans+l*k)%MOD
for j in range(2*i, mA, i):
coeff[j] = (coeff[j] + l)%MOD
print(ans)
```
| 107,656 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=998244353
input=lambda:sys.stdin.readline().rstrip()
class modfact(object):
def __init__(self,n):
fact=[1]*(n+1); invfact=[1]*(n+1)
for i in range(1,n+1): fact[i]=i*fact[i-1]%MOD
invfact[n]=pow(fact[n],MOD-2,MOD)
for i in range(n-1,-1,-1): invfact[i]=invfact[i+1]*(i+1)%MOD
self.__fact=fact; self.__invfact=invfact
def inv(self,n):
assert(n>0)
return self.__fact[n-1]*self.__invfact[n]%MOD
def fact(self,n):
return self.__fact[n]
def invfact(self,n):
return self.__invfact[n]
def comb(self,n,k):
if(k<0 or n<k): return 0
return self.__fact[n]*self.__invfact[k]*self.__invfact[n-k]%MOD
def perm(self,n,k):
if(k<0 or n<k): return 0
self.__fact[n]*self.__invfact[k]%MOD
def prime(n):
if n<=1: return []
S=[1]*(n+1)
S[0]=0; S[1]=0
for i in range(2,n):
if(S[i]==0): continue
for j in range(2*i,n+1,i): S[j]=0
return [p for p in range(n+1) if(S[p])]
def resolve():
n=int(input())
A=list(map(int,input().split()))
V=max(A)
C=[0]*(V+1)
for a in A: C[a]+=1
P=prime(V)
W=[1]*(V+1)
for p in P:
for i in range(p,V+1,p):
W[i]*=(1-p)
mf=modfact(V)
for i in range(1,V+1):
W[i]=(W[i]*mf.inv(i))%MOD
ans=0
for d in range(1,V+1):
s=0 # 和(後に2乗する)
t=0 # 2乗の和
for i in range(d,V+1,d):
s+=i*C[i]
t+=(i**2)*C[i]
ans+=W[d]*(s**2-t)//2
ans%=MOD
print(ans)
resolve()
```
| 107,657 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
N = int(input())
A = list(map(int, input().split()))
zeta = [0] * (max(A) + 1)
mod = 998244353
res = 0
for a in A:
zeta[a] += a
for i in range(1, len(zeta)):
for j in range(2 * i, len(zeta), i):
zeta[i] += zeta[j]
for i in range(1, len(zeta)):
zeta[i] *= zeta[i]
for i in range(len(zeta) - 1, 0, -1):
for j in range(2 * i, len(zeta), i):
zeta[i] -= zeta[j]
for a in A:
zeta[a] -= a ** 2
for i in range(1, len(zeta)):
zeta[i] //= 2
for i in range(1, len(zeta)):
zeta[i] //= i
res = (res + zeta[i]) % mod
print(res)
```
| 107,658 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
N=int(input());A=list(map(int, input().split()));z=[0]*(max(A)+1);m=998244353;r=0
for a in A:z[a]+=a
for i in range(1,len(z)):
for j in range(2*i,len(z),i):z[i]+=z[j]
for i in range(1,len(z)):z[i]*=z[i]
for i in range(len(z)-1,0,-1):
for j in range(2*i,len(z),i):z[i]-=z[j]
for a in A:z[a]-=a**2
for i in range(1,len(z)):
z[i]//=i*2;r=(r+z[i])%m
print(r)
```
| 107,659 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
import sys
readline = sys.stdin.readline
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
def primes(n):
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False
for i in range(2, int((n+1)**0.5)+1):
if is_prime[i]:
for j in range(i *2, n + 1, i):
is_prime[j] = False
res = [i for i in range(n+1) if is_prime[i]]
return res
def make_modinv_list(n, mod=10**9+7):
inv_list = [0]*(n+1)
inv_list[1] = 1
for i in range(2, n+1):
inv_list[i] = (mod - mod//i * inv_list[mod%i] % mod)
return inv_list
def solve():
mod = 998244353
n = ni()
a = nl()
m = max(a)
s = -sum(a) % mod
l = [0]*(m+1)
for x in a:
l[x] += x
a = make_modinv_list(m, mod)
pr = primes(m)
for i in pr:
for j in range(m//i, 0, -1):
l[j] += l[j*i]
for i in range(m+1):
l[i] = l[i] * l[i] % mod
for i in pr:
for j in range(1, m//i + 1):
l[j] = (l[j] - l[j*i]) % mod
for i in range(1, m+1):
if l[i]:
s = (s + l[i] * a[i]) % mod
print(s * a[2] % mod)
return
solve()
```
| 107,660 |
Provide a correct Python 3 solution for this coding contest problem.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
"Correct Solution:
```
mod = 998244353
n = int(input())
a = list(map(int, input().split()))
m = max(a)
cnt = [0]*(m+1)
for ai in a:
cnt[ai]+=1
ans = 0
res = [0]*(m+1)
for i in range(1, m+1)[::-1]:
sm = 0
sq = 0
for j in range(i, m+1, i):
sm+=j*cnt[j]
sq+=cnt[j]*j*j
res[i]-=res[j]
res[i]+=sm*sm-sq
ans+=res[i]//i
ans%=mod
print(ans*(pow(2, mod-2, mod))%mod)
```
| 107,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
N=int(input())
A=list(map(int,input().split()))
V=max(A)
mod=998244353
data=[0]*(V+1)
data[1]=1
for i in range(2,V+1):
data[i]=-(mod//i)*data[mod%i]%mod
for i in range(1,V+1):
for j in range(2,V//i+1):
data[i*j]=(data[i*j]-data[i])%mod
lst=[0]*(V+1)
for a in A:
lst[a]+=1
mod_2=pow(2,mod-2,mod)
ans=0
for i in range(1,V+1):
sum_1=0
sum_2=0
for j in range(1,V//i+1):
zzz=i*j
sum_1+=zzz*lst[zzz]
sum_2+=zzz**2*lst[zzz]
ans=(ans+(sum_1**2-sum_2)*data[i]*mod_2)%mod
print(ans)
```
Yes
| 107,662 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
import sys
def prepare(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
solo_invs = [0] + [f * i % MOD for f, i in zip(factorials, invs[1:])]
return factorials, invs, solo_invs
def decompose_inverses(solo_invs, MOD):
# 各整数 g に対して、g の約数である各 i について dcm[i] を全て足すと 1/g になるような数列を作成
n = len(solo_invs)
dcm = solo_invs[:]
for i in range(1, n):
d = dcm[i]
for j in range(2 * i, n, i):
dcm[j] -= d
for i in range(1, n):
dcm[i] %= MOD
return dcm
n, *aaa = map(int, sys.stdin.buffer.read().split())
MOD = 998244353
LIMIT = max(aaa)
count = [0] * (LIMIT + 1)
double = [0] * (LIMIT + 1)
for a in aaa:
count[a] += a
double[a] += a * a
_, _, solo_invs = prepare(LIMIT, MOD)
dcm = decompose_inverses(solo_invs, MOD)
ans = 0
inv2 = solo_invs[2]
for d in range(1, LIMIT + 1):
mulsum = sum(count[d::d]) ** 2 - sum(double[d::d]) % MOD
if mulsum:
ans = (ans + dcm[d] * mulsum * inv2) % MOD
print(ans)
```
Yes
| 107,663 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
n = int(input())
a = tuple(map(int,input().split()))
mod = 998244353
v = max(a)
inv = [0]*(v+1)
inv[1] = 1
for i in range(2,v+1):
inv[i] = mod - (mod//i)*inv[mod%i]%mod
#w
w = [1]*(v+1)
for i in range(2,v+1):
w[i] = (inv[i]-w[i])%mod
for j in range(i*2,v+1,i):
w[j] = (w[j] + w[i])%mod
#res
res = 0
num = [0]*(v+1)
for e in a:
num[e] += 1
for d in range(1,v+1):
s = 0
t = 0
for j in range(d,v+1,d):
s = (s + num[j]*(j//d))
t = (t + (num[j]*(j//d))*(j//d))
AA = ((((s**2-t)//2)%mod*d)%mod)*d%mod
res = (res + w[d]*AA%mod)%mod
print(res%mod)
if __name__ == '__main__':
main()
```
Yes
| 107,664 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=998244353
input=lambda:sys.stdin.readline().rstrip()
class modfact(object):
def __init__(self,n):
fact=[1]*(n+1); invfact=[1]*(n+1)
for i in range(1,n+1): fact[i]=i*fact[i-1]%MOD
invfact[n]=pow(fact[n],MOD-2,MOD)
for i in range(n-1,-1,-1): invfact[i]=invfact[i+1]*(i+1)%MOD
self.__fact=fact; self.__invfact=invfact
def inv(self,n):
assert(n>0)
return self.__fact[n-1]*self.__invfact[n]%MOD
def fact(self,n):
return self.__fact[n]
def invfact(self,n):
return self.__invfact[n]
def comb(self,n,k):
if(k<0 or n<k): return 0
return self.__fact[n]*self.__invfact[k]*self.__invfact[n-k]%MOD
def perm(self,n,k):
if(k<0 or n<k): return 0
self.__fact[n]*self.__invfact[k]%MOD
def prime(n):
if n<=1: return []
S=[1]*(n+1)
S[0]=0; S[1]=0
for i in range(2,n):
if(S[i]==0): continue
for j in range(2*i,n+1,i): S[j]=0
return [p for p in range(n+1) if(S[p])]
def resolve():
n=int(input())
A=list(map(int,input().split()))
V=max(A)
C=[0]*(V+1)
for a in A: C[a]+=1
P=prime(V)
W=[1]*(V+1)
for p in P:
for i in range(p,V+1,p):
W[i]*=(1-p)
mf=modfact(V)
for i in range(1,V+1):
W[i]=(W[i]*mf.inv(i))%MOD
ans=0
for d in range(1,V+1):
s=0 # 和(後に2乗する)
t=0 # 2乗の和
for i in range(d,V+1,d):
s+=i*C[i]%MOD
t+=(i**2)*C[i]%MOD
ans+=W[d]*(s**2-t)*mf.inv(2)
ans%=MOD
print(ans)
resolve()
```
Yes
| 107,665 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
import sys
def prepare(n, MOD):
f = 1
factorials = [1]
for m in range(1, n + 1):
f *= m
f %= MOD
factorials.append(f)
inv = pow(f, MOD - 2, MOD)
invs = [1] * (n + 1)
invs[n] = inv
for m in range(n, 1, -1):
inv *= m
inv %= MOD
invs[m - 1] = inv
solo_invs = [0] + [f * i % MOD for f, i in zip(factorials, invs[1:])]
return factorials, invs, solo_invs
def decompose_inverses(solo_invs, MOD):
# 各整数 g に対して、g の約数である各 i について dcm[i] を全て足すと 1/g になるような数列を作成
n = len(solo_invs)
dcm = solo_invs[:]
for i in range(1, n):
d = dcm[i]
for j in range(2 * i, n, i):
dcm[j] -= d
for i in range(1, n):
dcm[i] %= MOD
return dcm
n, *aaa = map(int, sys.stdin.buffer.read().split())
MOD = 998244353
LIMIT = max(aaa)
count = [0] * (LIMIT + 1)
double = [0] * (LIMIT + 1)
for a in aaa:
count[a] += a
double[a] += a * a
_, _, solo_invs = prepare(LIMIT, MOD)
dcm = decompose_inverses(solo_invs, MOD)
ans = 0
inv2 = solo_invs[2]
for d in range(1, LIMIT + 1):
mulsum = sum(count[d::d]) ** 2 - sum(double[d::d]) % MOD
if mulsum:
ans = (ans + dcm[d] * mulsum * inv2) % MOD
print(ans)
```
No
| 107,666 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
n = int(input())
a = tuple(map(int,input().split()))
mod = 998244353
v = max(a)
inv = [0]*(v+1)
inv[1] = 1
for i in range(2,v+1):
inv[i] = mod - (mod//i)*inv[mod%i]%mod
#w
w = [1]*(v+1)
for i in range(2,v+1):
w[i] = (inv[i]-w[i])%mod
for j in range(i*2,v+1,i):
w[j] = (w[j] + w[i])%mod
#res
res = 0
num = [0]*(v+1)
for e in a:
num[e] += 1
for d in range(1,v+1):
s = 0
t = 0
for j in range(d,v+1,d):
s = (s + num[j]*(j//d))%mod
t = (t + (num[j]*(j//d)%mod)*(j//d))%mod
AA = ((((s**2-t)//2)%mod*d)%mod)*d%mod
res = (res + w[d]*AA%mod)%mod
print(res%mod)
if __name__ == '__main__':
main()
```
No
| 107,667 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
import sys
sys.setrecursionlimit(4100000)
n=int(input())
A=[int(x) for x in input().split()]
import itertools
#import fractions
from functools import lru_cache
#com = list(itertools.combinations(A, 2))
res = 0
waru=998244353
@lru_cache(maxsize=None)
def gcd(a,b):
if b == 0:
return a
return gcd(b,a % b)
@lru_cache(maxsize=None)
def lcm(x,y):
r = (x * y) // gcd(x, y) % waru
return r
@lru_cache(maxsize=None)
def goukei(i,j):
if j < n-1:
return lcm(A[i],A[j]) + goukei(i,j+1)
else:
return lcm(A[i],A[j])
for i in range(n-1):
res += goukei(i,i+1)
#for a, b in com:
#res += lcm(a,b)
print(res % waru)
```
No
| 107,668 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have an integer sequence of length N: A_0,A_1,\cdots,A_{N-1}.
Find the following sum (\mathrm{lcm}(a, b) denotes the least common multiple of a and b):
* \sum_{i=0}^{N-2} \sum_{j=i+1}^{N-1} \mathrm{lcm}(A_i,A_j)
Since the answer may be enormous, compute it modulo 998244353.
Constraints
* 1 \leq N \leq 200000
* 1 \leq A_i \leq 1000000
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
N
A_0\ A_1\ \cdots\ A_{N-1}
Output
Print the sum modulo 998244353.
Examples
Input
3
2 4 6
Output
22
Input
8
1 2 3 4 6 8 12 12
Output
313
Input
10
356822 296174 484500 710640 518322 888250 259161 609120 592348 713644
Output
353891724
Submitted Solution:
```
import math
import sys
sys.setrecursionlimit(10**6)
N = int(input())
A = list(map(int , input().split()))
#result = 0;
def lcm(x, y):
return (x * y) // math.gcd(x, y)
def sigma2(func, frm, to):
result1 = 0; #答えの受け皿
for i in range(frm, to+1):
result1 += func(A[frm - 1],A[i])
#ここで関数を呼び出す。ちなみにここではi = x
return result1
def sigma(sigma2, frm, to):
result = 0; #答えの受け皿
for i in range(frm, to+1):
result += sigma2(lcm,i + 1,N - 1)
result %= 998244353
#ここで関数を呼び出す。ちなみにここではi = x
return result
if __name__ == "__main__":
print(sigma(sigma2,0,N - 2) )
```
No
| 107,669 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import sys
from heapq import heappush, heappushpop
Q = int(input())
high = []
low = []
sum_dh, sum_dl = 0, 0
sum_b = 0
MIN_X = -(10 ** 9)
buf = []
for qi, line in enumerate(sys.stdin):
q = list(map(int, line.split()))
if len(q) == 1:
x = -low[0]
dx = x - MIN_X
ans_l = dx * len(low) - sum_dl
ans_h = sum_dh - dx * len(high)
buf.append('{} {}\n'.format(x, ans_l + ans_h + sum_b))
else:
_, a, b = q
da = a - MIN_X
sum_b += b
if len(low) == len(high):
h = heappushpop(high, a)
heappush(low, -h)
dh = h - MIN_X
sum_dh += da - dh
sum_dl += dh
else:
l = -heappushpop(low, -a)
heappush(high, l)
dl = l - MIN_X
sum_dl += da - dl
sum_dh += dl
print(''.join(buf))
```
| 107,670 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
from heapq import*
L,R=[],[]
B=t=0
Q,*E=open(0)
for e in E:
if' 'in e:_,a,b=map(int,e.split());t^=1;a*=2*t-1;c=heappushpop([L,R][t],a);heappush([R,L][t],-c);B+=b+a-c-c
else:print(-L[0],B-L[0]*t)
```
| 107,671 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import sys
input = sys.stdin.readline
Q = int(input())
Y = []
D = []
S = [0] * Q
s = 0
for i in range(Q):
a = list(map(int, input().split()))
Y.append(a)
if a[0] == 1:
D.append(a[1])
s += a[2]
S[i] = s
D = sorted(list(set(D)))
INV = {}
for i in range(len(D)):
INV[D[i]] = i
N = 17
X = [0] * (2**(N+1)-1)
C = [0] * (2**(N+1)-1)
def add(j, x):
i = 2**N + j - 1
while i >= 0:
X[i] += x
C[i] += 1
i = (i-1) // 2
def rangeof(i):
s = (len(bin(i+1))-3)
l = ((i+1) - (1<<s)) * (1<<N-s)
r = l + (1<<N-s)
return (l, r)
def rangesum(a, b):
l = a + (1<<N)
r = b + (1<<N)
s = 0
while l < r:
if l%2:
s += X[l-1]
l += 1
if r%2:
r -= 1
s += X[r-1]
l >>= 1
r >>= 1
return s
def rangecnt(a, b):
l = a + (1<<N)
r = b + (1<<N)
s = 0
while l < r:
if l%2:
s += C[l-1]
l += 1
if r%2:
r -= 1
s += C[r-1]
l >>= 1
r >>= 1
return s
c = 0
su = 0
CC = [0] * (2**N)
for i in range(Q):
y = Y[i]
if y[0] == 1:
add(INV[y[1]], y[1])
CC[INV[y[1]]] += 1
c += 1
su += y[1]
else:
l, r = 0, 2**N
while True:
m = (l+r)//2
rc = rangecnt(0, m)
if rc >= (c+1)//2:
r = m
elif rc + CC[m] <= (c-1)//2:
l = m
else:
break
rs = rangesum(0, m)
print(D[m], D[m]*rc-rs+(su-rs)-(c-rc)*D[m]+S[i])
```
| 107,672 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import sys
from heapq import heappush, heappushpop
Q = int(input())
high = []
low = []
sum_dh, sum_dl = 0, 0
sum_b = 0
buf = []
for qi, line in enumerate(sys.stdin):
q = list(map(int, line.split()))
if len(q) == 1:
x = -low[0]
ans_l = x * len(low) - sum_dl
ans_h = sum_dh - x * len(high)
buf.append('{} {}\n'.format(x, ans_l + ans_h + sum_b))
else:
_, a, b = q
sum_b += b
if len(low) == len(high):
h = heappushpop(high, a)
heappush(low, -h)
sum_dh += a - h
sum_dl += h
else:
l = -heappushpop(low, -a)
heappush(high, l)
sum_dl += a - l
sum_dh += l
print(''.join(buf))
```
| 107,673 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import heapq
class DynamicMedian():
"""値をO(logN)で追加し、中央値をO(1)で求める
add(val): valを追加する
median_low(): 小さい方の中央値(low median)を求める
median_high(): 大きい方の中央値(high median)を求める
"""
def __init__(self):
self.l_q = [] # 中央値以下の値を降順で格納する
self.r_q = [] # 中央値以上の値を昇順で格納する
self.l_sum = 0
self.r_sum = 0
def add(self, val):
"""valを追加する"""
if len(self.l_q) == len(self.r_q):
self.l_sum += val
val = -heapq.heappushpop(self.l_q, -val)
self.l_sum -= val
heapq.heappush(self.r_q, val)
self.r_sum += val
else:
self.r_sum += val
val = heapq.heappushpop(self.r_q, val)
self.r_sum -= val
heapq.heappush(self.l_q, -val)
self.l_sum += val
def median_low(self):
"""小さい方の中央値を求める"""
if len(self.l_q) + 1 == len(self.r_q):
return self.r_q[0]
else:
return -self.l_q[0]
def median_high(self):
"""大きい方の中央値を求める"""
return self.r_q[0]
def minimum_query(self):
"""キューに追加されている値 a1,...,aN に対して、|x-a1| + |x-a2| + ⋯ + |x-aN|の最小値を求める
x = (a1,...,aN の中央値) となる"""
res1 = (len(self.l_q) * self.median_high() - self.l_sum)
res2 = (self.r_sum - len(self.r_q) * self.median_high())
return res1 + res2
q = int(input())
info = [list(map(int, input().split())) for i in range(q)]
dm = DynamicMedian()
b = 0
for i in range(q):
if info[i][0] == 1:
_, tmp_a, tmp_b = info[i]
dm.add(tmp_a)
b += tmp_b
else:
print(dm.median_low(), dm.minimum_query() + b)
```
| 107,674 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import heapq
q = int(input())
l = []
r = []
ai = 0
bs = 0
for i in range(q):
ipt = list(map(int,input().split()))
if ipt[0] == 1:
al = heapq.heappushpop(l,-ipt[1])
ar = heapq.heappushpop(r,ipt[1])
ai -= (al+ar)
heapq.heappush(l,-ar)
heapq.heappush(r,-al)
bs += ipt[2]
else:
an = heapq.heappop(l)
print(-an,bs+ai)
heapq.heappush(l,an)
```
| 107,675 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import heapq
Q = int(input())
# 中央値の左側の値、右側の値を管理する
# heapqとする。rightは最小が興味あるが、leftは最大なので、-1をかけて扱う
left, right = [], []
# 両方のSUMも管理する必要がある。毎回SUMしてたら間に合わん
Lsum, Rsum = 0,0
Lcnt, Rcnt = 0,0
B = 0
for _ in range(Q):
q = list(map(int, input().split()))
if len(q) == 1:
# 2
# heapqってPeakできないの・・・?
l = (-1) *left[0]
#l = (-1) * heapq.heappop(left)
#heapq.heappush(left,(-1)*l)
# (l-l1) + (l-l2) + ... + (l-l) + (r-l) + ... + (r1 - l)
print(l, Rsum//2 - Lsum//2 + B)
#print(left,right, Lsum, Rsum)
else:
# 1
_,a,b = q
B += b
# まず双方にaを突っ込む
heapq.heappush(left,(-1)*a)
heapq.heappush(right,a)
Lsum += a
Lcnt += 1
Rsum += a
Rcnt += 1
# leftの最大値と、rightの最小値の関係が崩れていたら、交換する
l = (-1)*left[0]
r = right[0]
#l = (-1) * heapq.heappop(left)
#r = heapq.heappop(right)
if l>=r:
Lsum = Lsum - l + r
Rsum = Rsum - r + l
l,r = r,l
_ = heapq.heappop(left)
_ = heapq.heappop(right)
heapq.heappush(left,(-1)*l)
heapq.heappush(right,r)
```
| 107,676 |
Provide a correct Python 3 solution for this coding contest problem.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
"Correct Solution:
```
import heapq
q = int(input())
inf = 10000000000
left = [inf]
right = [inf]
minval = 0
for _ in range(q):
query = list(map(int, input().split()))
if query[0] == 1:
_, a, b = query
if a < -left[0]:
v = -heapq.heappop(left)
heapq.heappush(right, v)
heapq.heappush(left, -a)
heapq.heappush(left, -a)
minval += abs(v - a) + b
elif a > right[0]:
v = heapq.heappop(right)
heapq.heappush(left, -v)
heapq.heappush(right, a)
heapq.heappush(right, a)
minval += abs(v - a) + b
else:
heapq.heappush(left, -a)
heapq.heappush(right, a)
minval += b
else:
print(-left[0], minval)
```
| 107,677 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
import sys
from heapq import heappush, heappop
read = sys.stdin.read
readline = sys.stdin.readline
readlines = sys.stdin.readlines
sys.setrecursionlimit(10 ** 9)
INF = 1 << 60
MOD = 1000000007
def main():
Q = int(readline())
hi = []
lo = []
hi_sum = lo_sum = 0
b_sum = 0
ans = []
for _ in range(Q):
A = list(map(int, readline().split()))
if len(A) == 3:
a, b = A[1], A[2]
b_sum += b
if not lo:
lo.append(-a)
lo_sum += a
else:
if a <= -lo[0]:
heappush(lo, -a)
lo_sum += a
else:
heappush(hi, a)
hi_sum += a
if len(hi) > len(lo):
x = heappop(hi)
hi_sum -= x
heappush(lo, -x)
lo_sum += x
elif len(hi) + 1 < len(lo):
x = -heappop(lo)
lo_sum -= x
heappush(hi, x)
hi_sum += x
else:
x = -lo[0]
val = x * (len(lo) - len(hi)) - lo_sum + hi_sum + b_sum
ans.append((x, val))
for x, val in ans:
print(x, val)
return
if __name__ == '__main__':
main()
```
Yes
| 107,678 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
from heapq import heappush, heappop
def inpl(): return list(map(int, input().split()))
Q = int(input())
L = []
R = []
B = 0
M = 0
for _ in range(Q):
q = inpl()
if len(q) == 3:
B += q[2]
if len(R) == 0:
L.append(-q[1])
R.append(q[1])
continue
M += min(abs(-L[0] - q[1]), abs(R[0] - q[1])) * (not (-L[0] <= q[1] <= R[0]))
if q[1] < R[0]:
heappush(L, -q[1])
heappush(L, -q[1])
heappush(R, -heappop(L))
else:
heappush(R, q[1])
heappush(R, q[1])
heappush(L, -heappop(R))
else:
print(-L[0], B+M)
```
Yes
| 107,679 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
# import numpy as np
# from collections import defaultdict
# from functools import reduce
import heapq
# s = input()
Q = int(input())
# A = list(map(int, input().split()))
# n, m, k = map(int, input().split())
A_left_sum = 0
A_left = []
A_right_sum = 0
A_right = []
A_med = None
query_size = 0
b_sum = 0
# n = len(As)
# n is odd:
# A_left + As[n//2] + B_left
# n is even:
# A_left + B_left
for i in range(Q):
query = list(map(int, input().split()))
if query[0] == 1:
a = query[1]
if A_med is None:
A_med = a
else:
if query_size%2 == 0: # even
left_max = -A_left[0]
right_min = A_right[0]
if a < left_max:
heapq.heappushpop(A_left, -a)
A_left_sum += a - left_max
A_med = left_max
elif a > right_min:
heapq.heappushpop(A_right, a)
A_right_sum += a - right_min
A_med = right_min
else:
A_med = a
else: # odd
if A_med <= a:
heapq.heappush(A_left, -A_med)
heapq.heappush(A_right, a)
A_left_sum += A_med
A_right_sum += a
else:
heapq.heappush(A_left, -a)
heapq.heappush(A_right, A_med)
A_right_sum += A_med
A_left_sum += a
# print(As)
# print(A_left)
# print(A_right)
query_size += 1
b_sum += query[2]
else:
if query_size%2 == 0: #even
print(-A_left[0], A_right_sum - A_left_sum + b_sum)
else:
print(A_med, A_right_sum - A_left_sum + b_sum)
```
Yes
| 107,680 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
import heapq
class PriorityQueue:
def __init__(self):
self.__heap = []
self.__count = 0
def empty(self) -> bool:
return self.__count == 0
def dequeue(self):
if self.empty():
raise Exception('empty')
self.__count -= 1
return heapq.heappop(self.__heap)
def enqueue(self, v):
self.__count += 1
heapq.heappush(self.__heap, v)
def __len__(self):
return self.__count
def absolute_minima():
Q = int(input())
L, R = PriorityQueue(), PriorityQueue()
sL, sR = 0, 0
M = None
B = 0
N = 0
for _ in range(Q):
query = [int(s) for s in input().split()]
if query[0] == 1:
_, a, b = query
B += b
N += 1
if M is None:
M = a
elif M < a:
R.enqueue(a)
sR += a
else:
L.enqueue(-a)
sL += a
while len(R)-len(L) > 1:
L.enqueue(-M)
sL += M
M = R.dequeue()
sR -= M
while len(L) > len(R):
R.enqueue(M)
sR += M
M = -L.dequeue()
sL -= M
else:
s = - sL + sR + B
if N % 2 == 0:
s -= M
print(M, s)
if __name__ == "__main__":
absolute_minima()
```
Yes
| 107,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
Q = int(input())
cnt = 0
m = []
M = []
import heapq
heapq.heapify(m)
heapq.heapify(M)
sum_m = 0
sum_M = 0
B = 0
cnt = 0
for i in range(Q):
q = str(input())
if q != '2':
_, a, b = map(int, q.split())
B += b
cnt += 1
if len(m) != 0 and len(M) != 0:
x1 = heapq.heappop(m)*(-1)
x2 = heapq.heappop(M)
sum_m -= x1
sum_M -= x2
if a <= x1:
heapq.heappush(m, a*(-1))
sum_m += a
heapq.heappush(M, x1)
heapq.heappush(M, x2)
sum_M += x1+x2
else:
heapq.heappush(M, a)
sum_M += a
heapq.heappush(m, x1*(-1))
heapq.heappush(M, x2*(-1))
sum_m += x1+x2
elif len(m) != 0 and len(M) == 0:
x1 = heapq.heappop(m)*(-1)
sum_m -= x1
if a <= x1:
heapq.heappush(m, a*(-1))
sum_m += a
heapq.heappush(M, x1)
sum_M += x1
else:
heapq.heappush(M, a)
sum_M += a
heapq.heappush(m, x1*(-1))
sum_m += x1
else:
heapq.heappush(m, a*(-1))
sum_m += a
else:
if cnt%2 == 1:
x = heapq.heappop(m)*(-1)
min_ = sum_M+sum_m+B-x*cnt
print(x, min_)
heapq.heappush(m, x*(-1))
else:
if cnt == 0:
print(0, 0)
else:
x = heapq.heappop(m)*(-1)
min_ = sum_M+sum_m+B-x*cnt
#print(sum_M, sum_m, B)
print(x, min_)
heapq.heappush(m, x*(-1))
```
No
| 107,682 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
Q = int(input())
queries = []
for _ in range(Q):
queries.append(input())
from bisect import insort_left
ary, bsum, c = [], 0, 0
for query in queries:
if query[0] == '2':
absum = sum(abs(a - ary[(c-1)//2]) for a in ary)
print(' '.join(map(str, (ary[(c-1)//2], absum + bsum))))
else:
_, a, b = map(int, query.split())
insort_left(ary, a)
bsum += b
c += 1
```
No
| 107,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
from collections import defaultdict,deque
import sys,heapq,bisect,math,itertools,string,queue,datetime
sys.setrecursionlimit(10**8)
INF = float('inf')
mod = 10**9+7
eps = 10**-7
def inpl(): return list(map(int, input().split()))
def inpl_str(): return list(input().split())
Q = int(input())
LOWq = []
HIGHq = []
heapq.heapify(LOWq)
heapq.heapify(HIGHq)
SUM = 0
LOWsum = 0
HIGHsum = 0
LOWn = 0
HIGHn = 0
keisu = 0
ans = []
N = 0
ave = -INF
for _ in range(Q):
inp = inpl()
if inp[0] == 1:
query,a,b = inp
SUM += a # 合計値
keisu += b # 係数
N += 1
bef_ave = ave # 前平均
ave = SUM/N # 平均
if a >= ave:
heapq.heappush(HIGHq,a)
HIGHsum += a
HIGHn += 1
else:
heapq.heappush(LOWq,-a)
LOWsum += a
LOWn += 1
if bef_ave < ave:
while True:
pop = heapq.heappop(HIGHq)
HIGHsum -= pop
HIGHn -= 1
if pop >= ave:
heapq.heappush(HIGHq,pop)
HIGHsum += pop
HIGHn += 1
break
else:
heapq.heappush(LOWq,-pop)
LOWsum += pop
LOWn += 1
elif bef_ave > ave:
while True:
pop = -heapq.heappop(LOWq)
LOWsum -= pop
LOWn -= 1
if pop <= ave:
heapq.heappush(LOWq,-pop)
LOWsum += pop
LOWn += 1
break
else:
heapq.heappush(HIGHq,pop)
HIGHsum += pop
HIGHn += 1
else:
#print(LOWsum,HIGHsum)
#print('n',LOWn,HIGHn)
if LOWn == 0:
x = heapq.heappop(HIGHq)
heapq.heappush(HIGHq,x)
else:
x = -heapq.heappop(LOWq)
heapq.heappush(LOWq,-x)
tmp = (HIGHsum - LOWsum) + (LOWn-HIGHn)*x + keisu
ans.append([x,tmp])
for azu,nyan in ans:
print(azu,nyan)
```
No
| 107,684 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a function f(x), which is initially a constant function f(x) = 0.
We will ask you to process Q queries in order. There are two kinds of queries, update queries and evaluation queries, as follows:
* An update query `1 a b`: Given two integers a and b, let g(x) = f(x) + |x - a| + b and replace f(x) with g(x).
* An evaluation query `2`: Print x that minimizes f(x), and the minimum value of f(x). If there are multiple such values of x, choose the minimum such value.
We can show that the values to be output in an evaluation query are always integers, so we ask you to print those values as integers without decimal points.
Constraints
* All values in input are integers.
* 1 \leq Q \leq 2 \times 10^5
* -10^9 \leq a, b \leq 10^9
* The first query is an update query.
Input
Input is given from Standard Input in the following format:
Q
Query_1
:
Query_Q
See Sample Input 1 for an example.
Output
For each evaluation query, print a line containing the response, in the order in which the queries are given.
The response to each evaluation query should be the minimum value of x that minimizes f(x), and the minimum value of f(x), in this order, with space in between.
Examples
Input
4
1 4 2
2
1 1 -8
2
Output
4 2
1 -3
Input
4
1 -1000000000 1000000000
1 -1000000000 1000000000
1 -1000000000 1000000000
2
Output
-1000000000 3000000000
Submitted Solution:
```
Q = int(input())
query = []
mid = []
for _ in range(Q):
a = list(map(int, input().split()))
query.append(a)
for i in range(len(query)):
if query[i][0] == 1:
mid.append(query[i][1:])
else:
ans = 0
mid.sort(key=lambda x: x[0])
minx = int((len(mid)+1)/2)
for j in mid:
ans += abs(mid[minx-1][0]-j[0])+j[1]
print(mid[minx-1][0],ans)
```
No
| 107,685 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
def main():
import sys
input = sys.stdin.readline
N, mod = map(int, input().split())
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
"""ここから変更"""
# op: 普通に根を固定した木DPで子の情報を親に集めるときの演算
def op(a, b):
return (a * (b + 1))%mod
# cum_merge: 累積opどうしをマージするときの演算
def cum_merge(a, b):
return (a * b)%mod
"""ここまで変更"""
# root=1でまず普通に木DPをする
# 並行して各頂点につき、子の値の累積opを左右から求めておく
# その後根から順番に、親からの寄与を求めていく(from_par)
def Rerooting(adj):
N = len(adj) - 1
st = [1]
seen = [0] * (N + 1)
seen[1] = 1
par = [0] * (N + 1)
child = [[] for _ in range(N + 1)]
seq = []
while st:
v = st.pop()
seq.append(v)
for u in adj[v]:
if not seen[u]:
seen[u] = 1
par[u] = v
child[v].append(u)
st.append(u)
seq.reverse()
dp = [1] * (N + 1)
left = [1] * (N + 1)
right = [1] * (N + 1)
for v in seq:
tmp = 1
for u in child[v]:
left[u] = tmp
tmp = op(tmp, dp[u])
tmp = 1
for u in reversed(child[v]):
right[u] = tmp
tmp = op(tmp, dp[u])
dp[v] = tmp
seq.reverse()
from_par = [0] * (N + 1)
for v in seq:
if v == 1:
continue
from_par[v] = op(cum_merge(left[v], right[v]), from_par[par[v]])
dp[v] = op(dp[v], from_par[v])
return dp
dp = Rerooting(adj)
for i in range(1, N+1):
print(dp[i])
if __name__ == '__main__':
main()
```
| 107,686 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
from collections import defaultdict, deque, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, bisect_left
import random
from itertools import permutations, accumulate, combinations, product
import sys
import string
from bisect import bisect_left, bisect_right
from math import factorial, ceil, floor, gamma, log
from operator import mul
from functools import reduce
from copy import deepcopy
sys.setrecursionlimit(2147483647)
INF = 10 ** 20
def LI(): return list(map(int, sys.stdin.readline().split()))
def I(): return int(sys.stdin.readline())
def LS(): return sys.stdin.buffer.readline().rstrip().split()
def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8')
def IR(n): return [I() for i in range(n)]
def LIR(n): return [LI() for i in range(n)]
def SR(n): pass
def LSR(n): return [LS() for i in range(n)]
def SRL(n): return [list(S()) for i in range(n)]
def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)]
n, mod = LI()
G = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = LI()
G[a - 1] += [b - 1]
G[b - 1] += [a - 1]
dp = [-1] * n
par = [-1] * n
def f(u):
ret = 1
for v in G[u]:
if v == par[u]:
continue
par[v] = u
ret = ret * f(v)
dp[u] = ret
if u: return ret + 1
f(0)
ans = [0] * n
ans[0] = dp[0]
par_acc = [1] * n
dp2 = [1] * n
q = deque([0])
while q:
u = q.pop()
ans[u] = dp[u] * dp2[u] % mod
L1 = [1]
L2 = []
D = {}
cnt = 0
for v in G[u]:
if par[u] == v:
continue
L1 += [dp[v] + 1]
L2 += [dp[v] + 1]
D[cnt] = v
q += [v]
cnt += 1
L2 += [1]
if len(L1) > 2:
for i in range(len(L1) - 2):
L1[i + 2] = L1[i + 2] * L1[i + 1] % mod
L2[-i - 3] = L2[-i - 3] * L2[-i - 2] % mod
for j in D:
dp2[D[j]] = (L1[j] * L2[j + 1] * dp2[u] + 1) % mod
print(*ans, sep="\n")
```
| 107,687 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()
def resolve():
n, MOD = map(int,input().split())
E = [[] for _ in range(n)]
nv_to_idx = [{} for _ in range(n)]
for _ in range(n - 1):
u, v = map(int,input().split())
u -= 1; v -= 1
nv_to_idx[u][v] = len(E[u])
nv_to_idx[v][u] = len(E[v])
E[u].append(v)
E[v].append(u)
# tree DP
dp = [1] * n
deg = [len(E[v]) - 1 for v in range(n)]
deg[0] += 1
stack = [(0, -1)]
while stack:
v, p = stack.pop()
if v >= 0:
for nv in E[v]:
if nv == p:
continue
stack.append((~nv, v))
stack.append((nv, v))
else:
if deg[~v] == 0:
dp[p] = dp[p] * (dp[~v] + 1) % MOD
deg[p] -= 1
# rerooting
def rerooting(v, p):
# p-rooted -> dp[p] を v-rooted に modify
if p != -1:
idx = nv_to_idx[p][v]
dp[p] = cum_left[p][idx] * cum_right[p][idx + 1] % MOD
# monoid に対する cumulative sum を計算
if cum_left[v] is None:
k = len(E[v])
left = [1] * (k + 1)
right = [1] * (k + 1)
for i in range(k):
left[i + 1] = left[i] * (dp[E[v][i]] + 1) % MOD
for i in range(k - 1, -1, -1):
right[i] = right[i + 1] * (dp[E[v][i]] + 1) % MOD
cum_left[v] = left
cum_right[v] = right
# dp[v] を v-rooted に modify
dp[v] = cum_left[v][-1]
ans = [None] * n
stack = [(0, -1)]
cum_left = [None] * n
cum_right = [None] * n
while stack:
v, p = stack.pop()
if v >= 0:
rerooting(v, p)
ans[v] = dp[v]
for nv in E[v]:
if nv == p:
continue
stack.append((~nv, v))
stack.append((nv, v))
else:
rerooting(p, ~v)
print(*ans, sep = '\n')
resolve()
```
| 107,688 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
# -*- coding: utf-8 -*-
#############
# Libraries #
#############
import sys
input = sys.stdin.readline
import math
#from math import gcd
import bisect
import heapq
from collections import defaultdict
from collections import deque
from collections import Counter
from functools import lru_cache
#############
# Constants #
#############
INF = float('inf')
AZ = "abcdefghijklmnopqrstuvwxyz"
#############
# Functions #
#############
######INPUT######
def I(): return int(input().strip())
def S(): return input().strip()
def IL(): return list(map(int,input().split()))
def SL(): return list(map(str,input().split()))
def ILs(n): return list(int(input()) for _ in range(n))
def SLs(n): return list(input().strip() for _ in range(n))
def ILL(n): return [list(map(int, input().split())) for _ in range(n)]
def SLL(n): return [list(map(str, input().split())) for _ in range(n)]
N,MOD = IL()
#####Shorten#####
def DD(arg): return defaultdict(arg)
#####Inverse#####
def inv(n): return pow(n, MOD-2, MOD)
######Combination######
kaijo_memo = []
def kaijo(n):
if(len(kaijo_memo) > n): return kaijo_memo[n]
if(len(kaijo_memo) == 0): kaijo_memo.append(1)
while(len(kaijo_memo) <= n): kaijo_memo.append(kaijo_memo[-1] * len(kaijo_memo) % MOD)
return kaijo_memo[n]
gyaku_kaijo_memo = []
def gyaku_kaijo(n):
if(len(gyaku_kaijo_memo) > n): return gyaku_kaijo_memo[n]
if(len(gyaku_kaijo_memo) == 0): gyaku_kaijo_memo.append(1)
while(len(gyaku_kaijo_memo) <= n): gyaku_kaijo_memo.append(gyaku_kaijo_memo[-1] * pow(len(gyaku_kaijo_memo),MOD-2,MOD) % MOD)
return gyaku_kaijo_memo[n]
def nCr(n,r):
if n == r: return 1
if n < r or r < 0: return 0
ret = 1
ret = ret * kaijo(n) % MOD
ret = ret * gyaku_kaijo(r) % MOD
ret = ret * gyaku_kaijo(n-r) % MOD
return ret
######Factorization######
def factorization(n):
arr = []
temp = n
for i in range(2, int(-(-n**0.5//1))+1):
if temp%i==0:
cnt=0
while temp%i==0:
cnt+=1
temp //= i
arr.append([i, cnt])
if temp!=1: arr.append([temp, 1])
if arr==[]: arr.append([n, 1])
return arr
#####MakeDivisors######
def make_divisors(n):
divisors = []
for i in range(1, int(n**0.5)+1):
if n % i == 0:
divisors.append(i)
if i != n // i:
divisors.append(n//i)
return divisors
#####MakePrimes######
def make_primes(N):
max = int(math.sqrt(N))
seachList = [i for i in range(2,N+1)]
primeNum = []
while seachList[0] <= max:
primeNum.append(seachList[0])
tmp = seachList[0]
seachList = [i for i in seachList if i % tmp != 0]
primeNum.extend(seachList)
return primeNum
#####GCD#####
def gcd(a, b):
while b: a, b = b, a % b
return a
#####LCM#####
def lcm(a, b):
return a * b // gcd (a, b)
#####BitCount#####
def count_bit(n):
count = 0
while n:
n &= n-1
count += 1
return count
#####ChangeBase#####
def base_10_to_n(X, n):
if X//n: return base_10_to_n(X//n, n)+[X%n]
return [X%n]
def base_n_to_10(X, n):
return sum(int(str(X)[-i-1])*n**i for i in range(len(str(X))))
def base_10_to_n_without_0(X, n):
X -= 1
if X//n: return base_10_to_n_without_0(X//n, n)+[X%n]
return [X%n]
#####IntLog#####
def int_log(n, a):
count = 0
while n>=a:
n //= a
count += 1
return count
#############
# Main Code #
#############
order = []
d = [INF] * N
def bfs(graph, start):
N = len(graph)
d[start] = 0
q = deque([start])
while q:
u = q.popleft()
order.append(u)
for v in graph[u]:
if d[v] != INF: continue
d[v] = d[u] + 1
q.append(v)
graph = [[] for i in range(N)]
for _ in range(N-1):
a,b = IL()
graph[a-1].append(b-1)
graph[b-1].append(a-1)
bfs(graph, 0)
dp = [0 for i in range(N)]
cum = [None for i in range(N)]
for x in order[::-1]:
cum1 = [1]
for y in graph[x]:
if d[x] < d[y]:
cum1.append((cum1[-1]*(dp[y]+1))%MOD)
cum2 = [1]
for y in graph[x][::-1]:
if d[x] < d[y]:
cum2.append((cum2[-1]*(dp[y]+1))%MOD)
dp[x] = cum1[-1]
cum[x] = [cum1,cum2]
factor = [1 for i in range(N)]
for x in order:
i = 0
for y in graph[x]:
if d[x] < d[y]:
dpinved = cum[x][0][i] * cum[x][1][len(cum[x][0])-2-i]
factor[y] = (dpinved*factor[x]+1)%MOD
i += 1
for i in range(N):
print((dp[i]*factor[i])%MOD)
```
| 107,689 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**9)
input = sys.stdin.readline
n, mod = map(int, input().split())
graph = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
ele_id = 1
# dp[v][i] = (頂点vから出るi番目の有向辺に関する部分木のDPの値)
# dp[v][i] = (c, m)
# c = 頂点vから出るi番目の有向辺に関する部分木の塗り方の数
# m = 頂点vから出るi番目の有向辺に関する部分木の頂点数
dp = [[ele_id] * len(graph[i]) for i in range(n)]
ans = [ele_id] * n
add_func = lambda x: x + 1
merge_func = lambda a, b: a * b % mod
def dfs1(v, v_p):
dp_cum = ele_id
for i, v_next in enumerate(graph[v]):
if v_next == v_p:
continue
dp[v][i] = dfs1(v_next, v)
dp_cum = merge_func(dp_cum, dp[v][i])
return add_func(dp_cum)
def dfs2(v, v_p, dp_vp):
for i, v_next in enumerate(graph[v]):
if v_next == v_p:
dp[v][i] = dp_vp
dp_l = [ele_id] * (len(graph[v]) + 1)
dp_r = [ele_id] * (len(graph[v]) + 1)
for i in range(len(graph[v])):
dp_l[i + 1] = merge_func(dp_l[i], dp[v][i])
for i in reversed(range(len(graph[v]))):
dp_r[i] = merge_func(dp_r[i + 1], dp[v][i])
ans[v] = add_func(dp_l[-1])
for i, v_next in enumerate(graph[v]):
if v_next == v_p:
continue
dfs2(v_next, v, add_func(merge_func(dp_l[i], dp_r[i + 1])))
dfs1(0, -1)
# print(*dp, sep='\n')
dfs2(0, -1, ele_id)
for ans_i in ans:
print(ans_i - 1)
```
| 107,690 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
from collections import deque
N, M = map(int, input().split())
d = [list() for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
d[a].append(b)
d[b].append(a)
queue=deque([1])
vs = set([1])
vs_bfs = list()
parents = [0] * (N+1)
while queue:
v = queue.popleft()
vs_bfs.append(v)
for u in d[v]:
if u in vs:
continue
parents[u] = v
vs.add(u)
queue.append(u)
dp = [0 for _ in range(N+1)]
dpl = [1 for _ in range(N+1)]
dpr = [1 for _ in range(N+1)]
for v in vs_bfs[::-1]:
t = 1
for u in d[v]:
if u == parents[v]:
continue
dpl[u] = t
t = (t * (dp[u]+1)) % M
t = 1
for u in d[v][::-1]:
if u == parents[v]:
continue
dpr[u] = t
t = (t * (dp[u]+1)) % M
dp[v] = t
dp2 = [0]*(N+1)
for v in vs_bfs:
if v == 1:
dp2[v] = 1
continue
p = parents[v]
dp2[v] = (dp2[p] * (dpl[v]*dpr[v]) +1)% M
# print(dp2[p] * (dpl[v]*dpr[v]))
# dp2[v] = dp2[p] %M
r = [0]*N
for i in range(1, N+1):
r[i-1] = str(dp[i] * dp2[i] % M)
print("\n".join(r))
```
| 107,691 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
# †全方位木DP†
import sys
input = lambda : sys.stdin.readline().strip()
n,m = map(int, input().split())
mod = m
G = [[] for i in range(n)]
for i in range(n-1):
a,b = map(int, input().split())
a,b = a-1,b-1
G[a].append(b)
G[b].append(a)
from collections import deque
def dfs(root):
que = deque()
que.append((root, -1))
order = []
while que:
cur,prev = que.popleft()
order.append(cur)
for to in G[cur]:
if to != prev:
que.append((to, cur))
return order
order = dfs(0)
child = set()
down = [1]*n
for cur in reversed(order):
tmp = 1
for to in G[cur]:
if to in child:
tmp *= (down[to]+1)
tmp %= mod
down[cur] = tmp
child.add(cur)
ans = [0]*n
que = deque()
que.append((0, -1, 1))
while que:
cur, prev, parent = que.popleft()
left = [1]
for to in G[cur]:
tmp = down[to]
if to == prev:
tmp = parent
left.append(left[-1]*(tmp+1)%mod)
right = [1]
for to in reversed(G[cur]):
tmp = down[to]
if to == prev:
tmp = parent
right.append(right[-1]*(tmp+1)%mod)
ans[cur] = left[-1]
m = len(G[cur])
for i, to in enumerate(G[cur]):
if to != prev:
que.append((to, cur, left[i]*right[m-i-1]))
print(*ans, sep="\n")
```
| 107,692 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
"Correct Solution:
```
import sys
sys.setrecursionlimit(2147483647)
INF=float("inf")
MOD=10**9+7 # 998244353
input=lambda:sys.stdin.readline().rstrip()
def resolve():
n, MOD = map(int,input().split())
if n == 1:
print(1)
return
E = [[] for _ in range(n)]
nv_to_idx = [{} for _ in range(n)]
for _ in range(n - 1):
u, v = map(int,input().split())
u -= 1; v -= 1
nv_to_idx[u][v] = len(E[u])
nv_to_idx[v][u] = len(E[v])
E[u].append(v)
E[v].append(u)
# topological sort
topological_sort = []
parent = [None] * n
stack = [(0, -1)]
while stack:
v, p = stack.pop()
parent[v] = p
topological_sort.append(v)
for nv in E[v]:
if nv == p:
continue
stack.append((nv, v))
topological_sort.reverse()
# tree DP
dp = [None] * n
for v in topological_sort:
res = 1
for nv in E[v]:
if nv == parent[v]:
continue
res = res * (dp[nv] + 1) % MOD
dp[v] = res
# rerooting
def rerooting(v, p):
# rerooting を先に済ませる
if p != -1 and v != -1:
idx = nv_to_idx[p][v]
p_res = 1
if idx > 0:
p_res *= cum_left[p][idx - 1]
if idx < len(E[p]) - 1:
p_res *= cum_right[p][idx + 1]
dp[p] = p_res % MOD
# monoid に対する cumulative sum を計算
if cum_left[v] is None:
left = [(dp[nv] + 1) % MOD for nv in E[v]]
right = [(dp[nv] + 1) % MOD for nv in E[v]]
k = len(E[v])
for i in range(k - 1):
left[i + 1] *= left[i]
left[i + 1] %= MOD
for i in range(k - 1, 0, -1):
right[i - 1] *= right[i]
right[i - 1] %= MOD
cum_left[v] = left
cum_right[v] = right
dp[v] = cum_left[v][-1]
ans = [None] * n
stack = [(~0, -1), (0, -1)]
cum_left = [None] * n
cum_right = [None] * n
while stack:
v, p = stack.pop()
if v >= 0:
rerooting(v, p)
ans[v] = dp[v]
for nv in E[v]:
if nv == p:
continue
stack.append((~nv, v))
stack.append((nv, v))
else:
rerooting(p, ~v)
print(*ans, sep = '\n')
resolve()
```
| 107,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
import sys
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[0] = -1
par[p] -1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
def topological_sort_tree(E, r):
Q = [r]
L = []
visited = set([r])
while Q:
vn = Q.pop()
L.append(vn)
for vf in E[vn]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N, M = map(int, input().split())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
P = getpar(Edge, 0)
L = topological_sort_tree(Edge, 0)
C = getcld(P)
dp1 = [1]*N
for l in L[N-1:0:-1]:
p = P[l]
dp1[p] = (dp1[p]*(dp1[l]+1)) % M
dp2 = [1]*N
dp2[0] = dp1[0]
info = [0]*(N+1)
vidx = [0]*N
vmull = [None]*N
vmulr = [None]*N
for i in range(N):
Ci = C[i]
res = [1]
for j, c in enumerate(Ci, 1):
vidx[c] = j
res.append(res[-1] * (1+dp1[c]) % M)
vmulr[i] = res + [1]
res = [1]
for c in Ci[::-1]:
res.append(res[-1] * (1+dp1[c]) % M)
vmull[i] = [1] + res[::-1]
for l in L[1:]:
p = P[l]
pp = P[p]
vi = vidx[l]
res = vmulr[p][vi-1] * vmull[p][vi+1] % M
res = res*(1+info[pp]) % M
dp2[l] = dp1[l]*(res+1) % M
info[p] = res % M
print(*dp2, sep = '\n')
```
Yes
| 107,694 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
INF = 10 ** 11
import sys
sys.setrecursionlimit(100000000)
N,M = map(int,input().split())
MOD = M
G = [[] for _ in range(N)]
for _ in range(N - 1):
x,y = map(int,input().split())
x -= 1
y -= 1
G[x].append(y)
G[y].append(x)
deg = [0] * N
dp = [None] * N
parents = [0] * N
ans = [0] * N
def dfs(v,p = -1):
deg[v] = len(G[v])
res = 1
dp[v] = [0] * deg[v]
for i,e in enumerate(G[v]):
if e == p:
parents[v] = i
continue
dp[v][i] = dfs(e,v)
res *= dp[v][i] + 1
res %= MOD
return res
def bfs(v,res_p = 0,p = -1):
if p != -1:
dp[v][parents[v]] = res_p
dpl = [1]*(deg[v] + 1)
dpr = [1]*(deg[v] + 1)
for i in range(deg[v]):
dpl[i + 1] = dpl[i]*(dp[v][i] + 1)%MOD
for i in range(deg[v] - 1,-1,-1):
dpr[i] = dpr[i + 1]*(dp[v][i] + 1)%MOD
ans[v] = dpr[0]
for i in range(deg[v]):
e = G[v][i]
if e == p:
continue
bfs(e,dpl[i]*dpr[i + 1]%MOD,v)
dfs(0)
bfs(0)
print('\n'.join(map(str,ans)))
```
Yes
| 107,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
#!/usr/bin/env pypy3
def I(): return int(input())
def MI(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def main():
#参考:https://qiita.com/Kiri8128/items/a011c90d25911bdb3ed3
#というかマルパクリ...
N,M=MI()
adj=[[]for _ in range(N)]
for i in range(N-1):
x,y=MI()
x-=1
y-=1
adj[x].append(y)
adj[y].append(x)
import queue
P=[-1]*N#親リスト
Q=queue.Queue()#BFSに使う
R=[]#BFSでトポソしたものを入れる
Q.put(0)#0を根とする
#トポソ########################
while not Q.empty():
v=Q.get()
R.append(v)
for nv in adj[v]:
if nv!=P[v]:
P[nv]=v
adj[nv].remove(v)#親につながるを消しておく
Q.put(nv)
#setting#############
#merge関数の単位元
unit=1
#子頂点を根とした木の結果をマージのための関数
merge=lambda a,b: (a*b)%M
#マージ後の調整用(bottom-up時),今回,木の中の要素が全部白というパターンがあるので+1
adj_bu=lambda a,v:a+1
#マージ後の調整用(top-down時)
adj_td=lambda a,v,p:a+1
#マージ後の調整用(最終結果を求める時),今回,全部白はダメなので,aをそのまま返す
adj_fin=lambda a,i:a
#今回の問題では,調整においてvやpは不要だが,必要な時もあるため,残している.
#Bottom-up#############
#merge関数を使ってMEを更新し,adjで調整してdpを埋める
#MEは親ノード以外の値を集約したようなもの
ME=[unit]*N
dp=[0]*N
for v in R[1:][::-1]:#根以外を後ろから
dp[v]=adj_bu(ME[v],v)#BU時の調整
p=P[v]
ME[p]=merge(ME[p],dp[v])#親に,子の情報を伝えている.ME[p]の初期値はunit
#print(v,p,dp[v],ME[p])
#最後だけ個別に考える
dp[R[0]]=adj_fin(ME[R[0]],R[0])
#print(ME)
#print(dp)
#Top-down##########
#TDは最終的に,Top-down時のdpを入れるが,途中においては左右累積和の左から累積させたものを入れておく
#メモリの省略のため
TD=[unit]*N
for v in R:
#左からDP(結果をTDに入れておく)
ac=TD[v]
for nv in adj[v]:
TD[nv]=ac
ac=merge(ac,dp[nv])
#右からDP(結果をacに入れて行きながら進めていく)
ac=unit
for nv in adj[v][::-1]:
TD[nv]=adj_td(merge(TD[nv],ac),nv,v)##TDときの調整
ac=merge(ac,dp[nv])
dp[nv]=adj_fin(merge(ME[nv],TD[nv]),nv)#最終調整
for i in range(N):
print(dp[i])
main()
```
Yes
| 107,696 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
# -*- coding: utf-8 -*-
from collections import defaultdict
class ReRooting:
def __init__(self, f, g, merge, ie):
self.tree = defaultdict(list)
self.f = f
self.g = g
self.merge = merge
self.ie = ie
self.dp = defaultdict(dict)
def add_edge(self, u, v):
self.tree[u].append(v)
self.tree[v].append(u)
def __dfs1(self, u, p):
o = []
s = [(u, -1)]
while s:
u, p = s.pop()
o.append((u, p))
for v in self.tree[u]:
if v == p:
continue
s.append((v, u))
for u, p in reversed(o):
r = self.ie
for v in self.tree[u]:
if v == p:
continue
# ep(u_, v, self.dp)
r = self.merge(r, self.f(self.dp[u][v], v))
self.dp[p][u] = self.g(r, u)
def __dfs2(self, u, p, a):
s = [(u, p, a)]
while s:
u, p, a = s.pop()
self.dp[u][p] = a
pl = [0] * (len(self.tree[u]) + 1)
pl[0] = self.ie
for i, v in enumerate(self.tree[u]):
pl[i+1] = self.merge(pl[i], self.f(self.dp[u][v], v))
pr = [0] * (len(self.tree[u]) + 1)
pr[-1] = self.ie
for i, v in reversed(list(enumerate(self.tree[u]))):
pr[i] = self.merge(pr[i+1], self.f(self.dp[u][v], v))
for i, v in enumerate(self.tree[u]):
if v == p:
continue
r = self.merge(pl[i], pr[i+1])
s.append((v, u, self.g(r, v)))
# def __dfs1(self, u, p):
# r = self.ie
# for v in self.tree[u]:
# if v == p:
# continue
# self.dp[u][v] = self.__dfs1(v, u)
# r = self.merge(r, self.f(self.dp[u][v], v))
# return self.g(r, u)
# def __dfs2(self, u, p, a):
# for v in self.tree[u]:
# if v == p:
# self.dp[u][v] = a
# break
# pl = [0] * (len(self.tree[u]) + 1)
# pl[0] = self.ie
# for i, v in enumerate(self.tree[u]):
# pl[i+1] = self.merge(pl[i], self.f(self.dp[u][v], v))
# pr = [0] * (len(self.tree[u]) + 1)
# pr[-1] = self.ie
# for i, v in reversed(list(enumerate(self.tree[u]))):
# pr[i] = self.merge(pr[i+1], self.f(self.dp[u][v], v))
# for i, v in enumerate(self.tree[u]):
# if v == p:
# continue
# r = self.merge(pl[i], pr[i+1])
# self.__dfs2(v, u, self.g(r, v))
def build(self, root=1):
self.__dfs1(root, -1)
self.__dfs2(root, -1, self.ie)
def slv(self, u):
r = self.ie
for v in self.tree[u]:
r = self.merge(r, self.f(self.dp[u][v], v))
return self.g(r, u)
def atcoder_dp_dp_v():
# https://atcoder.jp/contests/dp/tasks/dp_v
N, M = map(int, input().split())
XY = [list(map(int, input().split())) for _ in range(N-1)]
f = lambda x, y: x
g = lambda x, y: x + 1
merge = lambda x, y: (x * y) % M
rr = ReRooting(f, g, merge, 1)
for x, y in XY:
rr.add_edge(x, y)
rr.build()
for u in range(1, N+1):
print(rr.slv(u)-1)
def atcoder_abc60_f():
N = int(input())
AB = [list(map(int, input().split())) for _ in range(N-1)]
M = 10**9+7
from functools import reduce
fact = [1]
for i in range(1, 10**6):
fact.append(fact[-1]*i % M)
def f(x, _):
c = x[0]
s = x[1]
c *= pow(fact[s], M-2, M)
c %= M
return (c, s)
def g(x, _):
c = x[0]
s = x[1]
c *= fact[s]
c %= M
return (c, s+1)
def merge(x, y):
return (x[0]*y[0]%M, x[1]+y[1])
rr = ReRooting(f, g, merge, (1, 0))
for a, b in AB:
rr.add_edge(a, b)
rr.build()
for u in range(1, N+1):
print(rr.slv(u)[0])
if __name__ == '__main__':
atcoder_dp_dp_v()
# atcoder_abc60_f()
```
Yes
| 107,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
import queue
N, M = map(int, input().split())
G = [[] for _ in range(N)]
for _ in range(N-1):
x, y = map(int, input().split())
G[x-1].append(y-1)
G[y-1].append(x-1)
dp = {}
def rec(p, v):
C = set(G[v]) - set([p])
if len(C) == 0:
dp[(p, v)] = 1
return 1
res = 1
for u in C:
res *= (1+rec(v, u))
dp[(p, v)] = res
return dp[(p, v)]
r = 0
rec(-1, r)
q = queue.Queue()
q.put(r)
ans = [0]*N
ans[r] = dp[(-1, r)]
while not q.empty():
p = q.get()
for v in G[p]:
if ans[v] > 0: continue
ans[v] = int(dp[(p, v)]*(ans[p]/(1+dp[(p, v)])+1)) % M
q.put(v)
for a in ans:
print(a)
```
No
| 107,698 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1, 2, \ldots, N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Taro has decided to paint each vertex in white or black, so that any black vertex can be reached from any other black vertex by passing through only black vertices.
You are given a positive integer M. For each v (1 \leq v \leq N), answer the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 2 \leq M \leq 10^9
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N M
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print N lines. The v-th (1 \leq v \leq N) line should contain the answer to the following question:
* Assuming that Vertex v has to be black, find the number of ways in which the vertices can be painted, modulo M.
Examples
Input
3 100
1 2
2 3
Output
3
4
3
Input
4 100
1 2
1 3
1 4
Output
8
5
5
5
Input
1 100
Output
1
Input
10 2
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
0
0
1
1
1
0
1
0
1
1
Submitted Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
N,mod=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(N-1)]
#N=10**5
#mod=10**8
#import random
#EDGE=[[i,random.randint(1,i-1)] for i in range(2,N+1)]
EDGELIST=[[] for i in range(N+1)]
DPDICT=dict()
for x,y in EDGE:
EDGELIST[x].append(y)
EDGELIST[y].append(x)
for i in range(1,N+1):
if len(EDGELIST)==1:
DPDICT[(i,EDGELIST[i][0])]=2
def SCORE(point):
ANS=1
for to in EDGELIST[point]:
ANS=ANS*dp(to,point)%mod
return ANS
def dp(x,y):
if DPDICT.get((x,y))!=None:
return DPDICT[(x,y)]
ANS=1
for to in EDGELIST[x]:
if to==y:
continue
ANS=ANS*dp(to,x)%mod
DPDICT[(x,y)]=ANS+1
return ANS+1
for i in range(1,N+1):
print(SCORE(i))
```
No
| 107,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.