message stringlengths 2 28.7k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 21 109k | cluster float64 7 7 | __index_level_0__ int64 42 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0. | instruction | 0 | 49,308 | 7 | 98,616 |
Tags: dp
Correct Solution:
```
INF = 10 ** 18
MX_SZ = 112
dp = [[[INF for k in range (MX_SZ)] for j in range (MX_SZ)] for i in range (MX_SZ)]
best = [[[(INF, INF) for k in range (MX_SZ)] for j in range (MX_SZ)] for i in range (MX_SZ)]
def read():
return [int(x) for x in input().split()]
n, m, k_res = read()
arr = read()
cost = []
for i in range (n):
cost.append(read())
dp[0][0][MX_SZ - 1] = 0 #[trees painted][group amount][last color]
best[0][0][0] = (0, MX_SZ - 1)
#print(best[0][0][0][1])
#exit(0)
for i in range (1, n + 1):
clr = arr[i - 1]
if clr == 0:
for j in range (1, k_res + 1):
for k in range (1, m + 1):
dp[i][j][k] = dp[i - 1][j][k] + cost[i - 1][k - 1]
if k == best[i - 1][j - 1][0][1]:
dp[i][j][k] = min(dp[i][j][k], best[i - 1][j - 1][1][0] + cost[i - 1][k - 1])
else:
dp[i][j][k] = min(dp[i][j][k], best[i - 1][j - 1][0][0] + cost[i - 1][k - 1])
if dp[i][j][k] < best[i][j][0][0]:
best[i][j][1] = best[i][j][0]
best[i][j][0] = (dp[i][j][k], k)
elif dp[i][j][k] < best[i][j][1][0]:
best[i][j][1] = (dp[i][j][k], k)
else:
for j in range (1, n + 1):
dp[i][j][clr] = dp[i - 1][j][clr]
if clr == best[i - 1][j - 1][0][1]:
dp[i][j][clr] = min(dp[i][j][clr], best[i - 1][j - 1][1][0])
else:
dp[i][j][clr] = min(dp[i][j][clr], best[i - 1][j - 1][0][0])
best[i][j][0] = (dp[i][j][clr], clr)
ans = INF
for k in range (1, m + 1):
if dp[n][k_res][k] < ans:
ans = dp[n][k_res][k]
if ans == INF:
ans = -1
print(ans)
``` | output | 1 | 49,308 | 7 | 98,617 |
Provide tags and a correct Python 3 solution for this coding contest problem.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0. | instruction | 0 | 49,309 | 7 | 98,618 |
Tags: dp
Correct Solution:
```
def main():
n, m, k = map(int, input().split())
c, *cc = (map(int, input().split()))
pp, *ppp = (list(map(int, input().split())) for _ in range(n))
inf = 2 ** 47
inf2 = inf * 2
nxt = [[0 if i == c - 1 else inf for i in range(m)] if c else pp]
for c, pp in zip(cc, ppp):
newrow = [inf] * m
cur, nxt = nxt, [newrow]
if c:
c -= 1
for row in cur:
p = row[c]
if newrow[c] > p:
newrow[c] = p
if len(nxt) == k:
break
row[c] = inf2
newrow = [inf] * m
newrow[c] = min(row)
nxt.append(newrow)
else:
for row in cur:
for c, p in enumerate(a + b for a, b in zip(row, pp)):
if newrow[c] > p:
newrow[c] = p
if len(nxt) == k:
break
bestclr = min(range(m), key=row.__getitem__)
x, row[bestclr] = row[bestclr], inf2
newrow = [a + x for a in pp]
newrow[bestclr] = min(row) + pp[bestclr]
nxt.append(newrow)
p = min(nxt[-1])
print(p if p < inf else -1)
if __name__ == '__main__':
main()
``` | output | 1 | 49,309 | 7 | 98,619 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
MAX=10**18+5
n,m,k=map(int,input().split())
a=list(map(int,input().split()))
cost=[list(map(int,input().split())) for _ in range(n)]
min1=[[MAX]*(k+1) for _ in range(n)]
min2=[[MAX]*(k+1) for _ in range(n)]
idx=[[-1]*(k+1) for _ in range(n)]
for i in cost:
i.insert(0,0)
dp=[ [ [ MAX ]*(m+1) for _ in range(k+1)] for _ in range(n)]
if a[0]==0:
for i in range(1,m+1):
if min1[0][1]>=cost[0][i]:
if min1[0][1]==cost[0][i]:
idx[0][1]=-1
else:
idx[0][1]=i
min2[0][1]=min1[0][1]
min1[0][1]=cost[0][i]
elif min2[0][1]>=cost[0][i]:
min2[0][1]=cost[0][i]
dp[0][1][i]=cost[0][i]
else:
dp[0][1][a[0]]=0
min1[0][1]=0;idx[0][1]=a[0]
##print(min1)
##print(min2)
for i in range(1,n):
for j in range(1,k+1):
if a[i]==0:
for l in range(1,m+1):
dp[i][j][l]=min(dp[i][j][l],dp[i-1][j][l]+cost[i][l])
if l==idx[i-1][j-1]:
dp[i][j][l]=min(min2[i-1][j-1]+cost[i][l],dp[i][j][l])
else:
dp[i][j][l]=min(min1[i-1][j-1]+cost[i][l],dp[i][j][l])
else:
for l in range(1,m+1):
dp[i][j][a[i]]=min(dp[i][j][a[i]],dp[i-1][j][a[i]])
if l!=a[i]:
dp[i][j][a[i]]=min(dp[i-1][j-1][l],dp[i][j][a[i]])
for l in range(1,m+1):
if min1[i][j]>=dp[i][j][l]:
if min1[i][j]==dp[i][j][l]:
idx[i][j]=-1
else:
idx[i][j]=l
min2[i][j]=min1[i][j]
min1[i][j]=dp[i][j][l]
elif min2[i][j]>=dp[i][j][l]:
min2[i][j]=dp[i][j][l]
ans=MAX
for i in dp[-1][-1]:
ans=min(ans,i)
print(ans if ans <MAX else -1)
``` | instruction | 0 | 49,310 | 7 | 98,620 |
Yes | output | 1 | 49,310 | 7 | 98,621 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
def main():
n, m, k = map(int, input().split())
c, *cc = (map(int, input().split()))
pp, *ppp = (list(map(int, input().split())) for _ in range(n))
inf = 2 ** 47
inf2 = inf * 2
nxt = [[0 if i == c - 1 else inf for i in range(m)] if c else pp]
for c, pp in zip(cc, ppp):
newrow = [inf] * m
cur, nxt = nxt, [newrow]
if c:
c -= 1
for row in cur:
p = row[c]
if newrow[c] > p:
newrow[c] = p
if len(nxt) == k:
break
row[c] = inf2
newrow = [inf] * m
newrow[c] = min(row)
nxt.append(newrow)
else:
for row in cur:
for c, p in enumerate(a + b for a, b in zip(row, pp)):
if newrow[c] > p:
newrow[c] = p
if len(nxt) == k:
break
bestclr = min(range(m), key=row.__getitem__)
x, row[bestclr] = row[bestclr], inf2
newrow = [a + x for a in pp]
newrow[bestclr] = min(row) + pp[bestclr]
nxt.append(newrow)
p = min(nxt[-1])
print(p if p < inf else -1)
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | instruction | 0 | 49,311 | 7 | 98,622 |
Yes | output | 1 | 49,311 | 7 | 98,623 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
MAX=10**18+5
n,m,k=map(int,input().split())
a=list(map(int,input().split()))
cost=[list(map(int,input().split())) for _ in range(n)]
min1=[[MAX]*(k+1) for _ in range(n)]
min2=[[MAX]*(k+1) for _ in range(n)]
idx=[[-1]*(k+1) for _ in range(n)]
for i in cost:
i.insert(0,0)
dp=[ [ [ MAX ]*(m+1) for _ in range(k+1)] for _ in range(n)]
if a[0]==0:
for i in range(1,m+1):
if min1[0][1]>=cost[0][i]:
if min1[0][1]==cost[0][i]:
idx[0][1]=-2
else:
idx[0][1]=i
min2[0][1]=min1[0][1]
min1[0][1]=cost[0][i]
elif min2[0][1]>=cost[0][i]:
min2[0][1]=cost[0][i]
dp[0][1][i]=cost[0][i]
else:
dp[0][1][a[0]]=0
min1[0][1]=0;idx[0][1]=a[0]
##print(min1)
##print(min2)
for i in range(1,n):
for j in range(1,k+1):
if a[i]==0:
for l in range(1,m+1):
dp[i][j][l]=min(dp[i][j][l],dp[i-1][j][l]+cost[i][l])
if l==idx[i-1][j-1]:
dp[i][j][l]=min(min2[i-1][j-1]+cost[i][l],dp[i][j][l])
else:
dp[i][j][l]=min(min1[i-1][j-1]+cost[i][l],dp[i][j][l])
else:
for l in range(1,m+1):
dp[i][j][a[i]]=min(dp[i][j][a[i]],dp[i-1][j][a[i]])
if l!=a[i]:
dp[i][j][a[i]]=min(dp[i-1][j-1][l],dp[i][j][a[i]])
for l in range(1,m+1):
if min1[i][j]>=dp[i][j][l]:
if min1[i][j]==dp[i][j][l]:
idx[i][j]=-2
else:
idx[i][j]=l
min2[i][j]=min1[i][j]
min1[i][j]=dp[i][j][l]
elif min2[i][j]>=dp[i][j][l]:
min2[i][j]=dp[i][j][l]
ans=MAX
for i in dp[-1][-1]:
ans=min(ans,i)
print(ans if ans <MAX else -1)
``` | instruction | 0 | 49,312 | 7 | 98,624 |
Yes | output | 1 | 49,312 | 7 | 98,625 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
n,m,k=map(int,input().split())
colour=list(map(int,input().split()))
dollar=[]
for i in range(n):
dollar.append([float('inf')]+list(map(int,input().split())))
dp=[[[99999999999999999999999 for i in range(m+1)] for j in range(n+1)] for l in range(n+1)]
dp[0][1]=dollar[0]
for i in range(n-1):
if colour[i]!=0:
cost=colour[i]
for j in range(1,i+2):
for l in range(1,m+1):
if cost==l:
dp[i+1][j][l]=min(dp[i+1][j][l],dp[i][j][cost]+dollar[i+1][l]-dollar[i][cost])
else:
dp[i+1][j+1][l]=min(dp[i+1][j+1][l],dp[i][j][cost]+dollar[i+1][l]-dollar[i][cost])
else:
for j in range(1,i+2):
mini1, mini2 = 99999999999999999999999, 99999999999999999999999
for l in range(1,m+1):
if dp[i][j][l]<mini1:
mini2,mini1=mini1,dp[i][j][l]
else:
mini2=min(mini2,dp[i][j][l])
for l in range(1,m+1):
dp[i+1][j][l]=min(dp[i+1][j][l],dp[i][j][l]+dollar[i+1][l])
if dp[i][j][l] == mini1:
dp[i+1][j+1][l]=min(dp[i+1][j+1][l],dollar[i+1][l]+mini2)
else:
dp[i+1][j+1][l]=min(mini1+dollar[i+1][l],dp[i+1][j+1][l])
if colour[n-1]>0:
if dp[n-1][k][colour[n-1]] > 999999999999999999999:
print(-1)
else:
print(dp[n-1][k][colour[n-1]]-dollar[n-1][colour[n-1]])
else:
if min(dp[n-1][k]) > 99999999999999999999:
print(-1)
else:
print(min(dp[n-1][k]))
``` | instruction | 0 | 49,313 | 7 | 98,626 |
Yes | output | 1 | 49,313 | 7 | 98,627 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
s = input().split(" ")
n = int(s[0])
m = int(s[1])
k = int(s[2])
p = [int(x) for x in input().split(" ")]
cost = [[0 for i in range(0, 120)] for i in range(0, 120)]
for i in range(0, n):
s = input().split(" ")
for x in range(0, m):
cost[i][x] = int(s[x])
dyn = [[[-1 for x in range(120)] for y in range(120)] for z in range(120)]
def f(i, j, y):
if i >= n:
if y == k:
return 0
else:
return 100005000000
if dyn[i][j][y] != -1:
return dyn[i][j][y]
ans = 100005000000
if p[i] == 0:
for x in range(0, m):
dy = y
if j != x and j != -1:
dy += 1
ans = min(ans, f(i + 1, x, dy) + cost[i][x])
else:
dy = y
if j != p[i] and j != -1:
dy += 1
ans = min(ans, f(i + 1, p[i], dy))
dyn[i][j][y] = ans
return ans
aans = f(0, -1, 1)
if aans == 100005000000:
print(-1)
else:
print(aans)
``` | instruction | 0 | 49,314 | 7 | 98,628 |
No | output | 1 | 49,314 | 7 | 98,629 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
n,m,k=map(int,input().split())
col=list(map(int,input().split()))
p=[]
for i in range(n):p.append(list(map(int,input().split())))
dp=[[[float('inf')]*m for i in range(k+1)] for i in range(n)]
if col[0]==0:
for i in range(m):
dp[0][1][i]=p[0][i]
else:
dp[0][1][col[0]-1]=0
for i in range(1,n):
for j in range(1,k+1):
if j==1:
if col[i]:
dp[i][j][col[i]-1]=dp[i-1][j][col[i]-1]
else:
for c in range(m):
dp[i][j][c]=dp[i-1][j][c]+p[i][c]
else:
if col[i]:
x=dp[i-1][j][col[i]-1]
for t in range(m):
x=min(x,dp[i-1][j-1][t])
dp[i][j][col[i]-1]=x
else:
for c in range(m):
x=dp[i-1][j][c]
for t in range(m):
if t!=c:
x=min(x,dp[i-1][j-1][t])
dp[i][j][c]=x+p[i][c]
print(min(dp[-1][-1]))
``` | instruction | 0 | 49,315 | 7 | 98,630 |
No | output | 1 | 49,315 | 7 | 98,631 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
import math
dp=[[[math.inf for i in range(105)] for i in range(105)] for i in range(105)]
#dp[x][y][z] denote index x , beauty y , using paint z
#dp[x][y][z] denotes cost of it
n,m,k=map(int,input().split())
k+=1
z=list(map(int,input().split()))
matrix=[]
for i in range(n):
ans=list(map(int,input().split()))
matrix.append(ans)
for i in range(len(z)):
if(i==0 and z[i]!=0):
for o in range(m):
dp[0][1][o]=0
elif(z[i]!=0 and i>0):
if(z[i-1]!=0):
for x in range(m):
for j in range(k):
if(j==0):
continue;
dp[i][j][x]=min(dp[i-1][j-1][x],dp[i][j][x])
elif(z[i]==0):
col=z[i]-1
for x in range(m):
for j in range(k):
if(j==0):
continue;
if(x!=col):
dp[i][j][x]=min(dp[i][j][x],dp[i-1][j-1][x])
else:
dp[i][j][x]=min(dp[i][j][x],dp[i-1][j][x])
elif(z[i]==0 and i==0):
for o in range(m):
dp[0][1][o]=matrix[0][o]
elif(z[i]==0 and i>0 and z[i-1]==0):
for t in range(m):
for q in range(k):
if(q==0):
continue;
x=dp[i-1][q][t]
dp[i][q][t]=min(x+matrix[i][t],dp[i][q][t])
for w in range(m):
if(t==w):
continue;
dp[i][q+1][w]=min(dp[i][q+1][w],x+matrix[i][w])
elif(z[i]==0 and i>0 and z[i-1]!=0):
col=z[i-1]-1
for q in range(k):
if(q==0):
continue;
x=dp[i-1][q][col]
dp[i][q][col]=min(x+matrix[i][col],dp[i][q][col])
for w in range(m):
if(w==col):
continue;
dp[i][q+1][w]=min(dp[i][q+1][w],x+matrix[i][w])
mini=math.inf
for i in range(m):
mini=min(mini,dp[n-1][k-1][i])
if(mini==math.inf):
print(-1)
else:
print(mini)
``` | instruction | 0 | 49,316 | 7 | 98,632 |
No | output | 1 | 49,316 | 7 | 98,633 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
ZS the Coder and Chris the Baboon has arrived at Udayland! They walked in the park where n trees grow. They decided to be naughty and color the trees in the park. The trees are numbered with integers from 1 to n from left to right.
Initially, tree i has color ci. ZS the Coder and Chris the Baboon recognizes only m different colors, so 0 ≤ ci ≤ m, where ci = 0 means that tree i is uncolored.
ZS the Coder and Chris the Baboon decides to color only the uncolored trees, i.e. the trees with ci = 0. They can color each of them them in any of the m colors from 1 to m. Coloring the i-th tree with color j requires exactly pi, j litres of paint.
The two friends define the beauty of a coloring of the trees as the minimum number of contiguous groups (each group contains some subsegment of trees) you can split all the n trees into so that each group contains trees of the same color. For example, if the colors of the trees from left to right are 2, 1, 1, 1, 3, 2, 2, 3, 1, 3, the beauty of the coloring is 7, since we can partition the trees into 7 contiguous groups of the same color : {2}, {1, 1, 1}, {3}, {2, 2}, {3}, {1}, {3}.
ZS the Coder and Chris the Baboon wants to color all uncolored trees so that the beauty of the coloring is exactly k. They need your help to determine the minimum amount of paint (in litres) needed to finish the job.
Please note that the friends can't color the trees that are already colored.
Input
The first line contains three integers, n, m and k (1 ≤ k ≤ n ≤ 100, 1 ≤ m ≤ 100) — the number of trees, number of colors and beauty of the resulting coloring respectively.
The second line contains n integers c1, c2, ..., cn (0 ≤ ci ≤ m), the initial colors of the trees. ci equals to 0 if the tree number i is uncolored, otherwise the i-th tree has color ci.
Then n lines follow. Each of them contains m integers. The j-th number on the i-th of them line denotes pi, j (1 ≤ pi, j ≤ 109) — the amount of litres the friends need to color i-th tree with color j. pi, j's are specified even for the initially colored trees, but such trees still can't be colored.
Output
Print a single integer, the minimum amount of paint needed to color the trees. If there are no valid tree colorings of beauty k, print - 1.
Examples
Input
3 2 2
0 0 0
1 2
3 4
5 6
Output
10
Input
3 2 2
2 1 2
1 3
2 4
3 5
Output
-1
Input
3 2 2
2 0 0
1 3
2 4
3 5
Output
5
Input
3 2 3
2 1 2
1 3
2 4
3 5
Output
0
Note
In the first sample case, coloring the trees with colors 2, 1, 1 minimizes the amount of paint used, which equals to 2 + 3 + 5 = 10. Note that 1, 1, 1 would not be valid because the beauty of such coloring equals to 1 ({1, 1, 1} is a way to group the trees into a single group of the same color).
In the second sample case, all the trees are colored, but the beauty of the coloring is 3, so there is no valid coloring, and the answer is - 1.
In the last sample case, all the trees are colored and the beauty of the coloring matches k, so no paint is used and the answer is 0.
Submitted Solution:
```
n,m,k=map(int,input().split())
colour=list(map(int,input().split()))
dollar=[]
for i in range(n):
dollar.append([float("inf")]+list(map(int,input().split())))
dp=[[[float('inf') for i in range(m+1)] for j in range(n+1)] for l in range(n+1)]
dp[0][1]=dollar[0]
for i in range(n-1):
if colour[i]!=0:
cost=colour[i]
for j in range(1,i+2):
for l in range(1,m+1):
if cost==l:
dp[i+1][j][l]=min(dp[i+1][j][l],dp[i][j][cost]+dollar[i+1][l]-dollar[i][cost])
else:
dp[i+1][j+1][l]=min(dp[i+1][j+1][l],dp[i][j][cost]+dollar[i+1][l]-dollar[i][cost])
else:
for j in range(1,i+2):
mini1, mini2 = float('inf'), float('inf')
for l in range(1,m+1):
if dp[i][j][l]<mini1:
mini2,mini1=mini1,dp[i][j][l]
else:
mini2=min(mini2,dp[i][j][l])
for l in range(1,m+1):
dp[i+1][j][l]=min(dp[i+1][j][l],dp[i][j][l]+dollar[i+1][l])
if dp[i][j][l] == mini1:
dp[i+1][j+1][l]=min(dp[i+1][j+1][l],dollar[i+1][l]+mini2)
else:
dp[i+1][j+1][l]=min(mini1+dollar[i+1][l],dp[i+1][j+1][l])
if colour[n-1]>0:
if dp[n-1][k][colour[n-1]] == float('inf'):
print(-1)
else:
print(dp[n-1][k][colour[n-1]]-dollar[n-1][colour[n-1]])
else:
print(min(dp[n-1][k]))
``` | instruction | 0 | 49,317 | 7 | 98,634 |
No | output | 1 | 49,317 | 7 | 98,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a grid with N rows and N columns. The cell at the i-th row and j-th column is denoted (i, j).
Initially, M of the cells are painted black, and all other cells are white. Specifically, the cells (a_1, b_1), (a_2, b_2), ..., (a_M, b_M) are painted black.
Snuke will try to paint as many white cells black as possible, according to the following rule:
* If two cells (x, y) and (y, z) are both black and a cell (z, x) is white for integers 1≤x,y,z≤N, paint the cell (z, x) black.
Find the number of black cells when no more white cells can be painted black.
Constraints
* 1≤N≤10^5
* 1≤M≤10^5
* 1≤a_i,b_i≤N
* All pairs (a_i, b_i) are distinct.
Input
The input is given from Standard Input in the following format:
N M
a_1 b_1
a_2 b_2
:
a_M b_M
Output
Print the number of black cells when no more white cells can be painted black.
Examples
Input
3 2
1 2
2 3
Output
3
Input
2 2
1 1
1 2
Output
4
Input
4 3
1 2
1 3
4 4
Output
3
Submitted Solution:
```
from itertools import permutations
N, M = tuple(int(i) for i in input().split())
abset = {tuple(int(i) for i in line.split()) for line in [input() for i in range(M)]}
while True:
flg = True
for ab1, ab2 in permutations(abset, 2):
x1, y1 = ab1
x2, y2 = ab2
if y1 == x2 and (y2, x1) not in abset:
abset.add((y2, x1))
flg = False
if flg: break
print(len(abset))
``` | instruction | 0 | 49,512 | 7 | 99,024 |
No | output | 1 | 49,512 | 7 | 99,025 |
Provide a correct Python 3 solution for this coding contest problem.
You were lucky enough to get a map just before entering the legendary magical mystery world. The map shows the whole area of your planned exploration, including several countries with complicated borders. The map is clearly drawn, but in sepia ink only; it is hard to recognize at a glance which region belongs to which country, and this might bring you into severe danger. You have decided to color the map before entering the area. “A good deal depends on preparation,” you talked to yourself.
Each country has one or more territories, each of which has a polygonal shape. Territories belonging to one country may or may not “touch” each other, i.e. there may be disconnected territories. All the territories belonging to the same country must be assigned the same color. You can assign the same color to more than one country, but, to avoid confusion, two countries “adjacent” to each other should be assigned different colors. Two countries are considered to be “adjacent” if any of their territories share a border of non-zero length.
Write a program that finds the least number of colors required to color the map.
Input
The input consists of multiple map data. Each map data starts with a line containing the total number of territories n, followed by the data for those territories. n is a positive integer not more than 100. The data for a territory with m vertices has the following format:
String
x1 y1
x2 y2
...
xm ym
-1
“String” (a sequence of alphanumerical characters) gives the name of the country it belongs to. A country name has at least one character and never has more than twenty. When a country has multiple territories, its name appears in each of them.
Remaining lines represent the vertices of the territory. A vertex data line has a pair of nonneg- ative integers which represent the x- and y-coordinates of a vertex. x- and y-coordinates are separated by a single space, and y-coordinate is immediately followed by a newline. Edges of the territory are obtained by connecting vertices given in two adjacent vertex data lines, and byconnecting vertices given in the last and the first vertex data lines. None of x- and y-coordinates exceeds 1000. Finally, -1 in a line marks the end of vertex data lines. The number of vertices m does not exceed 100.
You may assume that the contours of polygons are simple, i.e. they do not cross nor touch themselves. No two polygons share a region of non-zero area. The number of countries in a map does not exceed 10.
The last map data is followed by a line containing only a zero, marking the end of the input data.
Output
For each map data, output one line containing the least possible number of colors required to color the map satisfying the specified conditions.
Example
Input
6
Blizid
0 0
60 0
60 60
0 60
0 50
50 50
50 10
0 10
-1
Blizid
0 10
10 10
10 50
0 50
-1
Windom
10 10
50 10
40 20
20 20
20 40
10 50
-1
Accent
50 10
50 50
35 50
35 25
-1
Pilot
35 25
35 50
10 50
-1
Blizid
20 20
40 20
20 40
-1
4
A1234567890123456789
0 0
0 100
100 100
100 0
-1
B1234567890123456789
100 100
100 200
200 200
200 100
-1
C1234567890123456789
0 100
100 100
100 200
0 200
-1
D123456789012345678
100 0
100 100
200 100
200 0
-1
0
Output
4
2 | instruction | 0 | 49,563 | 7 | 99,126 |
"Correct Solution:
```
def main():
while 1:
N = int(input())
if N == 0:
break
D = {}
G = [set() for i in range(N)]
cur = 0
K = []
PS = []
for i in range(N):
ps = []
s = input()
if s in D:
k = D[s]
else:
D[s] = k = cur
cur += 1
while 1:
d = input()
if d == "-1":
break
ps.append(list(map(int, d.split())))
for j in range(i):
if k == K[j]:
continue
qs = PS[j]
ok = 0
for k1 in range(len(ps)):
x0, y0 = ps[k1-1]
x1, y1 = ps[k1]
dx = x1 - x0; dy = y1 - y0
for k2 in range(len(qs)):
X0, Y0 = qs[k2-1]
X1, Y1 = qs[k2]
if (X0 - x0)*dy == (Y0 - y0)*dx and (X1 - x0)*dy == (Y1 - y0)*dx:
if dx != 0:
s0 = (X0 - x0); s1 = (X1 - x0)
t = dx
else:
s0 = (Y0 - y0); s1 = (Y1 - y0)
t = dy
if t < 0:
s0 = -s0; s1 = -s1
t = -t
if not s0 < s1:
s0, s1 = s1, s0
if s0 < t and 0 < s1:
break
else:
continue
break
else:
continue
l = K[j]
if k < l:
G[l].add(k)
else:
G[k].add(l)
K.append(k)
PS.append(ps)
def dfs(i, cs, ma):
if i == cur:
return max(cs)+1
U = 0
for j in G[i]:
U |= 1 << cs[j]
r = cur
for k in range(ma+1):
if U & 1 == 0:
cs[i] = k
r = min(r, dfs(i+1, cs, ma))
U >>= 1
cs[i] = ma+1
r = min(r, dfs(i+1, cs, ma+1))
return r
print(dfs(0, [0]*cur, 0))
main()
``` | output | 1 | 49,563 | 7 | 99,127 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | instruction | 0 | 49,710 | 7 | 99,420 |
Tags: combinatorics, dfs and similar, dp
Correct Solution:
```
def main():
line = input().split()
n = int(line[0])
line = input().split()
v = [int(x) for x in line]
mod = 998244353
dp = [[1] * (n + 5) for i in range(n + 5)]
for sz in range(2, n + 1):
for lo in range(1, n - sz + 2):
hi = lo + sz - 1
pos, num = -1, n + 5
for k in range(lo, hi + 1):
if v[k - 1] < num:
num = v[k - 1]
pos = k
s1, s2 = 0, 0
for k in range(lo, pos + 1):
cnt = dp[lo][k - 1] * dp[k][pos - 1] % mod
s1 = (s1 + cnt) % mod
for k in range(pos, hi + 1):
cnt = dp[pos + 1][k] * dp[k + 1][hi] % mod
s2 = (s2 + cnt) % mod
dp[lo][hi] = s1 * s2 % mod
print(dp[1][n])
main()
``` | output | 1 | 49,710 | 7 | 99,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | instruction | 0 | 49,711 | 7 | 99,422 |
Tags: combinatorics, dfs and similar, dp
Correct Solution:
```
n, m = map(int, input().split())
l = list(map(int, input().split()))
index = [[0 for i in range(n)] for j in range(n)]
for i in range(n):
mini = 10000000000000
for j in range(i, n):
if l[j] < mini:
inde = j
mini = l[j]
index[i][j] = inde
prime = 998244353
d = {}
val = [[1 for i in range(n + 1)] for j in range(n + 1)]
for i in range(n):
for j in range(n - i):
if i == 0:
val[j][j + i] = 1
elif i == 1:
val[j][j + i] = 2
else:
ind = index[j][j + i]
sumap = 0
sumak = 0
for p in range(j, ind +1):
sumap += (val[j][p - 1] * val[p][ind - 1]) % prime
for k in range(ind, j + i + 1):
sumak += (val[ind + 1][k] * val[k + 1][j + i]) % prime
val[j][j + i] = (sumap * sumak) % prime
print(val[0][n-1])
``` | output | 1 | 49,711 | 7 | 99,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | instruction | 0 | 49,712 | 7 | 99,424 |
Tags: combinatorics, dfs and similar, dp
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
A=list(map(int,input().split()))
A=[a-1 for a in A]
MININDLIST=[[i]*m for i in range(m)]
for i in range(m):
MIN=A[i]
MININDNOW=i
for j in range(i,m):
if A[j]<MIN:
MIN=A[j]
MININDNOW=j
MININDLIST[i][j]=MININDNOW
mod=998244353
SCORE=[0]*((m+1)**2)
def calc(i,j,m):
if SCORE[i*(m+1)+j]!=0:
return SCORE[i*(m+1)+j]
#print(i,j)
if j==i+1 or i==j:
return 1
MININD=MININDLIST[i][j-1]
#print(MININD)
ANS1=ANS2=0
for mi in range(i,MININD+1):
ANS1=(ANS1+calc(i,mi,m)*calc(mi,MININD,m))%mod
for Mi in range(MININD+1,j+1):
ANS2=(ANS2+calc(MININD+1,Mi,m)*calc(Mi,j,m))%mod
SCORE[i*(m+1)+j]=ANS1*ANS2%mod
return SCORE[i*(m+1)+j]
print(calc(0,m,m))
``` | output | 1 | 49,712 | 7 | 99,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | instruction | 0 | 49,713 | 7 | 99,426 |
Tags: combinatorics, dfs and similar, dp
Correct Solution:
```
class SparseTable():
"""区間取得クエリをO(1)で答えるデータ構造をO(NlogN)で構築する
query(l, r): 区間[l, r)に対するクエリに答える
"""
def __init__(self, array, n):
n = len(array)
self.row_size = n.bit_length()
# log_tableを構築する
# log_table = [0, 0, 1, 1, 2, 2, 2, 2, ...]
self.log_table = [0] * (n + 1)
for i in range(2, n + 1):
self.log_table[i] = self.log_table[i//2] + 1
# sparse_tableを構築する
self.sparse_table = [[0] * n for _ in range(self.row_size)]
for i in range(n):
self.sparse_table[0][i] = array[i]
for row in range(1, self.row_size):
for i in range(n - (1 << row) + 1):
self.sparse_table[row][i] = self._merge(self.sparse_table[row - 1][i], \
self.sparse_table[row - 1][i + (1 << row - 1)])
def _merge(self, num1, num2):
"""クエリの内容"""
return min(num1, num2)
def query(self, l, r):
"""区間[l, r)に対するクエリに答える"""
row = self.log_table[r - l]
return self._merge(self.sparse_table[row][l], self.sparse_table[row][r - (1 << row)])
n, m = map(int, input().split())
a = list(map(int, input().split()))
MOD = 998244353
sp = SparseTable(a, n)
to_ind = {}
for i in range(n):
to_ind[a[i]] = i
dp = [[-1]*(n+1) for i in range(n+1)]
def solve(l, r):
if dp[l][r] != -1:
return dp[l][r]
if l == r:
dp[l][r] = 1
return 1
if r - l == 1:
dp[l][r] = 1
return 1
ind = to_ind[sp.query(l, r)]
res1 = 0
res2 = 0
for i in range(ind+1, r+1):
res1 += solve(ind+1, i) * solve(i, r)
res1 %= MOD
for i in range(l, ind+1):
res2 += solve(l, i) * solve(i, ind)
res2 %= MOD
dp[l][r] = max(res1, 1)*max(res2, 1)
dp[l][r] %= MOD
return dp[l][r]
print(solve(0, n) % MOD)
``` | output | 1 | 49,713 | 7 | 99,427 |
Provide tags and a correct Python 3 solution for this coding contest problem.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image> | instruction | 0 | 49,714 | 7 | 99,428 |
Tags: combinatorics, dfs and similar, dp
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 998244353
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
n,m = li()
l = li()
l = [i - 1 for i in l]
mintill = [[0]*m for i in range(m)]
for i in range(n):
curr = l[i]
an = i
for j in range(i + 1,m):
if l[j] < curr:
curr = l[j]
an = j
mintill[i][j] = an
score = [[-1]*(m + 1) for i in range(m + 1)]
def recursive(i,j):
if score[i][j] != -1:return score[i][j]
if i == j or i + 1== j:return 1
mincurr = mintill[i][j - 1]
left = right = 0
for k in range(i,mincurr + 1):
left = (left + recursive(i,k)*recursive(k,mincurr))%mod
for k in range(mincurr + 1,j + 1):
right = (right + recursive(mincurr + 1,k)*recursive(k,j))%mod
score[i][j] = left*right%mod
return score[i][j]
print(recursive(0,m))
``` | output | 1 | 49,714 | 7 | 99,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image>
Submitted Solution:
```
s=input()
char=set()
n=len(s)
i=0
j=n-1
fin=''
# print(s[i],s[j])
while(j>=i+3):
if s[i]==s[j]:
fin+=s[i]
i+=1
j-=1
elif s[i]==s[j-1]:
fin+=s[i]
i+=1
j-=2
elif s[i+1]==s[j]:
fin+=s[i+1]
i+=2
j-=1
else:
fin+=s[i+1]
i+=2
j-=2
print(fin+fin[::-1])
``` | instruction | 0 | 49,715 | 7 | 99,430 |
No | output | 1 | 49,715 | 7 | 99,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image>
Submitted Solution:
```
# http://oeis.org/A067687/b067687.txt
print([1, 1, 2, 5, 12, 29, 69, 165, 393, 937, 2233, 5322, 12683, 30227, 72037, 171680, 409151, 975097, 2323870, 5538294, 13198973, 31456058, 74966710, 178662171, 425791279, 16509988, 421894250, 772317138, 758605251, 791572262, 152584055, 255001322, 886175694, 880627650, 165789169, 492846662, 562081977, 669550565, 367444374, 551333202, 869355827, 773441612, 168646354, 164139432, 876499776, 531107932, 595746456, 19179115, 642402929, 143272242, 908012821, 792799054, 912251042, 496829021, 824266664, 967856940, 192609533, 558904536, 511648975, 620758987, 958466325, 670757984, 118009093, 133737785, 942586845, 408942643, 18643877, 605150512, 989503005, 683705056, 418209389, 503449395, 950480778, 942900321, 270780723, 464695236, 209313111, 680519600, 895823392, 340681933, 662353274, 91601368, 487196441, 720894693, 280967139, 846163649, 518724758, 289035939, 518625939, 490006078, 815390993, 760235198, 390198397, 838927134, 216762914, 396291588, 649286477, 851818039, 478168705, 768368298, 372626473, 436606447, 532426353, 800259652, 61832633, 279530984, 214143778, 928462393, 522742059, 408967764, 850483804, 780916338, 737074325, 611790318, 408538342, 292125197, 259526237, 938950142, 55585726, 248747626, 747929003, 630793123, 618633031, 501000457, 321028916, 349338917, 773920532, 98903312, 122030203, 949165981, 798312152, 439277114, 868857454, 549559417, 280975182, 277396665, 242022996, 566776812, 294901760, 4761137, 141381022, 458171778, 257484609, 269333907, 573077901, 167628122, 483234338, 399701186, 370867367, 165195719, 422615997, 481059741, 792372810, 12790797, 975234079, 384735997, 322710930, 604063069, 611468844, 230939831, 444554011, 738204479, 824035594, 937835732, 993643992, 993904061, 106060265, 553844236, 903043949, 338376206, 171410616, 69462094, 522508601, 406493354, 738910605, 121185514, 747607507, 743321354, 591921466, 770244809, 693987710, 511892567, 551772421, 694606436, 382340005, 486088284, 725266688, 892443018, 150556699, 910868599, 788813893, 980670802, 140548726, 281789205, 655874377, 275274190, 702964824, 237895769, 275837198, 493320721, 339388377, 295154314, 123637254, 565135615, 114834927, 895864108, 721083382, 915062758, 114722486, 709980377, 13180642, 576827614, 936166314, 958533423, 843235257, 13380400, 561065473, 937390710, 512773045, 404338356, 58286881, 252422433, 153883653, 177303708, 628991009, 988228807, 248172675, 311144353, 800079028, 39328070, 597494650, 15048767, 717238431, 933408125, 252725304, 539080550, 494115145, 430242280, 592220686, 340597562, 413349227, 992872512, 684204025, 79970055, 943111984, 566425894, 613621841, 487376193, 615872348, 778681469, 516485424, 352660318, 473149928, 287838750, 307446067, 663285295, 363728857, 425819132, 181276078, 746189335, 894198420, 190001756, 642222636, 493166365, 501180824, 488626307, 140224352, 484707267, 633440945, 262683129, 550486540, 604465958, 357911591, 652497285, 215598692, 757609741, 306741922, 681299437, 258093706, 473023829, 80623832, 682529709, 364023856, 204136050, 425483984, 937295404, 176157201, 426163716, 882486303, 59222731, 427293990, 732072123, 963481563, 948381034, 971844844, 122099849, 325020707, 616050618, 427963679, 724187743, 472743269, 835754201, 37221631, 757888159, 998054174, 139258075, 899651024, 95774401, 41263863, 494810979, 510004566, 340153023, 249743998, 224884876, 586466893, 974585382, 876152399, 6577073, 703854524, 708981144, 618325209, 42294251, 524298582, 497923153, 733903455, 389566584, 114303126, 960118605, 560613149, 445877708, 245334767, 883443482, 320797393, 317026123, 275869404, 975489971, 188832181, 905034585, 310717227, 316018379, 538003920, 128903757, 162128819, 836240734, 989728251, 838168543, 533545339, 37693058, 90034273, 621534616, 657712470, 177898941, 136765697, 877997470, 110537791, 527110122, 964880993, 793193821, 28224262, 947601483, 783687528, 468824770, 781467141, 414834547, 539879240, 674995522, 123774616, 813922694, 232849214, 311748047, 740496810, 601679286, 420592035, 264640758, 377474106, 674488466, 438450339, 568760717, 742058111, 743336241, 206891756, 646231269, 716653901, 270685676, 260637451, 294938558, 668713442, 959693668, 783827663, 721205232, 975822890, 717605381, 805223657, 678290246, 52758401, 584972359, 731278059, 85187483, 197640760, 533147473, 319410432, 211802438, 867837787, 238572039, 976797245, 531149684, 749405641, 753010608, 610591150, 6825345, 338929136, 988837113, 187938818, 436162907, 292700539, 515542793, 764024147, 946061745, 522227218, 353674590, 33462626, 233279830, 217725590, 867835683, 341571715, 506285752, 403387500, 67902768, 103120423, 717819493, 690507781, 583146965, 887833889, 405198748, 499640318, 896554487, 475539470, 417989410, 274335632, 989748832, 458205449, 817649488, 526284905, 358005336, 671542899, 237582376, 560321163, 144814673, 73164002, 680014140, 791555373, 82830398, 771511276, 100145748, 774968686, 714878197, 340185593, 231248697, 495068273, 297650819, 281363051, 954885183, 396394807, 108652076, 430885526, 774141622, 591314096, 289269790, 826062888, 181863380, 81194099, 766017360, 877559214, 75108474, 101053225, 61763897, 674113810, 166375264, 788058387, 594100344, 639484718, 183227240, 343030672, 91478121, 656467071, 700116967, 893718250, 568596910, 435698155, 961985583, 167998657, 535224628, 468416770, 748748871, 923607064, 409980843, 311287650, 158979317, 150972707, 957983483, 118169429, 313693918, 266592822][int(input().split()[0])])
``` | instruction | 0 | 49,716 | 7 | 99,432 |
No | output | 1 | 49,716 | 7 | 99,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image>
Submitted Solution:
```
print([1, 1, 2, 5, 12, 29, 69, 165, 393, 937, 2233, 5322, 12683, 30227, 72037, 171680, 409151, 975097, 2323870, 5538294, 13198973, 31456058, 74966710, 178662171, 425791279, 16509988, 421894250, 772317138, 758605251, 791572262, 152584055, 255001322, 886175694, 880627650, 165789169, 492846662, 562081977, 669550565, 367444374, 551333202, 869355827, 773441612, 168646354, 164139432, 876499776, 531107932, 595746456, 19179115, 642402929, 143272242, 908012821, 792799054, 912251042, 496829021, 824266664, 967856940, 192609533, 558904536, 511648975, 620758987, 958466325, 670757984, 118009093, 133737785, 942586845, 408942643, 18643877, 605150512, 989503005, 683705056, 418209389, 503449395, 950480778, 942900321, 270780723, 464695236, 209313111, 680519600, 895823392, 340681933, 662353274, 91601368, 487196441, 720894693, 280967139, 846163649, 518724758, 289035939, 518625939, 490006078, 815390993, 760235198, 390198397, 838927134, 216762914, 396291588, 649286477, 851818039, 478168705, 768368298, 372626473, 436606447, 532426353, 800259652, 61832633, 279530984, 214143778, 928462393, 522742059, 408967764, 850483804, 780916338, 737074325, 611790318, 408538342, 292125197, 259526237, 938950142, 55585726, 248747626, 747929003, 630793123, 618633031, 501000457, 321028916, 349338917, 773920532, 98903312, 122030203, 949165981, 798312152, 439277114, 868857454, 549559417, 280975182, 277396665, 242022996, 566776812, 294901760, 4761137, 141381022, 458171778, 257484609, 269333907, 573077901, 167628122, 483234338, 399701186, 370867367, 165195719, 422615997, 481059741, 792372810, 12790797, 975234079, 384735997, 322710930, 604063069, 611468844, 230939831, 444554011, 738204479, 824035594, 937835732, 993643992, 993904061, 106060265, 553844236, 903043949, 338376206, 171410616, 69462094, 522508601, 406493354, 738910605, 121185514, 747607507, 743321354, 591921466, 770244809, 693987710, 511892567, 551772421, 694606436, 382340005, 486088284, 725266688, 892443018, 150556699, 910868599, 788813893, 980670802, 140548726, 281789205, 655874377, 275274190, 702964824, 237895769, 275837198, 493320721, 339388377, 295154314, 123637254, 565135615, 114834927, 895864108, 721083382, 915062758, 114722486, 709980377, 13180642, 576827614, 936166314, 958533423, 843235257, 13380400, 561065473, 937390710, 512773045, 404338356, 58286881, 252422433, 153883653, 177303708, 628991009, 988228807, 248172675, 311144353, 800079028, 39328070, 597494650, 15048767, 717238431, 933408125, 252725304, 539080550, 494115145, 430242280, 592220686, 340597562, 413349227, 992872512, 684204025, 79970055, 943111984, 566425894, 613621841, 487376193, 615872348, 778681469, 516485424, 352660318, 473149928, 287838750, 307446067, 663285295, 363728857, 425819132, 181276078, 746189335, 894198420, 190001756, 642222636, 493166365, 501180824, 488626307, 140224352, 484707267, 633440945, 262683129, 550486540, 604465958, 357911591, 652497285, 215598692, 757609741, 306741922, 681299437, 258093706, 473023829, 80623832, 682529709, 364023856, 204136050, 425483984, 937295404, 176157201, 426163716, 882486303, 59222731, 427293990, 732072123, 963481563, 948381034, 971844844, 122099849, 325020707, 616050618, 427963679, 724187743, 472743269, 835754201, 37221631, 757888159, 998054174, 139258075, 899651024, 95774401, 41263863, 494810979, 510004566, 340153023, 249743998, 224884876, 586466893, 974585382, 876152399, 6577073, 703854524, 708981144, 618325209, 42294251, 524298582, 497923153, 733903455, 389566584, 114303126, 960118605, 560613149, 445877708, 245334767, 883443482, 320797393, 317026123, 275869404, 975489971, 188832181, 905034585, 310717227, 316018379, 538003920, 128903757, 162128819, 836240734, 989728251, 838168543, 533545339, 37693058, 90034273, 621534616, 657712470, 177898941, 136765697, 877997470, 110537791, 527110122, 964880993, 793193821, 28224262, 947601483, 783687528, 468824770, 781467141, 414834547, 539879240, 674995522, 123774616, 813922694, 232849214, 311748047, 740496810, 601679286, 420592035, 264640758, 377474106, 674488466, 438450339, 568760717, 742058111, 743336241, 206891756, 646231269, 716653901, 270685676, 260637451, 294938558, 668713442, 959693668, 783827663, 721205232, 975822890, 717605381, 805223657, 678290246, 52758401, 584972359, 731278059, 85187483, 197640760, 533147473, 319410432, 211802438, 867837787, 238572039, 976797245, 531149684, 749405641, 753010608, 610591150, 6825345, 338929136, 988837113, 187938818, 436162907, 292700539, 515542793, 764024147, 946061745, 522227218, 353674590, 33462626, 233279830, 217725590, 867835683, 341571715, 506285752, 403387500, 67902768, 103120423, 717819493, 690507781, 583146965, 887833889, 405198748, 499640318, 896554487, 475539470, 417989410, 274335632, 989748832, 458205449, 817649488, 526284905, 358005336, 671542899, 237582376, 560321163, 144814673, 73164002, 680014140, 791555373, 82830398, 771511276, 100145748, 774968686, 714878197, 340185593, 231248697, 495068273, 297650819, 281363051, 954885183, 396394807, 108652076, 430885526, 774141622, 591314096, 289269790, 826062888, 181863380, 81194099, 766017360, 877559214, 75108474, 101053225, 61763897, 674113810, 166375264, 788058387, 594100344, 639484718, 183227240, 343030672, 91478121, 656467071, 700116967, 893718250, 568596910, 435698155, 961985583, 167998657, 535224628, 468416770, 748748871, 923607064, 409980843, 311287650, 158979317, 150972707, 957983483, 118169429][int(input().split()[0])])
``` | instruction | 0 | 49,717 | 7 | 99,434 |
No | output | 1 | 49,717 | 7 | 99,435 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is the first subtask of problem F. The only differences between this and the second subtask are the constraints on the value of m and the time limit. You need to solve both subtasks in order to hack this one.
There are n+1 distinct colours in the universe, numbered 0 through n. There is a strip of paper m centimetres long initially painted with colour 0.
Alice took a brush and painted the strip using the following process. For each i from 1 to n, in this order, she picks two integers 0 ≤ a_i < b_i ≤ m, such that the segment [a_i, b_i] is currently painted with a single colour, and repaints it with colour i.
Alice chose the segments in such a way that each centimetre is now painted in some colour other than 0. Formally, the segment [i-1, i] is painted with colour c_i (c_i ≠ 0). Every colour other than 0 is visible on the strip.
Count the number of different pairs of sequences \\{a_i\}_{i=1}^n, \\{b_i\}_{i=1}^n that result in this configuration.
Since this number may be large, output it modulo 998244353.
Input
The first line contains a two integers n, m (1 ≤ n ≤ 500, n = m) — the number of colours excluding the colour 0 and the length of the paper, respectively.
The second line contains m space separated integers c_1, c_2, …, c_m (1 ≤ c_i ≤ n) — the colour visible on the segment [i-1, i] after the process ends. It is guaranteed that for all j between 1 and n there is an index k such that c_k = j.
Note that since in this subtask n = m, this means that c is a permutation of integers 1 through n.
Output
Output a single integer — the number of ways Alice can perform the painting, modulo 998244353.
Examples
Input
3 3
1 2 3
Output
5
Input
7 7
4 5 1 6 2 3 7
Output
165
Note
In the first example, there are 5 ways, all depicted in the figure below. Here, 0 is white, 1 is red, 2 is green and 3 is blue.
<image>
Below is an example of a painting process that is not valid, as in the second step the segment 1 3 is not single colour, and thus may not be repainted with colour 2.
<image>
Submitted Solution:
```
def dfs(l,r):
if l>=r:
return 1
wz=l;s1=0;s2=0
for i in range(l,r+1):
if a[i-1]<a[wz-1]:
wz=i
i=l
while i<=wz:
s1=(s1+dfs(l,i-1)*dfs(i,wz-1)%md)%md
i=i+1
i=wz
while i<=r:
s2=(s2+dfs(wz+1,i)*dfs(i+1,r)%md)%md
i=i+1
dp[l][r]=s1*s2%md
return dp[l][r]
md=998244353
n,m=map(int,input().split())
dp=[[0]*(n+2)]*(n+2)
a=input().split()
print(dfs(1,n))
``` | instruction | 0 | 49,718 | 7 | 99,436 |
No | output | 1 | 49,718 | 7 | 99,437 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example. | instruction | 0 | 49,787 | 7 | 99,574 |
Tags: math
Correct Solution:
```
for n in range(int(input())):
s=sorted(list(map(int,input().split())))
s.reverse()
if s[0]==s[1]==s[2]:
print('Yes')
elif s[0]-(s[1]+s[2])<=1 :
print('Yes')
else:
print('No')
``` | output | 1 | 49,787 | 7 | 99,575 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example. | instruction | 0 | 49,788 | 7 | 99,576 |
Tags: math
Correct Solution:
```
N = int(input())
cases = []
for _ in range(N):
case = [ int(x) for x in input().split() ]
cases.append(case)
def judge(case):
def get_max_and_sum(case):
a, b, c = case
if a > b and a > c:
return a, b + c
elif b > a and b > c:
return b, a + c
else:
return c, a + b
m, s = get_max_and_sum(case)
if (m-1) > s:
print('No')
else:
print('Yes')
for case in cases:
judge(case)
``` | output | 1 | 49,788 | 7 | 99,577 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example. | instruction | 0 | 49,791 | 7 | 99,582 |
Tags: math
Correct Solution:
```
#min of two should be less than or equal to half of third
for _ in range(int(input())):
a,b,c=sorted(map(int,input().split()))
if c<=a+b+1:
print("YES")
else:
print("NO")
``` | output | 1 | 49,791 | 7 | 99,583 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=tf-8
#
"""
"""
from operator import itemgetter
t = int(input())
def solve(cols):
mm = max(cols)
s = sum(cols)
if 2*mm - s <= 1 :
print("Yes")
else:
print("No")
for i in range(t):
cols = list(map(int,input().split()))
solve(cols)
``` | instruction | 0 | 49,792 | 7 | 99,584 |
Yes | output | 1 | 49,792 | 7 | 99,585 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
t=int(input())
while(t>0):
r,g,b=input().split(" ")
r=int(r)
g=int(g)
b=int(b)
flag=False
if((r>=g) and (r>=b)):
if(g+b >=r-1):
flag=True
elif((g>=r) and (g>=b)):
if(r+b >=g-1):
flag=True
elif((b>=g) and (b>=r)):
if(g+r >= b-1):
flag=True
if(flag==False):
print("No")
else:
print("Yes")
t=t-1
``` | instruction | 0 | 49,793 | 7 | 99,586 |
Yes | output | 1 | 49,793 | 7 | 99,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
####################
t=int(input())
for i in range(t):
r,g,b=map(int,input().split())
s=r+g+b
if s%2==0:
if r>s//2 or g>s//2 or b>s//2:
print("No")
else:
print("Yes")
else:
if r>s//2+1 or g>s//2+1 or b>s//2+1:
print("No")
else:
print("Yes")
``` | instruction | 0 | 49,794 | 7 | 99,588 |
Yes | output | 1 | 49,794 | 7 | 99,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
t=int(input())
for i in range(t):
a=list(map(int,input().split()));
a.sort()
if a[2]>a[1]+a[0]+1:
print ("No\n")
else:
print ("Yes\n")
``` | instruction | 0 | 49,795 | 7 | 99,590 |
Yes | output | 1 | 49,795 | 7 | 99,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
t=int(input())
for i in range(t):
a = [int(ii) for ii in input().split()]
s= sum(a)
out = True
for j in a:
if j > s//2:
out = False
if out:
print("Yes")
else:
print("No")
``` | instruction | 0 | 49,796 | 7 | 99,592 |
No | output | 1 | 49,796 | 7 | 99,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
# new_year_garland.py
t = int(input())
while t>0:
t-=1
l = list(map(int,input().split()))
l[1]-=l[0]
l[2]-=l[0]
if l[1]<=(l[0]+1) and l[2]<=(l[0]+1):
print('YES')
else:
print('NO')
``` | instruction | 0 | 49,797 | 7 | 99,594 |
No | output | 1 | 49,797 | 7 | 99,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
t=int(input())
for zz in range(t):
arr=list(map(int,input().split()))
arr.sort()
for i in range(3):
arr[i]=arr[i]-arr[0]
if(abs(arr[1]-arr[2])<2):
print('Yes')
else:
print('No')
``` | instruction | 0 | 49,798 | 7 | 99,596 |
No | output | 1 | 49,798 | 7 | 99,597 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Polycarp is sad — New Year is coming in few days but there is still no snow in his city. To bring himself New Year mood, he decided to decorate his house with some garlands.
The local store introduced a new service this year, called "Build your own garland". So you can buy some red, green and blue lamps, provide them and the store workers will solder a single garland of them. The resulting garland will have all the lamps you provided put in a line. Moreover, no pair of lamps of the same color will be adjacent to each other in this garland!
For example, if you provide 3 red, 3 green and 3 blue lamps, the resulting garland can look like this: "RGBRBGBGR" ("RGB" being the red, green and blue color, respectively). Note that it's ok to have lamps of the same color on the ends of the garland.
However, if you provide, say, 1 red, 10 green and 2 blue lamps then the store workers won't be able to build any garland of them. Any garland consisting of these lamps will have at least one pair of lamps of the same color adjacent to each other. Note that the store workers should use all the lamps you provided.
So Polycarp has bought some sets of lamps and now he wants to know if the store workers can build a garland from each of them.
Input
The first line contains a single integer t (1 ≤ t ≤ 100) — the number of sets of lamps Polycarp has bought.
Each of the next t lines contains three integers r, g and b (1 ≤ r, g, b ≤ 10^9) — the number of red, green and blue lamps in the set, respectively.
Output
Print t lines — for each set of lamps print "Yes" if the store workers can build a garland from them and "No" otherwise.
Example
Input
3
3 3 3
1 10 2
2 1 1
Output
Yes
No
Yes
Note
The first two sets are desribed in the statement.
The third set produces garland "RBRG", for example.
Submitted Solution:
```
t = int(input())
while t:
t-=1
r,g,b = map(int,input().split())
arr = [r,g,b]
arr.sort()
r,g,b = arr
b_ = b
r_ = r
g_ = g
b = b-g
if b>1:
r = r-b
if r>=0 and r<=(2*g_+1):
print("YES")
else:
print("NO")
``` | instruction | 0 | 49,799 | 7 | 99,598 |
No | output | 1 | 49,799 | 7 | 99,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,876 | 7 | 99,752 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
for _ in range(int(input())):
input();n, m = map(int, input().split());a = [];flag = "YES"
for _ in range(m):b, c = map(int, input().split());a.append([c, b])
if m % 2:print("NO");continue
a.sort()
for x in range(0, m, 2):
if a[x][1] == a[x + 1][1]:
if (a[x + 1][0] - a[x][0]) % 2 == 0:flag = "NO";break
else:
if (a[x + 1][0] - a[x][0]) % 2 == 1:flag = "NO";break
if x != 0 and a[x - 1][0] == a[x][0]:flag = "NO";break
print(flag)
``` | output | 1 | 49,876 | 7 | 99,753 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,877 | 7 | 99,754 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
import math
import sys
input=sys.stdin.readline
from collections import Counter, defaultdict, deque
def f(n,m, mp):
#mp = collections.OrderedDict(sorted(mp.items()))
#print(mp)
cap = 2*n - m
if cap%2 == 1:
return "NO"
blocked = 0
for i in sorted(mp.keys()):
if blocked:
if len(mp[i]) == 2:
return "NO"
currow = mp[i][0]
if(last_blocked[0] == currow):
if(last_blocked[1]%2 == i%2):
return "NO"
else:
blocked = 0
else:
if(last_blocked[1]%2 != i%2):
return "NO"
else:
blocked = 0
else:
if len(mp[i]) == 1:
blocked = 1
last_blocked = (mp[i][0], i)
return "YES"
t = int(input())
result = []
for i in range(t):
input()
#n = int(input())
mp = defaultdict(list)
n, m = list(map(int, input().split()))
for i in range(m):
r, c = list(map(int, input().split()))
mp[c].append(r)
result.append(f(n, m, mp))
for i in range(t):
print(result[i])
``` | output | 1 | 49,877 | 7 | 99,755 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,878 | 7 | 99,756 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
in_length = int(input())
final_ouput = []
for i in range(in_length):
blank = input()
[length, num_obstructions] = input().split()
state_saver = dict()
h_positon_obstacles = []
for j in range(int(num_obstructions)):
[row, column] = input().split()
col_index = int(column) - 1
if not col_index in state_saver:
state_saver.update({col_index: row})
else:
state_saver.update({col_index: state_saver[col_index]+row})
h_positon_obstacles.append(col_index)
final_ouput.append('YES')
if len(h_positon_obstacles)%2 != 0:
final_ouput[i] = 'NO'
continue
h_positon_obstacles = sorted(h_positon_obstacles)
for j in range(0,len(h_positon_obstacles),2):
block1 = h_positon_obstacles[j]
block2 = h_positon_obstacles[j+1]
if block1 == block2:
continue
col_block1 = state_saver[block1]
col_block2 = state_saver[block2]
if len(col_block1) == len(col_block2):
separation_parity = (block2-block1-1) % 2
if col_block1 != col_block2 and separation_parity == 0:
final_ouput[i] = 'NO'
break
elif col_block1 == col_block2 and separation_parity != 0:
final_ouput[i] = 'NO'
break
else:
final_ouput[i] = 'NO'
break
for out in final_ouput:
print(out)
``` | output | 1 | 49,878 | 7 | 99,757 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,879 | 7 | 99,758 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
# Author: yumtam
# Created at: 2021-01-06 06:10
from itertools import groupby
def solve():
input()
n, m = map(int, input().split())
A = [[int(t) for t in input().split()] for _ in range(m)]
A.sort(key=lambda p: p[1])
ps, pc = 0, 0
for c, it in groupby(A, key=lambda p: p[1]):
r = sum(p[0] for p in it)
if ps == 0:
cs = 0
else:
cs = ps if (c - pc) % 2 == 0 else 3 - ps
if cs & r:
print("NO")
break
cs |= r
if cs == 3:
cs = 0
ps, pc = cs, c
else:
print("YES" if cs == 0 else "NO")
import sys, os, io
input = sys.stdin.readline
stdout = io.BytesIO()
sys.stdout.write = lambda s: stdout.write(s.encode("ascii"))
for _ in range(int(input())):
solve()
os.write(1, stdout.getvalue())
``` | output | 1 | 49,879 | 7 | 99,759 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,880 | 7 | 99,760 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
input()
n, m = map(int, input().split())
a = [tuple(map(int, input().split())) for _ in range(m)]
a.sort(key=lambda x: x[1])
l = [0, 0]
for r, x in a:
r -= 1
if (x - l[r] - 1) % 2 == 0:
l[r] = x
elif x - l[r ^ 1] >= 2 and (x - l[r ^ 1] - 2) % 2 == 0:
l[r] = x
l[r ^ 1] = x - 1
else:
print("NO")
break
else:
print("YES" if l[0] % 2 == l[1] % 2 else "NO")
``` | output | 1 | 49,880 | 7 | 99,761 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,881 | 7 | 99,762 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
"""
pppppppppppppppppppp
ppppp ppppppppppppppppppp
ppppppp ppppppppppppppppppppp
pppppppp pppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppppp ppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppp
ppppppppppppppppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppp
pppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp pppppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppppp
ppppppppppppppppppppp ppppppppppppppppppppppppppppppppppppppppppppp
pppppppppppppppppppppppp
pppppppppppppppppppppppppppppppp
pppppppppppppppppppppp pppppppp
ppppppppppppppppppppp ppppppp
ppppppppppppppppppp ppppp
pppppppppppppppppppp
"""
import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm, zip_longest
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
# sys.setrecursionlimit(pow(10, 6))
# sys.stdin = open("input.txt", "r")
# sys.stdout = open("output.txt", "w")
mod = pow(10, 9) + 7
mod2 = 998244353
def data(): return sys.stdin.readline().strip()
def out(var): sys.stdout.write(str(var)+"\n")
def outa(*var, end="\n"): sys.stdout.write(' '.join(map(str, var)) + end)
def l(): return list(sp())
def sl(): return list(ssp())
def sp(): return map(int, data().split())
def ssp(): return map(str, data().split())
def l1d(n, val=0): return [val for i in range(n)]
def l2d(n, m, val=0): return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
s = data()
n, m = sp()
d = C()
for i in range(m):
r, c = sp()
d[c] |= (1 << (r - 1))
result = True
s = pos = 0
for a, b in sorted(d.items(), key=lambda x: x[0]):
if s in [0, 3]:
if b == 3:
continue
s = b
pos = a
continue
if b == 3:
result = False
break
if s == 1:
if b == 1 and not((a - pos) & 1):
result = False
break
if b == 2 and (a - pos) & 1:
result = False
break
s = 0
pos = a
continue
if b == 1 and (a - pos) & 1:
result = False
break
if b == 2 and not((a - pos) & 1):
result = False
break
s = 0
pos = a
if s in [1, 2]:
result = False
out(("No", "Yes")[result])
``` | output | 1 | 49,881 | 7 | 99,763 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,882 | 7 | 99,764 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
import sys;z=sys.stdin.readline;w=lambda:map(int,z().split())
for _ in[8]*int(z()):
z();_,m=w();d=l=0
for x,y in sorted([*w()][::-1]for _ in [8]*m):
d+=(x+y)%2*2-1
if abs(d)>1 or(l==x and d):d=m
l=x
print('no'if d else'yes')
``` | output | 1 | 49,882 | 7 | 99,765 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled. | instruction | 0 | 49,883 | 7 | 99,766 |
Tags: brute force, dp, graph matchings, greedy, sortings
Correct Solution:
```
t = int(input())
for tt in range(t):
input()
n,m = map(int,input().split())
a = []
for i in range(m):
r,c = map(int,input().split())
a.append([c,r])
a.sort()
c = 0
bc,br = -1,-1
start = a[0][0]
end = a[-1][0]
flg = False
# print(a)
while(start<=end):
# print(c,m)
if(c<m-2):
if(a[c+1][0]==a[c+2][0]):
flg = True
break
if(c<m-1):
if(a[c][0]==a[c+1][0]):
if(c<m-2):
start = a[c+2][0]
c+=2
else:
end = -1
else:
# print(c)
if(a[c+1][1]==a[c][1]):
if((a[c+1][0]-a[c][0])%2!=0):
if(c<m-2):
start = a[c+2][0]
c+=2
else:
end = -1
else:
# print("YESSSS")
flg = True
end = -1
else:
if((a[c+1][0]-a[c][0])%2==0):
if(c<m-2):
start = a[c+2][0]
c+=2
else:
end = -1
else:
flg = True
end = -1
elif(c==m-1):
flg = True
end = -1
else:
break
if(flg):
print("NO")
else:
print("YES")
``` | output | 1 | 49,883 | 7 | 99,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
import sys,io,os;Z=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline;o=[]
for _ in range(int(Z())):
Z();n,m=map(int,Z().split());p=[(0,0),(0,1)]
for i in range(m):r,c=map(int,Z().split());r-=1;p.append((c,r))
p.sort();p+=[(n+1,0),(n+1,1)];v=-2;i=0
while i<m+4:
b=p[i][0]==p[i+1][0];p[i]=(v+2-(p[i][0]-v)%2,p[i][1]);i+=1
if b:p[i]=(v+2-(p[i][0]-v)%2,p[i][1]);i+=1
v=p[i-1][0]
x=[0]*(2*p[-1][0]+2);y=1
for i in p:x[2*i[0]+i[1]]=1
for i in range(p[-1][0]):
if x[2*i]==0:
if x[2*i+1]<1:continue
if x[2*i+2]:y=0;break
x[2*i+2]=1;continue
if x[2*i+1]<1:
if x[2*i+3]:y=0;break
x[2*i+3]=1
o.append(["NO","YES"][y])
print('\n'.join(o))
``` | instruction | 0 | 49,884 | 7 | 99,768 |
Yes | output | 1 | 49,884 | 7 | 99,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
#### IMPORTANT LIBRARY ####
############################
### DO NOT USE import random --> 250ms to load the library
############################
### In case of extra libraries: https://github.com/cheran-senthil/PyRival
######################
####### IMPORT #######
######################
from functools import cmp_to_key
from collections import deque, Counter
from heapq import heappush, heappop
from math import log, ceil
######################
#### STANDARD I/O ####
######################
import sys
import os
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def print(*args, **kwargs):
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
def inp():
return sys.stdin.readline().rstrip("\r\n") # for fast input
def ii():
return int(inp())
def si():
return str(inp())
def li(lag = 0):
l = list(map(int, inp().split()))
if lag != 0:
for i in range(len(l)):
l[i] += lag
return l
def mi(lag = 0):
matrix = list()
for i in range(n):
matrix.append(li(lag))
return matrix
def lsi(): #string list
return list(map(str, inp().split()))
def print_list(lista, space = " "):
print(space.join(map(str, lista)))
######################
### BISECT METHODS ###
######################
def bisect_left(a, x):
"""i tale che a[i] >= x e a[i-1] < x"""
left = 0
right = len(a)
while left < right:
mid = (left+right)//2
if a[mid] < x:
left = mid+1
else:
right = mid
return left
def bisect_right(a, x):
"""i tale che a[i] > x e a[i-1] <= x"""
left = 0
right = len(a)
while left < right:
mid = (left+right)//2
if a[mid] > x:
right = mid
else:
left = mid+1
return left
def bisect_elements(a, x):
"""elementi pari a x nell'árray sortato"""
return bisect_right(a, x) - bisect_left(a, x)
######################
### MOD OPERATION ####
######################
MOD = 10**9 + 7
maxN = 5
FACT = [0] * maxN
INV_FACT = [0] * maxN
def add(x, y):
return (x+y) % MOD
def multiply(x, y):
return (x*y) % MOD
def power(x, y):
if y == 0:
return 1
elif y % 2:
return multiply(x, power(x, y-1))
else:
a = power(x, y//2)
return multiply(a, a)
def inverse(x):
return power(x, MOD-2)
def divide(x, y):
return multiply(x, inverse(y))
def allFactorials():
FACT[0] = 1
for i in range(1, maxN):
FACT[i] = multiply(i, FACT[i-1])
def inverseFactorials():
n = len(INV_FACT)
INV_FACT[n-1] = inverse(FACT[n-1])
for i in range(n-2, -1, -1):
INV_FACT[i] = multiply(INV_FACT[i+1], i+1)
def coeffBinom(n, k):
if n < k:
return 0
return multiply(FACT[n], multiply(INV_FACT[k], INV_FACT[n-k]))
######################
#### GRAPH ALGOS #####
######################
# ZERO BASED GRAPH
def create_graph(n, m, undirected = 1, unweighted = 1):
graph = [[] for i in range(n)]
if unweighted:
for i in range(m):
[x, y] = li(lag = -1)
graph[x].append(y)
if undirected:
graph[y].append(x)
else:
for i in range(m):
[x, y, w] = li(lag = -1)
w += 1
graph[x].append([y,w])
if undirected:
graph[y].append([x,w])
return graph
def create_tree(n, unweighted = 1):
children = [[] for i in range(n)]
if unweighted:
for i in range(n-1):
[x, y] = li(lag = -1)
children[x].append(y)
children[y].append(x)
else:
for i in range(n-1):
[x, y, w] = li(lag = -1)
w += 1
children[x].append([y, w])
children[y].append([x, w])
return children
def dist(tree, n, A, B = -1):
s = [[A, 0]]
massimo, massimo_nodo = 0, 0
distanza = -1
v = [-1] * n
while s:
el, dis = s.pop()
if dis > massimo:
massimo = dis
massimo_nodo = el
if el == B:
distanza = dis
for child in tree[el]:
if v[child] == -1:
v[child] = 1
s.append([child, dis+1])
return massimo, massimo_nodo, distanza
def diameter(tree):
_, foglia, _ = dist(tree, n, 0)
diam, _, _ = dist(tree, n, foglia)
return diam
def dfs(graph, n, A):
v = [-1] * n
s = [[A, 0]]
v[A] = 0
while s:
el, dis = s.pop()
for child in graph[el]:
if v[child] == -1:
v[child] = dis + 1
s.append([child, dis + 1])
return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges
def bfs(graph, n, A):
v = [-1] * n
s = deque()
s.append([A, 0])
v[A] = 0
while s:
el, dis = s.popleft()
for child in graph[el]:
if v[child] == -1:
v[child] = dis + 1
s.append([child, dis + 1])
return v #visited: -1 if not visited, otherwise v[B] is the distance in terms of edges
#FROM A GIVEN ROOT, RECOVER THE STRUCTURE
def parents_children_root_unrooted_tree(tree, n, root = 0):
q = deque()
visited = [0] * n
parent = [-1] * n
children = [[] for i in range(n)]
q.append(root)
while q:
all_done = 1
visited[q[0]] = 1
for child in tree[q[0]]:
if not visited[child]:
all_done = 0
q.appendleft(child)
if all_done:
for child in tree[q[0]]:
if parent[child] == -1:
parent[q[0]] = child
children[child].append(q[0])
q.popleft()
return parent, children
# CALCULATING LONGEST PATH FOR ALL THE NODES
def all_longest_path_passing_from_node(parent, children, n):
q = deque()
visited = [len(children[i]) for i in range(n)]
downwards = [[0,0] for i in range(n)]
upward = [1] * n
longest_path = [1] * n
for i in range(n):
if not visited[i]:
q.append(i)
downwards[i] = [1,0]
while q:
node = q.popleft()
if parent[node] != -1:
visited[parent[node]] -= 1
if not visited[parent[node]]:
q.append(parent[node])
else:
root = node
for child in children[node]:
downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse = True)[0:2]
s = [node]
while s:
node = s.pop()
if parent[node] != -1:
if downwards[parent[node]][0] == downwards[node][0] + 1:
upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
else:
upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
for child in children[node]:
s.append(child)
return longest_path
### TBD SUCCESSOR GRAPH 7.5
### TBD TREE QUERIES 10.2 da 2 a 4
### TBD ADVANCED TREE 10.3
### TBD GRAPHS AND MATRICES 11.3.3 e 11.4.3 e 11.5.3 (ON GAMES)
######################
## END OF LIBRARIES ##
######################
for test in range(ii()):
inp()
n,m=li()
black = []
for i in range(m):
r,c = li(-1)
black.append(2*c + r)
black.sort()
if m % 2 == 1:
print("NO")
else:
ok = 1
for i in range(m//2):
primo = black[2*i]
secondo = black[2*i+1]
if 2*i+2 < m:
terzo = black[2*i + 2]
if secondo // 2 == terzo // 2:
ok = 0
c1 = primo // 2
c2 = secondo // 2
r1 = primo % 2
r2 = secondo % 2
if r1 != r2:
if abs(c1-c2) % 2 == 1:
ok = 0
else:
if abs(c1-c2) % 2 == 0:
ok = 0
if ok:
print("YES")
else:
print("NO")
``` | instruction | 0 | 49,885 | 7 | 99,770 |
Yes | output | 1 | 49,885 | 7 | 99,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
for _ in range(int(input())):
non = input()
n, m = map(int, input().split())
blocks = []
for b in range(m):
x, y = map(int, input().split())
blocks.append((x,y))
if m%2==1:
print("NO")
continue
blocks.sort(key=lambda x:x[1])
i = 0
while i <m-1:
block1, block2, block3 = blocks[i], blocks[i+1], (0,-1)
if i<m-2:
block3 = blocks[i+2]
if block1[1] == block2[1]:
i+=2
continue
elif block2[1] == block3[1]:
print("NO")
break
if block1[0] == block2[0]:
if (block2[1] - block1[1])%2==0:
print("NO")
break
else:
i+=2
continue
else:
if (block2[1] - block1[1])%2==1:
print("NO")
break
else:
i+=2
continue
if i>= m:
print("YES")
``` | instruction | 0 | 49,886 | 7 | 99,772 |
Yes | output | 1 | 49,886 | 7 | 99,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import *
for _ in range(int(input())):
input()
n, m = map(int, input().split())
mask = defaultdict(int)
for _ in range(m):
r, c = map(int, input().split())
mask[c] += 1<<(r-1)
mask[n+1] = 3
ks = list(mask.keys())
ks.sort()
last_row = -1
flag = True
for i in range(len(ks)):
if mask[ks[i]]==3:
if last_row!=-1:
flag = False
else:
if last_row==-1:
if mask[ks[i]]==1:
last_row = 1
else:
last_row = 0
else:
r = (ks[i]-ks[i-1]-1+last_row)%2
if (mask[ks[i]]>>r)&1:
flag = False
last_row = -1
if flag:
print('YES')
else:
print('NO')
``` | instruction | 0 | 49,887 | 7 | 99,774 |
Yes | output | 1 | 49,887 | 7 | 99,775 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
###########################
# Sorted list
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
# self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
# self.lista[a] += self.lista[b]
# self.lista[b] = []
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
#
# to find factorial and ncr
# tot = 200005
# mod = 10**9 + 7
# fac = [1, 1]
# finv = [1, 1]
# inv = [0, 1]
#
# for i in range(2, tot + 1):
# fac.append((fac[-1] * i) % mod)
# inv.append(mod - (inv[mod % i] * (mod // i) % mod))
# finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def arr1d(n, v):
return [v] * n
def arr2d(n, m, v):
return [[v] * m for _ in range(n)]
def arr3d(n, m, p, v):
return [[[v] * p for _ in range(m)] for i in range(n)]
def solve():
inp()
n,m=sep()
d=defaultdict(list)
s=set()
for i in range(m):
r,c=sep()
if(c-1 > 0):s.add(c-1)
if(c+1<n) : s.add(c+1)
s.add(c)
d[c].append(r)
so=sorted(s)
ar=[[0] *2 for _ in range(len(so)+2)]
n=len(so)
for i in range(n):
if d[so[i]]:
for j in d[so[i]]: ar[i+1][j-1]=1
dp=[[0]*3 for _ in range(n+2)]
dp[0][0]=1
for i in range(1,n+1):
if (ar[i][0]==1 and ar[i][1]==1):
dp[i][0]=dp[i-1][0]
continue
if (ar[i][0]==1):
dp[i][1]=dp[i-1][0]
dp[i][0]=dp[i-1][1]
continue
if (ar[i][1]==1):
dp[i][2]=dp[i-1][0]
dp[i][0]=dp[i-1][2]
continue
dp[i][0]=dp[i-1][0]
dp[i][1]=dp[i-1][2]
dp[i][2]=dp[i-1][1]
if(dp[n][0]==1):
YES()
else:
NO()
#
# for i in ar:
# print(i)
# print("//////////////////////")
#solve()
testcase(int(inp()))
``` | instruction | 0 | 49,888 | 7 | 99,776 |
No | output | 1 | 49,888 | 7 | 99,777 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
for nt in range(int(input())):
input()
n, m = map(int,input().split())
block = []
area = [[0, 0] for i in range(n)]
for i in range(m):
x, y = map(int,input().split())
block.append([y-1, x-1])
area[y-1][x-1] = 1
arr = []
i = 0
while i<n:
if area[i].count(0)==2 and (i<n-1 and area[i+1].count(0)==2):
i += 2
continue
elif area[i].count(0)==2 and (i<n-1 and area[i+1].count(0)!=2):
i += 1
continue
elif area[i].count(0)==2:
break
elif area[i].count(0)==0:
i += 1
continue
arr.append(area[i])
if i<n-1:
arr.append(area[i+1])
i += 2
else:
i += 1
n = len(arr)
i = 0
ans = "YES"
# print (arr)
while i<n:
if arr[i][0]==0 and arr[i][1]==0:
i += 1
continue
if arr[i][0]==1:
if i==n-1 or arr[i+1].count(1)==2:
ans = "NO"
break
if arr[i+1][0]==1 and arr[i+1][1]==0:
i += 2
elif arr[i+1][0]==0 and arr[i+1][1]==1:
ans = "NO"
break
elif arr[i+1][0]==0 and arr[i+1][1]==0:
arr[i+1][1] = 1
i += 1
else:
if i==n-1 or arr[i+1].count(1)==2:
ans = "NO"
break
if arr[i+1][1]==1 and arr[i+1][0]==0:
i += 2
elif arr[i+1][0]==1 and arr[i+1][1]==0:
ans = "NO"
break
elif arr[i+1][0]==0 and arr[i+1][1]==0:
arr[i+1][0] = 1
i += 1
print (ans)
``` | instruction | 0 | 49,889 | 7 | 99,778 |
No | output | 1 | 49,889 | 7 | 99,779 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
z=input;w=lambda:map(int,z().split());u=int(z())
while u:=u-1:
z();_,m=w();d=l=0
for x,y in sorted([*w()][::-1]for _ in [8]*m):
if abs(d:=d+(x+y)%2*2-1)>1 or l==x and d:d=m
l=x
print('no'if d else'yes')
``` | instruction | 0 | 49,890 | 7 | 99,780 |
No | output | 1 | 49,890 | 7 | 99,781 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Every year Santa Claus gives gifts to all children. However, each country has its own traditions, and this process takes place in different ways. For example, in Berland you need to solve the New Year's puzzle.
Polycarp got the following problem: given a grid strip of size 2 × n, some cells of it are blocked. You need to check if it is possible to tile all free cells using the 2 × 1 and 1 × 2 tiles (dominoes).
For example, if n = 5 and the strip looks like this (black cells are blocked):
<image>
Then it can be tiled, for example, using two vertical and two horizontal tiles, as in the picture below (different tiles are marked by different colors).
<image>
And if n = 3 and the strip looks like this:
<image>
It is impossible to tile free cells.
Polycarp easily solved this task and received his New Year's gift. Can you solve it?
Input
The first line contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases. Then t test cases follow.
Each test case is preceded by an empty line.
The first line of each test case contains two integers n and m (1 ≤ n ≤ 10^9, 1 ≤ m ≤ 2 ⋅ 10^5) — the length of the strip and the number of blocked cells on it.
Each of the next m lines contains two integers r_i, c_i (1 ≤ r_i ≤ 2, 1 ≤ c_i ≤ n) — numbers of rows and columns of blocked cells. It is guaranteed that all blocked cells are different, i.e. (r_i, c_i) ≠ (r_j, c_j), i ≠ j.
It is guaranteed that the sum of m over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, print on a separate line:
* "YES", if it is possible to tile all unblocked squares with the 2 × 1 and 1 × 2 tiles;
* "NO" otherwise.
You can output "YES" and "NO" in any case (for example, the strings yEs, yes, Yes and YES will be recognized as positive).
Example
Input
3
5 2
2 2
1 4
3 2
2 1
2 3
6 4
2 1
2 3
2 4
2 6
Output
YES
NO
NO
Note
The first two test cases are explained in the statement.
In the third test case the strip looks like this:
<image> It is easy to check that the unblocked squares on it can not be tiled.
Submitted Solution:
```
import bisect
import sys
data = sys.stdin.read().split("\n")[::-1]
def input():
return data.pop()
def solve(strip, n):
if n == 1:
return strip.get(0, 0) in (0, 3)
strip[n] = 3
keys = sorted(strip)
dp_prev = [0] * 4
dp_prev[strip.get(0, 0)] = 1
i = 1
while i <= n:
if i not in strip:
i = keys[bisect.bisect_right(keys, i)] - 1
red = strip.get(i, 0)
dp = [0] * 4
if dp_prev[0] or dp_prev[3]:
dp[red] = 1
if dp_prev[1]:
if (red & 2) == 0:
dp[red | 2] = 1
if dp_prev[2]:
if (red & 1) == 0:
dp[red | 1] = 1
dp_prev = dp
i += 1
return dp_prev[3]
for _ in range(int(input())):
_ = input()
n, m = map(int, input().split())
strip = {}
for _ in range(m):
r, c = map(int, input().split())
r -= 1
c -= 1
strip[c] = 1 << r
print("YES" if solve(strip, n) else "NO")
``` | instruction | 0 | 49,891 | 7 | 99,782 |
No | output | 1 | 49,891 | 7 | 99,783 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a board represented as a grid with 2 × n cells.
The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black.
You have w white dominoes (2 × 1 tiles, both cells are colored in white) and b black dominoes (2 × 1 tiles, both cells are colored in black).
You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.
Can you place all w + b dominoes on the board if you can place dominoes both horizontally and vertically?
Input
The first line contains a single integer t (1 ≤ t ≤ 3000) — the number of test cases.
The first line of each test case contains three integers n, k_1 and k_2 (1 ≤ n ≤ 1000; 0 ≤ k_1, k_2 ≤ n).
The second line of each test case contains two integers w and b (0 ≤ w, b ≤ n).
Output
For each test case, print YES if it's possible to place all w + b dominoes on the board and NO, otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
1 0 1
1 0
1 1 1
0 0
3 0 0
1 3
4 3 1
2 2
5 4 3
3 1
Output
NO
YES
NO
YES
YES
Note
In the first test case, n = 1, k_1 = 0 and k_2 = 1. It means that 2 × 1 board has black cell (1, 1) and white cell (2, 1). So, you can't place any white domino, since there is only one white cell.
In the second test case, the board of the same size 2 × 1, but both cell are white. Since w = 0 and b = 0, so you can place 0 + 0 = 0 dominoes on the board.
In the third test case, board 2 × 3, but fully colored in black (since k_1 = k_2 = 0), so you can't place any white domino.
In the fourth test case, cells (1, 1), (1, 2), (1, 3), and (2, 1) are white and other cells are black. You can place 2 white dominoes at positions ((1, 1), (2, 1)) and ((1, 2), (1, 3)) and 2 black dominoes at positions ((1, 4), (2, 4)) ((2, 2), (2, 3)). | instruction | 0 | 49,892 | 7 | 99,784 |
Tags: combinatorics, constructive algorithms, math
Correct Solution:
```
t = int(input())
for _ in range(t):
n,k1,k2 = list(map(int , input().split()))
w,b = list(map(int , input().split()))
odd_w = w & 1
odd_b = b & 1
if odd_w ^ odd_w:
print('NO')
else:
whites = k1 + k2
blacks = 2*n-k1-k2
ans = 'YES' if w*2 <= whites and b*2 <= blacks else 'NO'
print(ans)
``` | output | 1 | 49,892 | 7 | 99,785 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a board represented as a grid with 2 × n cells.
The first k_1 cells on the first row and first k_2 cells on the second row are colored in white. All other cells are colored in black.
You have w white dominoes (2 × 1 tiles, both cells are colored in white) and b black dominoes (2 × 1 tiles, both cells are colored in black).
You can place a white domino on the board if both board's cells are white and not occupied by any other domino. In the same way, you can place a black domino if both cells are black and not occupied by any other domino.
Can you place all w + b dominoes on the board if you can place dominoes both horizontally and vertically?
Input
The first line contains a single integer t (1 ≤ t ≤ 3000) — the number of test cases.
The first line of each test case contains three integers n, k_1 and k_2 (1 ≤ n ≤ 1000; 0 ≤ k_1, k_2 ≤ n).
The second line of each test case contains two integers w and b (0 ≤ w, b ≤ n).
Output
For each test case, print YES if it's possible to place all w + b dominoes on the board and NO, otherwise.
You may print every letter in any case you want (so, for example, the strings yEs, yes, Yes and YES are all recognized as positive answer).
Example
Input
5
1 0 1
1 0
1 1 1
0 0
3 0 0
1 3
4 3 1
2 2
5 4 3
3 1
Output
NO
YES
NO
YES
YES
Note
In the first test case, n = 1, k_1 = 0 and k_2 = 1. It means that 2 × 1 board has black cell (1, 1) and white cell (2, 1). So, you can't place any white domino, since there is only one white cell.
In the second test case, the board of the same size 2 × 1, but both cell are white. Since w = 0 and b = 0, so you can place 0 + 0 = 0 dominoes on the board.
In the third test case, board 2 × 3, but fully colored in black (since k_1 = k_2 = 0), so you can't place any white domino.
In the fourth test case, cells (1, 1), (1, 2), (1, 3), and (2, 1) are white and other cells are black. You can place 2 white dominoes at positions ((1, 1), (2, 1)) and ((1, 2), (1, 3)) and 2 black dominoes at positions ((1, 4), (2, 4)) ((2, 2), (2, 3)). | instruction | 0 | 49,893 | 7 | 99,786 |
Tags: combinatorics, constructive algorithms, math
Correct Solution:
```
T = int( input() )
for t in range(T):
(n, k1, k2) = [ int(i) for i in input().split(' ') ]
(w,b) = [ int(i) for i in input().split(' ') ]
wTot = int( (k1+k2)/2 )
bTot = int( ((2*n) - k1-k2 )/2 )
#print(n, k1, k2, w, b, wTot, bTot)
if (bTot >= b) and (wTot >= w):
print("YES")
else:
print("NO")
``` | output | 1 | 49,893 | 7 | 99,787 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.