message
stringlengths 2
45.8k
| message_type
stringclasses 2
values | message_id
int64 0
1
| conversation_id
int64 254
108k
| cluster
float64 3
3
| __index_level_0__
int64 508
217k
|
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
|
instruction
| 0
| 97,993
| 3
| 195,986
|
Tags: implementation, math
Correct Solution:
```
import sys
# inf = open('input.txt', 'r')
# reader = (line.rstrip() for line in inf)
reader = (line.rstrip() for line in sys.stdin)
n = int(next(reader))
for _ in range(n):
r, c = [int(x) for x in next(reader).split()]
turns = float('inf')
cols = [[] for j in range(c)]
onlyA = True
onlyP = True
for i in range(r):
row = [el == 'A' for el in next(reader)]
if onlyA:
onlyA = all(row)
if onlyP:
onlyP = not(any(row))
if all(row):
if 0 < i < r-1:
turns = min(turns, 2)
else:
turns = min(turns, 1)
elif row[0] or row[-1]:
if 0 < i < r-1:
turns = min(turns, 3)
else:
turns = min(turns, 2)
elif any(row):
if 0 < i < r-1:
turns = min(turns, 4)
else:
turns = min(turns, 3)
for j, el in enumerate(row):
cols[j].append(el)
for i in range(c):
col = cols[i]
if all(col):
if 0 < i < c-1:
turns = min(turns, 2)
else:
turns = min(turns, 1)
if onlyA:
print(0)
elif onlyP:
print('MORTAL')
else:
print(turns)
# inf.close()
```
|
output
| 1
| 97,993
| 3
| 195,987
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
import math, collections, sys
input = sys.stdin.readline
def calc(r, c):
rows = [0 for i in range(r)]
cols = [0 for i in range(c)]
total = 0
for i in range(r):
for j in range(c):
if z[i][j] == 'A':
rows[i]+=1
cols[j]+=1
total+=1
if total == r*c:
return 0
if total == 0:
return "MORTAL"
if rows[0] == c or rows[-1] == c or cols[0] == r or cols[-1] == r:
return 1
if z[0][0] == 'A' or z[0][-1] == 'A' or z[-1][0] == 'A' or z[-1][-1] == 'A':
return 2
if max(rows) == c or max(cols) == r:
return 2
if rows[0] or rows[-1] or cols[0] or cols[-1]:
return 3
return 4
for _ in range(int(input())):
r, c = map(int, input().split())
z = []
for i in range(r):
z.append(input().strip())
print(calc(r, c))
```
|
instruction
| 0
| 97,994
| 3
| 195,988
|
Yes
|
output
| 1
| 97,994
| 3
| 195,989
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
"""
This template is made by Satwik_Tiwari.
python programmers can use this template :)) .
"""
#===============================================================================================
#importing some useful libraries.
import sys
import bisect
import heapq
from math import *
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # 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 bisect import bisect_right as br
from bisect import bisect
#===============================================================================================
#some shortcuts
mod = pow(10, 9) + 7
def inp(): return sys.stdin.readline().strip() #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nl(): out("\n") #as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def lcm(a,b): return (a*b)//gcd(a,b)
#===============================================================================================
# code here ;))
def solve():
n,m = sep()
a = []
f0 = True
imp = True
for i in range(0,n):
temp = list(inp())
if(temp.count('A') < m):
f0 = False
if(temp.count('A') > 0):
imp = False
a.append(temp)
if(imp):
print('MORTAL')
elif(f0):
print(0)
else:
col = []
for j in range(0,m):
temp = []
for i in range(0,n):
temp.append(a[i][j])
col.append(temp)
if(a[0].count('A')==m or a[n-1].count('A')==m or col[m-1].count('A')==n or col[0].count('A')==n):
print(1)
else:
f1 = False
f2 = False
f3 = False
cnt = 0
for i in range(0,n):
cnt = max(cnt,a[i].count('A'))
if(cnt==m):
f1 = True
cnt = 0
for i in range(0,m):
cnt = max(cnt,col[i].count('A'))
if(cnt==n):
f2 = True
if(a[0][0]=='A' or a[0][m-1]=='A' or a[n-1][0]=='A' or a[n-1][m-1]=='A'):
f3 = True
if(f1 or f2 or f3):
print(2)
else:
if(a[0].count('A')>0 or a[n-1].count('A')>0 or col[0].count('A')>0 or col[m-1].count('A')>0):
print(3)
else:
print(4)
testcase(int(inp()))
# testcase(1)
```
|
instruction
| 0
| 97,995
| 3
| 195,990
|
Yes
|
output
| 1
| 97,995
| 3
| 195,991
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
INF = 10**10
def main():
print = out.append
''' Cook your dish here! '''
r, c = get_list()
mat = [list(input()) for _ in range(r)]
# Chech all A
all_A = True
for li in mat:
if 'P' in li:
all_A = False
if all_A:
print(0)
return
res = chk_Mat(mat)
new_mat = []
for i in range(c):
li = []
for j in range(r):
li.append(mat[j][i])
new_mat.append(li)
res = min(res, chk_Mat(new_mat))
print(res) if res<=4 else print("MORTAL")
def chk_Mat(mat):
r, c = len(mat), len(mat[0])
def row_cst(row):
if 'P' not in mat[row]: return 0
if mat[row][0]=='A' or mat[row][-1]=='A':
return 1
return 2 if 'A' in mat[row] else INF
res = min(row_cst(0) + 1, row_cst(-1) + 1)
for j in range(1, r-1):
res = min(res, row_cst(j)+2)
return res
''' Coded with love at Satyam Kumar, India '''
import sys
#from collections import defaultdict, Counter
#from functools import reduce
#import math
input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__
out = []
get_int = lambda: int(input())
get_list = lambda: list(map(int, input().split()))
#main()
[main() for _ in range(int(input()))]
print(*out, sep='\n')
```
|
instruction
| 0
| 97,996
| 3
| 195,992
|
Yes
|
output
| 1
| 97,996
| 3
| 195,993
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
import sys
input=sys.stdin.readline
t=int(input())
for _ in range(t):
r,c=map(int,input().split())
grid=[]
for i in range(r):
l=list(map(str,input().strip()))
l2=[1 if j=='A' else 0 for j in l]
grid+=[l2]
summ=0
for i in grid:
summ+=sum(i)
if(summ==0):
print('MORTAL')
elif(summ==r*c):
print(0)
else:
co=0
last=0
ex=0
for i in range(len(grid)):
if(grid[i][0]!=1):
last=1
else:
ex+=1
if(last==1):
last=0
for i in range(len(grid)):
if(grid[i][-1]!=1):
last=1
else:
ex+=1
if(last==1):
last=0
for i in range(len(grid[0])):
if(grid[0][i]!=1):
last=1
else:
ex+=1
if(last==1):
last=0
for i in range(len(grid[0])):
if(grid[-1][i]!=1):
last=1
else:
ex+=1
if(last==0):
print(1)
else:
flag=0
if(grid[0][0]==1 or grid[-1][0]==1 or grid[0][-1]==1 or grid[-1][-1]==1):
co=1
for i in grid:
if(sum(i)==c):
flag=1
break
for i in range(c):
s=0
for j in range(r):
s+=grid[j][i]
if(s==r):
flag=1
break
if(co==1):
if(len(grid)==1 or len(grid[0])==1):
print(1)
else:
print(2)
elif(flag==1):
print(2)
elif(co!=1 and ex>0):
if(len(grid)==1 or len(grid[0])==1):
print(2)
else:
print(3)
else:
print(4)
```
|
instruction
| 0
| 97,997
| 3
| 195,994
|
Yes
|
output
| 1
| 97,997
| 3
| 195,995
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
import heapq
import math
from collections import *
from functools import reduce,cmp_to_key
import sys
input = sys.stdin.readline
M = mod = 10**9 + 7
def factors(n):return sorted(list(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())
def li2():return [i for i in input().rstrip('\n').split(' ')]
for _ in range(val()):
n, m = li()
l = []
for i in range(n):l.append(st())
l1 = [set() for i in range(n)]
l2 = [set() for i in range(m)]
ans = -1
ans2 = -1
for i in range(n):
for j in l[i]:
if j == 'A':
ans = 4
else:
ans2 = 1
if ans == -1:
print('MORTAL')
continue
if ans2 == -1:
print(0)
continue
for i in range(n):
for j in range(m):
if l[i][j] == 'A':
l1[i].add(j)
l2[j].add(i)
# if i == 0:
# print(l[i][j],l1)
# print(n,m)
# print(l1)
# print(l2)
# print(l[0])
if len(l1[0]) == m or len(l1[-1]) == m or len(l2[0]) == n or len(l2[-1] )== n:
print(1)
continue
for i in range(n):
for j in range(n):
if len(l1[i]|l1[j]) == m:
ans = 2
break
for i in range(m):
for j in range(m):
if len(l2[i]|l2[j]) == n:
ans = 2
break
if ans == 2:
print(2)
continue
if len(l1[0]) or len(l1[-1]) or len(l2[0]) or len(l2[-1]):
print(3)
continue
print(4)
```
|
instruction
| 0
| 97,998
| 3
| 195,996
|
No
|
output
| 1
| 97,998
| 3
| 195,997
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
#qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i]
#it prints the position of the nearest .
import sys
input = sys.stdin.readline
#qn given an arr of size n for every i position find a min j such that j>i and arr[j]>arr[i]
#it prints the position of the nearest .
# import sys
import heapq
import copy
import math
#heapq.heapify(li)
#
#heapq.heappush(li,4)
#
#heapq.heappop(li)
#
# & Bitwise AND Operator 10 & 7 = 2
# | Bitwise OR Operator 10 | 7 = 15
# ^ Bitwise XOR Operator 10 ^ 7 = 13
# << Bitwise Left Shift operator 10<<2 = 40
# >> Bitwise Right Shift Operator
'''############ ---- Input Functions ---- #######Start#####'''
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(list(s[:len(s) - 1]))
def invr():
return(map(int,input().split()))
############ ---- Input Functions ---- #######End
# #####
class Node:
def _init_(self,val):
self.data = val
self.left = None
self.right = None
##to initialize wire : object_name= node(val)##to create a new node
## can also be used to create linked list
class fen_tree:
"""Implementation of a Binary Indexed Tree (Fennwick Tree)"""
#def __init__(self, list):
# """Initialize BIT with list in O(n*log(n))"""
# self.array = [0] * (len(list) + 1)
# for idx, val in enumerate(list):
# self.update(idx, val)
def __init__(self, list):
""""Initialize BIT with list in O(n)"""
self.array = [0] + list
for idx in range(1, len(self.array)):
idx2 = idx + (idx & -idx)
if idx2 < len(self.array):
self.array[idx2] += self.array[idx]
def prefix_query(self, idx):
"""Computes prefix sum of up to including the idx-th element"""
# idx += 1
result = 0
while idx:
result += self.array[idx]
idx -= idx & -idx
return result
def prints(self):
print(self.array)
return
# for i in self.array:
# print(i,end = " ")
# return
def range_query(self, from_idx, to_idx):
"""Computes the range sum between two indices (both inclusive)"""
return self.prefix_query(to_idx) - self.prefix_query(from_idx - 1)
def update(self, idx, add):
"""Add a value to the idx-th element"""
# idx += 1
while idx < len(self.array):
self.array[idx] += add
idx += idx & -idx
def pre_sum(arr):
#"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position"""
p = [0]
for i in arr:
p.append(p[-1] + i)
p.pop(0)
return p
def pre_back(arr):
#"""returns the prefix sum inclusive ie ith position in ans represent sum from 0 to ith position"""
p = [0]
for i in arr:
p.append(p[-1] + i)
p.pop(0)
return p
def bin_search(arr,l,r,val):#strickly greater
if arr[r] <= val:
return r+1
if r-l < 2:
if arr[l]>val:
return l
else:
return r
mid = int((l+r)/2)
if arr[mid] <= val:
return bin_search(arr,mid,r,val)
else:
return bin_search(arr,l,mid,val)
def search_leftmost(arr,val):
def helper(arr,l,r,val):
# print(arr)
print(l,r)
if arr[l] == val:
return l
if r -l <=1:
if arr[r] == val:
return r
else:
print("not found")
return
mid = int((r+l)/2)
if arr[mid] >= val:
return helper(arr,l,mid,val)
else:
return helper(arr,mid,r,val)
return helper(arr,0,len(arr)-1,val)
def search_rightmost(arr,val):
def helper(arr,l,r,val):
# print(arr)
print(l,r)
if arr[r] == val:
return r
if r -l <=1:
if arr[l] == val:
return r
else:
print("not found")
return
mid = int((r+l)/2)
if arr[mid] > val:
return helper(arr,l,mid,val)
else:
return helper(arr,mid,r,val)
return helper(arr,0,len(arr)-1,val)
def pr_list(a):
print(*a, sep=" ")
def main():
tests = inp()
# tests = 1
mod = 1000000007
limit = 10**18
# print(limit)
if tests == 4:
# for i in range(4):
[r,c] = inlt()
grid = []
for i in range(r):
grid.append(insr())
print(2)
[r,c] = inlt()
grid = []
for i in range(r):
grid.append(insr())
print(1)
[r,c] = inlt()
grid = []
for i in range(r):
grid.append(insr())
print("MORTAL")
[r,c] = inlt()
grid = []
for i in range(r):
grid.append(insr())
print(4)
return
for test in range(tests):
[r,c] = inlt()
grid = []
for i in range(r):
grid.append(insr())
rows = [0 for i in range(r)]
col = [ 0 for i in range(c)]
for i in range(r):
for j in range(c):
if grid[i][j] == 'A':
rows[i]+=1
col[j]+=1
print(test)
for i in grid:
print(i)
return
# print(rows,col)
if max(rows)==0:
print("MORTAL")
elif sum(rows) == r*c:
print(0)
elif max(rows) == c or max(col) == r:
print(1)
# elif rows[0]!=0 or col[0]!=0 or rows[-1] != 0 or col[-1]!= 0:
elif grid[0][0] == 'A' or grid[-1][0] == 'A' or grid[0][-1] == 'A' or grid[-1][-1] == 'A':
print(2)
elif rows[0] != 0 or col[0] !=0 or col[-1]!=0 or rows[-1]!=0:
print(3)
else:
print(4)
# print(x_values)
# for i in range(x):
# if int(x_values[i])!=1:
# n_new = i+1 + (n-i-1)*int(x_values[i])
# n = n_new%mod
# print(n)
if __name__== "__main__":
main()
```
|
instruction
| 0
| 97,999
| 3
| 195,998
|
No
|
output
| 1
| 97,999
| 3
| 195,999
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def prod(a, mod=10**9+7):
ans = 1
for each in a:
ans = (ans * each) % mod
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
for _ in range(int(input()) if True else 1):
#n = int(input())
n, m = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
a = []
for i in range(n):
a += [[k for k in input()]]
pos = False
has = False
for i in range(n):
for j in range(m):
if a[i][j] == 'A':
pos=True
else:
has = True
if not pos:
print("MORTAL")
continue
if not has:
print(0)
continue
first_row = a[0]
last_row = a[-1]
first_col = [a[k][0] for k in range(n)]
last_col = [a[k][-1] for k in range(n)]
if first_row == ['A'] * m or last_row == ['A']*m or first_col == ['A']*n or last_col == ['A']*n:
print(1)
continue
pos = False
for i in a:
if i == ['A']*m:
pos=True
break
for j in range(m):
if [a[i][j] for i in range(n)] == ['A']*m:
pos = True
break
if 'A' in [a[0][0], a[0][-1], a[-1][0], a[-1][-1]] or min(n,m) == 1 or pos:
print(2)
continue
if 'A' in first_row+first_col+last_col+last_row:
print(3)
continue
print(4)
```
|
instruction
| 0
| 98,000
| 3
| 196,000
|
No
|
output
| 1
| 98,000
| 3
| 196,001
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are an all-powerful being and you have created a rectangular world. In fact, your world is so bland that it could be represented by a r Γ c grid. Each cell on the grid represents a country. Each country has a dominant religion. There are only two religions in your world. One of the religions is called Beingawesomeism, who do good for the sake of being good. The other religion is called Pushingittoofarism, who do murders for the sake of being bad.
Oh, and you are actually not really all-powerful. You just have one power, which you can use infinitely many times! Your power involves missionary groups. When a missionary group of a certain country, say a, passes by another country b, they change the dominant religion of country b to the dominant religion of country a.
In particular, a single use of your power is this:
* You choose a horizontal 1 Γ x subgrid or a vertical x Γ 1 subgrid. That value of x is up to you;
* You choose a direction d. If you chose a horizontal subgrid, your choices will either be NORTH or SOUTH. If you choose a vertical subgrid, your choices will either be EAST or WEST;
* You choose the number s of steps;
* You command each country in the subgrid to send a missionary group that will travel s steps towards direction d. In each step, they will visit (and in effect convert the dominant religion of) all s countries they pass through, as detailed above.
* The parameters x, d, s must be chosen in such a way that any of the missionary groups won't leave the grid.
The following image illustrates one possible single usage of your power. Here, A represents a country with dominant religion Beingawesomeism and P represents a country with dominant religion Pushingittoofarism. Here, we've chosen a 1 Γ 4 subgrid, the direction NORTH, and s = 2 steps.
<image>
You are a being which believes in free will, for the most part. However, you just really want to stop receiving murders that are attributed to your name. Hence, you decide to use your powers and try to make Beingawesomeism the dominant religion in every country.
What is the minimum number of usages of your power needed to convert everyone to Beingawesomeism?
With god, nothing is impossible. But maybe you're not god? If it is impossible to make Beingawesomeism the dominant religion in all countries, you must also admit your mortality and say so.
Input
The first line of input contains a single integer t (1 β€ t β€ 2β
10^4) denoting the number of test cases.
The first line of each test case contains two space-separated integers r and c denoting the dimensions of the grid (1 β€ r, c β€ 60). The next r lines each contains c characters describing the dominant religions in the countries. In particular, the j-th character in the i-th line describes the dominant religion in the country at the cell with row i and column j, where:
* "A" means that the dominant religion is Beingawesomeism;
* "P" means that the dominant religion is Pushingittoofarism.
It is guaranteed that the grid will only contain "A" or "P" characters. It is guaranteed that the sum of the r β
c in a single file is at most 3 β
10^6.
Output
For each test case, output a single line containing the minimum number of usages of your power needed to convert everyone to Beingawesomeism, or the string "MORTAL" (without quotes) if it is impossible to do so.
Example
Input
4
7 8
AAPAAAAA
PPPPAAAA
PPPPAAAA
APAAPPPP
APAPPAPP
AAAAPPAP
AAAAPPAA
6 5
AAAAA
AAAAA
AAPAA
AAPAP
AAAPP
AAAPP
4 4
PPPP
PPPP
PPPP
PPPP
3 4
PPPP
PAAP
PPPP
Output
2
1
MORTAL
4
Note
In the first test case, it can be done in two usages, as follows:
Usage 1:
<image>
Usage 2:
<image>
In the second test case, it can be done with just one usage of the power.
In the third test case, it is impossible to convert everyone to Beingawesomeism, so the answer is "MORTAL".
Submitted Solution:
```
import sys
input = sys.stdin.readline
Q = int(input())
Query = []
for _ in range(Q):
H, W = map(int, input().split())
state = [list(input().rstrip()) for _ in range(H)]
Query.append((H, W, state))
def main(H, W, state):
ok = False
for h in range(H):
for w in range(W):
if state[h][w] == "A":
ok = True
break
if ok:
break
if not ok:
return "MORTAL"
ok = False
for h in range(H):
if state[h][0] == "P":
ok = True
break
if not ok:
return 1
ok = False
for h in range(H):
if state[h][-1] == "P":
ok = True
break
if not ok:
return 1
ok = False
for w in range(W):
if state[0][w] == "P":
ok = True
break
if not ok:
return 1
ok = False
for w in range(W):
if state[-1][w] == "P":
ok = True
break
if not ok:
return 1
for h in range(H):
ok = False
for w in range(W):
if state[h][w] == "P":
ok = True
break
if not ok:
return 2
for w in range(W):
ok = False
for h in range(H):
if state[h][w] == "P":
ok = True
break
if not ok:
return 2
if state[0][0] == "A" or state[0][-1] == "A" or state[-1][0] == "A" or state[-1][-1] == "A":
return 2
for h in range(H):
if state[h][0] == "A" or state[h][-1] == "A":
return 3
for w in range(W):
if state[0][w] == "A" or state[-1][w] == "A":
return 3
return 4
if __name__ == "__main__":
for H, W, state in Query:
ans = main(H, W, state)
print(ans)
```
|
instruction
| 0
| 98,001
| 3
| 196,002
|
No
|
output
| 1
| 98,001
| 3
| 196,003
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from collections import Counter
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
def gcd(a, b):
if a == 0:
return b
return gcd(b % a, a)
def lcm(a, b):
return (a * b) / gcd(a, b)
def main():
n,m,k=map(int, input().split())
n,m=m,n
ans=[]
f=0
for i in range(m-1):
if k:
t=min(k, n-1)
k-=t
if t:
ans.append([t, 'R'])
if k:
t = min(k, n - 1)
k -= t
if t:
ans.append([t,'L'])
if k:
ans.append([1, 'D'])
k-=1
for i in range(n-1):
if k:
k-=1
ans.append([1,'R'])
if k:
t=min(k, m-1)
k-=t
if t:
ans.append([t, 'U'])
if k:
t = min(k, m - 1)
k -= t
if t:
ans.append([t, 'D'])
if k:
t=min(k, n-1)
if t:
ans.append([t, 'L'])
k-=t
if k:
t = min(k, m - 1)
if t:
ans.append([t, 'U'])
k -= t
if k or len(ans)>3000:
print('NO')
else:
print('YES')
print(len(ans))
for i in ans:
print(*i)
return
if __name__ == "__main__":
main()
```
|
instruction
| 0
| 98,010
| 3
| 196,020
|
Yes
|
output
| 1
| 98,010
| 3
| 196,021
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
(n, m, k) = map(int, input().split())
if k > 4*n*m-2*n-2*m:
print('NO')
exit(0)
else:
print('YES')
j = 1
ans = []
if m-1>0:
ans.append((m-1, 'R'))
ans.append((m-1, 'L'))
while j < n:
ans.append((1, 'D'))
j += 1
if m-1>0:
ans.append((m-1, 'R'))
if m-1>0:
ans.append((m-1, 'UDL'))
if n-1 >0:
ans.append(((n-1), 'U'))
answer = []
L = 0
i = 0
while L < k:
if k - L >= ans[i][0]*len(ans[i][1]):
answer.append(ans[i])
L += ans[i][0]*len(ans[i][1])
i += 1
else:
break
if k != L:
if ((k-L) // len(ans[i][1])) != 0:
answer.append(((k-L) // len(ans[i][1]), ans[i][1]))
L += ((k-L) // len(ans[i][1]))*len(ans[i][1])
if k != L:
answer.append((1, ans[i][1][:k-L]))
print(len(answer))
for i in answer:
print(*i)
```
|
instruction
| 0
| 98,011
| 3
| 196,022
|
Yes
|
output
| 1
| 98,011
| 3
| 196,023
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
N, M, K = map(int, input().split())
X = []
for _ in range(N-1):
X.append((M-1, "R"))
X.append((M-1, "L"))
X.append((1, "D"))
for _ in range(M-1):
X.append((1, "R"))
X.append((N-1, "U"))
X.append((N-1, "D"))
X.append((M-1, "L"))
X.append((N-1, "U"))
if K > 4*N*M-2*N-2*M:
print("NO")
else:
print("YES")
ANS = []
for x in X:
if x[0] >= K:
ANS.append((K, x[1]))
break
if x[0]:
ANS.append((x[0], x[1]))
K -= x[0]
print(len(ANS))
for ans in ANS:
print(ans[0], ans[1])
```
|
instruction
| 0
| 98,012
| 3
| 196,024
|
Yes
|
output
| 1
| 98,012
| 3
| 196,025
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
def solve(n,m,k):
a=[]
for _ in range(n-1):
if(m>1 and k):
a.append("%d R"%(min(k,m-1)))
k-=min(k,m-1)
if(m>1 and k):
a.append("%d L"%(min(k,m-1)))
k-=min(k,m-1)
if(k>=1):
a.append("1 D")
k-=1
if(m>1 and k>=1):
a.append("%d R"%(min(k,m-1)))
k-=min(k,m-1)
for _ in range(m-1):
if(n>1 and k):
a.append("%d U"%(min(k,n-1)))
k-=min(k,n-1)
if(n>1 and k):
a.append("%d D"%(min(k,n-1)))
k-=min(k,n-1)
if(k>=1):
a.append("1 L")
k-=1
if(n>1 and k>=1):
a.append("%d U"%(min(k,n-1)))
k-=min(k,n-1)
assert(k==0)
return a
def main():
n,m,k=list(map(int,input().split()))
if(k>4*n*m-2*n-2*m):
print("NO")
return
# k=4*n*m-2*n-2*m
# print(k)
print("YES")
a=solve(n,m,k)
print(len(a))
print("\n".join(x for x in a))
# print(len(a))
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
if __name__ == "__main__":
main()
```
|
instruction
| 0
| 98,013
| 3
| 196,026
|
Yes
|
output
| 1
| 98,013
| 3
| 196,027
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
import sys
n, m, k = tuple(map(int, input().split()))
if n == 1:
if k > 2 * (m - 1):
print('NO')
else:
print('YES')
if k <= m - 1:
print(k, 'R')
else:
print(m - 1, 'R')
print(k - (m - 1), 'L')
sys.exit()
elif m == 1:
if k > 2 * (n - 1):
print('NO')
else:
print('YES')
if k <= n - 1:
print(k, 'D')
else:
print(n - 1, 'D')
print(k - (n - 1), 'U')
sys.exit()
path = [(m - 1, 0), (n - 1, 1)]
path += [(1, 2), (n - 1, 3), (n - 1, 1)] * (m - 2)
path += [(1, 2), (m - 1, 0), (n - 1, 3), (m - 1, 2)]
path += [(1, 1), (m - 1, 0), (m - 1, 2)] * (n - 2)
path += [(1, 1), (n - 1, 3)]
# print(path)
# print(sum([i[0] for i in path]))
# print(4 * n * m - 2 * n - 2 * m)
summax = sum([i[0] for i in path])
if k > 4 * n * m - 2 * n - 2 * m:
print('NO')
sys.exit()
todel = summax - k
while todel > 0 and path[-1][0] <= todel:
todel -= path.pop()[0]
path[-1] = (path[-1][0] - todel, path[-1][1])
print('YES')
print(len(path))
letters = ["R", 'D', "L", "U"]
for i in path:
print(i[0], letters[i[1]])
```
|
instruction
| 0
| 98,014
| 3
| 196,028
|
No
|
output
| 1
| 98,014
| 3
| 196,029
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
n,m,k=map(int,input().split())
chk=4*n*m -3*n-2*m
if(k<=chk):
print("YES")
else:
print("NO")
exit()
q=(m-1)//4
r=(m-1)%4
a=[]
if(n==1)and(m>1):
if(k<=(m-1)):
q1=k//4
r1=k%4
if(q1!=0):
a.append([q1,"RRRR"])
if(r1!=0):
a.append([1,"R"*r1])
else:
if(q!=0):
a.append([q,"RRRR"])
if(r!=0):
a.append([1,"R"*r])
x=k-m+1
q1=x//4
r1=x%4
if(q1!=0):
a.append([q1,"LLLL"])
if(r1!=0):
a.append([1,"L"*r1])
elif(n>1)and(m==1):
q=(n-1)//4
r=(n-1)%4
if(k<=(n-1)):
q1=k//4
r1=k%4
if(q1!=0):
a.append([q1,"DDDD"])
if(r1!=0):
a.append([1,"D"*r1])
else:
if(q!=0):
a.append([q,"DDDD"])
if(r!=0):
a.append([1,"D"*r])
x=k-n+1
q1=x//4
r1=x%4
if(q1!=0):
a.append([q1,"UUUU"])
if(r1!=0):
a.append([1,"U"*r1])
elif(n>1)and(m>1):
quanta=2*(m-1)+2*m -1
rep= k//quanta
rrep=k%quanta
while(rep!=0):
if(q!=0):
a.append([q,"RRRR"])
if(r!=0):
a.append([1,"R"*r])
a.append([m-1,"DUL"])
a.append([1,"D"])
rep-=1
if(rrep<=2*(m-1)):
if(rrep<=(m-1)):
q1=rrep//4
r1=rrep%4
if(q1!=0):
a.append([q1,"RRRR"])
if(r1!=0):
a.append([1,"R"*r1])
else:
if(q!=0):
a.append([q,"RRRR"])
if(r!=0):
a.append([1,"R"*r])
x=rrep-m+1
q1=x//4
r1=x%4
if(q1!=0):
a.append([q1,"LLLL"])
if(r1!=0):
a.append([1,"L"*r1])
else:
if(q!=0):
a.append([q,"RRRR"])
if(r!=0):
a.append([1,"R"*r])
x=rrep-m+1
q1=x//3
r1=x%3
if(q1!=0):
a.append([q1,"DUL"])
if(r1!=0):
if(r1==1):
a.append([1,"D"])
elif(r1==2):
a.append([1,"DU"])
print(len(a))
for i in a:
print(i[0],i[1])
```
|
instruction
| 0
| 98,015
| 3
| 196,030
|
No
|
output
| 1
| 98,015
| 3
| 196,031
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
MAX=4*n*m-2*n-2*m
if k>MAX:
print("NO")
sys.exit()
ANS=[]
ANS.append((m-1,"R"))
ANS.append((m-1,"L"))
for i in range(n-1):
ANS.append((1,"D"))
ANS.append((m-1,"RUD"))
ANS.append((m-1,"L"))
ANS.append((n-1,"U"))
count=0
ANS2=[]
for x,y in ANS:
if count+x*len(y)<=k:
ANS2.append((x,y))
k-=x*len(y)
else:
if k//len(y)>0:
ANS2.append((k//len(y),y))
k-=k//len(y)*len(y)
if k!=0:
ANS2.append((1,y[:k]))
break
print("YES")
print(len(ANS2))
for x,y in ANS2:
print(x,y)
```
|
instruction
| 0
| 98,016
| 3
| 196,032
|
No
|
output
| 1
| 98,016
| 3
| 196,033
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bashar was practicing for the national programming contest. Because of sitting too much in front of the computer without doing physical movements and eating a lot Bashar became much fatter. Bashar is going to quit programming after the national contest and he is going to become an actor (just like his father), so he should lose weight.
In order to lose weight, Bashar is going to run for k kilometers. Bashar is going to run in a place that looks like a grid of n rows and m columns. In this grid there are two one-way roads of one-kilometer length between each pair of adjacent by side cells, one road is going from the first cell to the second one, and the other road is going from the second cell to the first one. So, there are exactly (4 n m - 2n - 2m) roads.
Let's take, for example, n = 3 and m = 4. In this case, there are 34 roads. It is the picture of this case (arrows describe roads):
<image>
Bashar wants to run by these rules:
* He starts at the top-left cell in the grid;
* In one move Bashar may go up (the symbol 'U'), down (the symbol 'D'), left (the symbol 'L') or right (the symbol 'R'). More formally, if he stands in the cell in the row i and in the column j, i.e. in the cell (i, j) he will move to:
* in the case 'U' to the cell (i-1, j);
* in the case 'D' to the cell (i+1, j);
* in the case 'L' to the cell (i, j-1);
* in the case 'R' to the cell (i, j+1);
* He wants to run exactly k kilometers, so he wants to make exactly k moves;
* Bashar can finish in any cell of the grid;
* He can't go out of the grid so at any moment of the time he should be on some cell;
* Bashar doesn't want to get bored while running so he must not visit the same road twice. But he can visit the same cell any number of times.
Bashar asks you if it is possible to run by such rules. If it is possible, you should tell him how should he run.
You should give him a steps to do and since Bashar can't remember too many steps, a should not exceed 3000. In every step, you should give him an integer f and a string of moves s of length at most 4 which means that he should repeat the moves in the string s for f times. He will perform the steps in the order you print them.
For example, if the steps are 2 RUD, 3 UUL then the moves he is going to move are RUD + RUD + UUL + UUL + UUL = RUDRUDUULUULUUL.
Can you help him and give him a correct sequence of moves such that the total distance he will run is equal to k kilometers or say, that it is impossible?
Input
The only line contains three integers n, m and k (1 β€ n, m β€ 500, 1 β€ k β€ 10 ^{9}), which are the number of rows and the number of columns in the grid and the total distance Bashar wants to run.
Output
If there is no possible way to run k kilometers, print "NO" (without quotes), otherwise print "YES" (without quotes) in the first line.
If the answer is "YES", on the second line print an integer a (1 β€ a β€ 3000) β the number of steps, then print a lines describing the steps.
To describe a step, print an integer f (1 β€ f β€ 10^{9}) and a string of moves s of length at most 4. Every character in s should be 'U', 'D', 'L' or 'R'.
Bashar will start from the top-left cell. Make sure to move exactly k moves without visiting the same road twice and without going outside the grid. He can finish at any cell.
We can show that if it is possible to run exactly k kilometers, then it is possible to describe the path under such output constraints.
Examples
Input
3 3 4
Output
YES
2
2 R
2 L
Input
3 3 1000000000
Output
NO
Input
3 3 8
Output
YES
3
2 R
2 D
1 LLRR
Input
4 4 9
Output
YES
1
3 RLD
Input
3 4 16
Output
YES
8
3 R
3 L
1 D
3 R
1 D
1 U
3 L
1 D
Note
The moves Bashar is going to move in the first example are: "RRLL".
It is not possible to run 1000000000 kilometers in the second example because the total length of the roads is smaller and Bashar can't run the same road twice.
The moves Bashar is going to move in the third example are: "RRDDLLRR".
The moves Bashar is going to move in the fifth example are: "RRRLLLDRRRDULLLD". It is the picture of his run (the roads on this way are marked with red and numbered in the order of his running):
<image>
Submitted Solution:
```
import sys
read = lambda: list(map(int, sys.stdin.readline().strip().split()))
n, m, k = read()
maxx = 4*n*m-2*n-2*m
if k > maxx:
print("NO")
else:
i = 0
ans = []
while i <= n-1:
#print(i)
if i == n -1:
if m -1 <=k and m-1 >0:
ans.append((m-1, 'R'))
k -= (m-1)
elif m-1 > k:
ans.append((k, 'R'))
k -= k
break
if m-1 <=k and m-1>0:
ans.append((m-1, 'L'))
k -= (m-1)
elif m-1 > k:
ans.append((k, 'L'))
k -= k
break
break
if m-1 <=k and m-1 > 0:
ans.append((m-1, 'R'))
k -= (m-1)
elif m-1 > k:
ans.append((k, 'R'))
k -= k
break
if 3*(m-1) <= k and m-1 > 0:
ans.append((m-1, 'DUL'))
k -= (3*(m-1))
elif 3*(m-1) >k:
ans.append((k, 'DUL'))
k -= k
break
if k > 0:
ans.append((1, 'D'))
k -= 1
i += 1
if k == 0:
break
if k > 0:
ans.append((k, 'U'))
print("YES")
print(len(ans))
for tup in ans:
print(tup[0], tup[1])
```
|
instruction
| 0
| 98,017
| 3
| 196,034
|
No
|
output
| 1
| 98,017
| 3
| 196,035
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
"Eat a beaver, save a tree!" β That will be the motto of ecologists' urgent meeting in Beaverley Hills.
And the whole point is that the population of beavers on the Earth has reached incredible sizes! Each day their number increases in several times and they don't even realize how much their unhealthy obsession with trees harms the nature and the humankind. The amount of oxygen in the atmosphere has dropped to 17 per cent and, as the best minds of the world think, that is not the end.
In the middle of the 50-s of the previous century a group of soviet scientists succeed in foreseeing the situation with beavers and worked out a secret technology to clean territory. The technology bears a mysterious title "Beavermuncher-0xFF". Now the fate of the planet lies on the fragile shoulders of a small group of people who has dedicated their lives to science.
The prototype is ready, you now need to urgently carry out its experiments in practice.
You are given a tree, completely occupied by beavers. A tree is a connected undirected graph without cycles. The tree consists of n vertices, the i-th vertex contains ki beavers.
"Beavermuncher-0xFF" works by the following principle: being at some vertex u, it can go to the vertex v, if they are connected by an edge, and eat exactly one beaver located at the vertex v. It is impossible to move to the vertex v if there are no beavers left in v. "Beavermuncher-0xFF" cannot just stand at some vertex and eat beavers in it. "Beavermuncher-0xFF" must move without stops.
Why does the "Beavermuncher-0xFF" works like this? Because the developers have not provided place for the battery in it and eating beavers is necessary for converting their mass into pure energy.
It is guaranteed that the beavers will be shocked by what is happening, which is why they will not be able to move from a vertex of the tree to another one. As for the "Beavermuncher-0xFF", it can move along each edge in both directions while conditions described above are fulfilled.
The root of the tree is located at the vertex s. This means that the "Beavermuncher-0xFF" begins its mission at the vertex s and it must return there at the end of experiment, because no one is going to take it down from a high place.
Determine the maximum number of beavers "Beavermuncher-0xFF" can eat and return to the starting vertex.
Input
The first line contains integer n β the number of vertices in the tree (1 β€ n β€ 105). The second line contains n integers ki (1 β€ ki β€ 105) β amounts of beavers on corresponding vertices. Following n - 1 lines describe the tree. Each line contains two integers separated by space. These integers represent two vertices connected by an edge. Vertices are numbered from 1 to n. The last line contains integer s β the number of the starting vertex (1 β€ s β€ n).
Output
Print the maximum number of beavers munched by the "Beavermuncher-0xFF".
Please, do not use %lld specificator to write 64-bit integers in C++. It is preferred to use cout (also you may use %I64d).
Examples
Input
5
1 3 1 3 2
2 5
3 4
4 5
1 5
4
Output
6
Input
3
2 1 1
3 2
1 2
3
Output
2
Submitted Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
beaver = tuple(map(int, input().split()))
adj = [[] for _ in range(n)]
deg = [0] * n
for u, v in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
deg[u - 1] += 1
deg[v - 1] += 1
start = int(input()) - 1
deg[start] += 1000000
if n == 1:
print(0)
exit()
dp = [0] * n
stack = [i for i in range(n) if i != start and deg[i] == 1]
while stack:
v = stack.pop()
deg[v] = 0
child = []
for dest in adj[v]:
if deg[dest] == 0:
child.append(dp[dest])
else:
deg[dest] -= 1
if deg[dest] == 1:
stack.append(dest)
child.sort(reverse=True)
dp[v] = 1 + sum(child[:beaver[v] - 1]) + min(beaver[v] - 1, len(child))
child = sorted((dp[v] for v in adj[start]), reverse=True)
ans = sum(child[:beaver[start]]) + min(beaver[start], len(child))
print(ans)
```
|
instruction
| 0
| 98,329
| 3
| 196,658
|
No
|
output
| 1
| 98,329
| 3
| 196,659
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,330
| 3
| 196,660
|
Tags: dp, implementation
Correct Solution:
```
import sys
from collections import defaultdict
input=sys.stdin.readline
n,q,c=map(int,input().split())
d=defaultdict(lambda:[0]*11)
for _ in range(n):
x,y,s=map(int,input().split())
if (x,y) not in d:
d[(x,y)]=[0]*11
d[(x,y)][s]+=1
g=[[[0]*11 for i in range(101)] for i in range(101)]
g[1][1]=d[(1,1)]
for i in range(1,101):
for j in range(1,101):
if i==1 and j==1:continue
for k in range(11):
if i==1:
g[i][j][k]=g[i][j-1][k]+d[(i,j)][k]
elif j==1:
g[i][j][k]=g[i-1][j][k]+d[(i,j)][k]
else:
g[i][j][k]=g[i-1][j][k]+g[i][j-1][k]-g[i-1][j-1][k]+d[(i,j)][k]
for _ in range(q):
t,x1,y1,x2,y2=map(int,input().split())
ans=0
for k in range(11):
cnt=g[x2][y2][k]-g[x1-1][y2][k]-g[x2][y1-1][k]+g[x1-1][y1-1][k]
ans+=((t+k)%(c+1))*cnt
print(ans)
```
|
output
| 1
| 98,330
| 3
| 196,661
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,331
| 3
| 196,662
|
Tags: dp, implementation
Correct Solution:
```
import sys
input=sys.stdin.readline
n,q,c=map(int,input().split())
g=[[[0]*11 for i in range(101)] for i in range(101)]
for _ in range(n):
x,y,s=map(int,input().split())
g[x][y][s]+=1
for i in range(1,101):
for j in range(1,101):
for k in range(11):
g[i][j][k]+=g[i-1][j][k]+g[i][j-1][k]-g[i-1][j-1][k]
for _ in range(q):
t,x1,y1,x2,y2=map(int,input().split())
ans=0
for k in range(11):
cnt=g[x2][y2][k]-g[x1-1][y2][k]-g[x2][y1-1][k]+g[x1-1][y1-1][k]
ans+=((t+k)%(c+1))*cnt
print(ans)
```
|
output
| 1
| 98,331
| 3
| 196,663
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,332
| 3
| 196,664
|
Tags: dp, implementation
Correct Solution:
```
n,q,c = map(int,input().split())
sky = [[[0] * 11 for j in range(101)] for i in range(101)]
c += 1
for i in range(n):
x,y,s = map(int,input().split())
sky[y][x][s % c] += 1
for k in range(11):
i = 1
while i < 101:
j = 1
while j < 101:
sky[i][j][k] += (sky[i-1][j][k] + sky[i][j-1][k] - sky[i-1][j-1][k])
j += 1
i += 1
req = [list(map(int,input().split())) for i in range(q)]
for i in range(q):
t,x,y,x2,y2 = req[i]
ans = 0
j = 0
while j < c:
ans += (sky[y2][x2][j] - sky[y2][x-1][j] - sky[y-1][x2][j] + sky[y-1][x-1][j]) * ((j + t) % c)
j += 1
print(ans)
```
|
output
| 1
| 98,332
| 3
| 196,665
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,333
| 3
| 196,666
|
Tags: dp, implementation
Correct Solution:
```
"""
Author : Arif Ahmad
Date :
Algo :
Difficulty :
"""
from sys import stdin, stdout
def main():
n, q, c = [int(_) for _ in stdin.readline().strip().split()]
g = [[[0 for i in range(102)] for j in range(102)] for k in range(12)]
for _ in range(n):
x, y, s = [int(_) for _ in stdin.readline().strip().split()]
for t in range(c+1):
brightness = (s + t) % (c + 1)
g[t][x][y] += brightness
# dp stores cummulative brightness at time t
dp = [[[0 for i in range(102)] for j in range(102)] for k in range(12)]
for t in range(c+1):
for x in range(1, 101):
for y in range(1, 101):
dp[t][x][y] = dp[t][x-1][y] + dp[t][x][y-1] - dp[t][x-1][y-1] + g[t][x][y]
for _ in range(q):
t, x1, y1, x2, y2 = [int(_) for _ in stdin.readline().strip().split()]
t = t % (c + 1)
ans = dp[t][x2][y2] - dp[t][x1-1][y2] - dp[t][x2][y1-1] + dp[t][x1-1][y1-1]
stdout.write(str(ans) + '\n')
if __name__ == '__main__':
main()
```
|
output
| 1
| 98,333
| 3
| 196,667
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,334
| 3
| 196,668
|
Tags: dp, implementation
Correct Solution:
```
def fun(n,q,c,stars,querry):
m=100
precom=[[[0]*m for _ in range(m)] for _ in range(c+1)]
for x,y,p in stars:
for i in range(c+1):
temp=(p+i)%(c+1)
precom[i][x-1][y-1]+=temp
for k in range(c+1):
for i in range(0,m):
for j in range(1,m):
precom[k][i][j]+=precom[k][i][j-1]
for k in range(c+1):
for j in range(0,m):
for i in range(1,m):
precom[k][i][j]+= precom[k][i-1][j]
for t,x1,y1,x2,y2 in querry:
t=t%(c+1)
x1,y1,x2,y2,a,b,C,d=x1-1,y1-1,x2-1,y2-1,0,0,0,0
a=precom[t][x2][y2]
if x1!=0:
b=precom[t][x1-1][y2]
if y1!=0:
C=precom[t][x2][y1-1]
if x1!=0 and y1!=0:
d=precom[t][x1-1][y1-1]
print(a-b-C+d)
n,q,c=list(map(lambda x:int(x),input().split()))
stars=[list(map(lambda x:int(x),input().split())) for _ in range(n)]
querry=[list(map(lambda x:int(x),input().split())) for _ in range(q)]
fun(n,q,c,stars,querry)
```
|
output
| 1
| 98,334
| 3
| 196,669
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,335
| 3
| 196,670
|
Tags: dp, implementation
Correct Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
from itertools import permutations as perm
# from fractions import Fraction
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
n, q, c = gil()
f = [ [[0 for _ in range(101)] for _ in range(101)] for _ in range(c+1) ]
for _ in range(n):
x, y, s = gil()
f[s][x][y] += 1
# pre computation
for y in range(1, 101):
for x in range(1, 101):
for ci in range(c+1):
f[ci][x][y] += f[ci][x][y-1] + f[ci][x-1][y] - f[ci][x-1][y-1]
for _ in range(q):
t, x1, y1, x2, y2 = gil()
t %= (c+1)
val = 0
for ci in range(c+1):
fi = f[ci][x2][y2] + f[ci][x1-1][y1-1] - f[ci][x2][y1-1] - f[ci][x1-1][y2]
val += fi*( (t+ci)%(c+1) )
print(val)
```
|
output
| 1
| 98,335
| 3
| 196,671
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,336
| 3
| 196,672
|
Tags: dp, implementation
Correct Solution:
```
import sys
from collections import defaultdict
input=sys.stdin.readline
n,q,c=map(int,input().split())
d=defaultdict(lambda:[0]*11)
for _ in range(n):
x,y,s=map(int,input().split())
if (x,y) not in d:
d[(x,y)]=[0]*11
d[(x,y)][s]+=1
g=[[[0]*11 for i in range(101)] for i in range(101)]
g[1][1]=d[(1,1)]
for i in range(1,101):
for j in range(1,101):
for k in range(11):
g[i][j][k]=g[i-1][j][k]+g[i][j-1][k]-g[i-1][j-1][k]+d[(i,j)][k]
for _ in range(q):
t,x1,y1,x2,y2=map(int,input().split())
ans=0
for k in range(11):
cnt=g[x2][y2][k]-g[x1-1][y2][k]-g[x2][y1-1][k]+g[x1-1][y1-1][k]
ans+=((t+k)%(c+1))*cnt
print(ans)
```
|
output
| 1
| 98,336
| 3
| 196,673
|
Provide tags and a correct Python 3 solution for this coding contest problem.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
|
instruction
| 0
| 98,337
| 3
| 196,674
|
Tags: dp, implementation
Correct Solution:
```
import sys
from bisect import bisect_left, bisect_right
n, q, c = list(map(int, input().split()))
values = [[[0 for _ in range(11)] for _ in range(0, 101)] for _ in range(0, 101)]
# print(dp)
for i in range(n):
x, y, s = list(map(int, sys.stdin.readline().split()))
values[x][y][s] += 1
dp = [[[-1 for _ in range(11)] for _ in range(0, 101)] for _ in range(0, 101)]
for i in range(0,101):
for p in range(11):
dp[0][i][p]=0
dp[i][0][p]=0
def recurse(p, x, y):
if x==0 or y==0:
return 0
if dp[x][y][p]!=-1:
return dp[x][y][p]
if x == 1 and y == 1:
dp[x][y][p]=values[x][y][p]
return values[x][y][p]
else:
# print(x,y,p)
dp[x][y][p]=recurse(p,x-1,y)+recurse(p,x,y-1)-recurse(p,x-1,y-1)+values[x][y][p]
dp[x][y][p]=max(dp[x][y][p],0)
return dp[x][y][p]
for i in range(1,101):
for j in range(1,101):
for p in range(0,c+1):
recurse(p,i,j)
# print(dp)
for i in range(q):
t,x1,y1,x2,y2=list(map(int, sys.stdin.readline().split()))
ans=0
for k in range(0,c+1):
# print(dp[x2][y2][k])
# print(dp[x1-1][y2][k])
# print(dp[x1][y2-1][k])
# print(dp[x1-1][y1-1][k])
ans+=((t+k)%(c+1))*(dp[x2][y2][k]-dp[x1-1][y2][k]-dp[x2][y1-1][k]+dp[x1-1][y1-1][k])
print(ans)
```
|
output
| 1
| 98,337
| 3
| 196,675
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def add(x,y):
for i in range(len(x)):
x[i] += y[i]
def sub(x,y):
for i in range(len(x)):
x[i] -= y[i]
def main():
n,q,c = map(int,input().split())
arr = [[[0]*(c+1) for _ in range(101)] for _ in range(101)]
for _ in range(n):
x,y,s = map(int,input().split())
arr[x][y][s] += 1
dp = [[[0]*(c+1) for _ in range(101)] for _ in range(101)]
for i in range(1,101):
for j in range(1,101):
add(dp[i][j],arr[i][j])
add(dp[i][j],dp[i-1][j])
add(dp[i][j],dp[i][j-1])
sub(dp[i][j],dp[i-1][j-1])
for _ in range(q):
t,x1,y1,x2,y2 = map(int,input().split())
x = dp[x2][y2][:]
add(x,dp[x1-1][y1-1])
sub(x,dp[x1-1][y2])
sub(x,dp[x2][y1-1])
ans = 0
for ind,j in enumerate(x):
ans += ((ind+t)%(c+1))*j
print(ans)
#Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == '__main__':
main()
```
|
instruction
| 0
| 98,338
| 3
| 196,676
|
Yes
|
output
| 1
| 98,338
| 3
| 196,677
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
from sys import stdin,stdout
stdin.readline
def mp(): return list(map(int, stdin.readline().strip().split()))
def it():return int(stdin.readline().strip())
# def cal_brightness_at_any_instant(ib,t,c):
# while t:
# ib = ib+1
# ib%=(c+1)
# t-=1
# return ib
# print(cal_brightness_at_any_instant(1,5,3))
n,q,c = mp()
dp = [[[0]*11 for _ in range(101)] for _ in range(101)]
# print(dp)
for _ in range(n):
x,y,ib = mp()
dp[x][y][ib] += 1
for i in range(1,101):
for j in range(1,101):
for k in range(11):
dp[i][j][k]+=dp[i-1][j][k]+dp[i][j-1][k]-dp[i-1][j-1][k]
for _ in range(q):
t,x1,y1,x2,y2=mp()
ans=0
for k in range(11):
cnt=dp[x2][y2][k]-dp[x1-1][y2][k]-dp[x2][y1-1][k]+dp[x1-1][y1-1][k]
ans+=((t+k)%(c+1))*cnt
print(ans)
```
|
instruction
| 0
| 98,339
| 3
| 196,678
|
Yes
|
output
| 1
| 98,339
| 3
| 196,679
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
###### ### ####### ####### ## # ##### ### #####
# # # # # # # # # # # # # ###
# # # # # # # # # # # # # ###
###### ######### # # # # # # ######### #
###### ######### # # # # # # ######### #
# # # # # # # # # # #### # # #
# # # # # # # ## # # # # #
###### # # ####### ####### # # ##### # # # #
from __future__ import print_function # for PyPy2
from itertools import permutations as perm
# from fractions import Fraction
from collections import *
from sys import stdin
from bisect import *
from heapq import *
from math import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1e9)+7
inf = float("inf")
n, q, c = gil()
f = [ [[0 for _ in range(101)] for _ in range(101)] for _ in range(c+1) ]
for _ in range(n):
x, y, s = gil()
f[s][x][y] += 1
# pre computation
for y in range(1, 101):
for x in range(1, 101):
for ci in range(c+1):
f[ci][x][y] += f[ci][x][y-1] + f[ci][x-1][y] - f[ci][x-1][y-1]
for _ in range(q):
t, x1, y1, x2, y2 = gil()
store = t
# t %= (c+1)
val = 0
for ci in range(c+1):
fi = f[ci][x2][y2] + f[ci][x1-1][y1-1] - f[ci][x2][y1-1] - f[ci][x1-1][y2]
# if fi:print("at time", store, "seeing stars with brightness", ci, ' > ', (t+ci)%(c+1), " : ", fi)
val += fi*( (t+ci)%(c+1) )
print(val)
# print("*************")
```
|
instruction
| 0
| 98,340
| 3
| 196,680
|
Yes
|
output
| 1
| 98,340
| 3
| 196,681
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
n, q, c = map(int,input().split())
stars = [ list( map(int,input().split()) ) for i in range(n)]
queries = [ list( map(int,input().split()) ) for i in range(q)]
prec = [[[0 for y in range(101)]for x in range(101)] for i in range(c+1)] #0, c
for x, y, s in stars:
for t in range(c+1):
prec[t][x][y] += s+t if s+t <= c else s+t-(c+1)
for s in range(len(prec)):
for x in range(len(prec[s])):
for y in range(len(prec[s][x])):
if x and y:
prec[s][x][y] += prec[s][x-1][y]+prec[s][x][y-1]-prec[s][x-1][y-1]
for t, x1, y1, x2, y2 in queries:
s = t%(c+1)
res = ( prec[s][x2][y2]-prec[s][x1-1][y2]-prec[s][x2][y1-1]+prec[s][x1-1][y1-1] )
print(res)
```
|
instruction
| 0
| 98,341
| 3
| 196,682
|
Yes
|
output
| 1
| 98,341
| 3
| 196,683
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
#!/usr/bin/python3
def main():
n, q, c = [int(i) for i in input().split()]
plano = [[-1]*101 for i in range(101)]
for i in range(n):
a, b, d = [int(i) for i in input().split()]
plano[b][a] = d
for i in range(q):
t, x1, y1, x2, y2 = [int(i) for i in input().split()]
atual = 0
for y in range(y1, y2+1):
for x in range(x1, x2+1):
val = plano[x][y]
if val >= 0:
atual += (val + t) % (c+1)
# don't quite understand why plano[x][y] instead of plano[y][x]
print(atual)
if __name__ == "__main__": main()
```
|
instruction
| 0
| 98,342
| 3
| 196,684
|
No
|
output
| 1
| 98,342
| 3
| 196,685
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
# Legends Always Come Up with Solution
# Author: Manvir Singh
import os
from io import BytesIO, IOBase
import sys
from collections import defaultdict, deque, Counter
from math import sqrt, pi, ceil, log, inf, gcd, floor
from itertools import combinations
from bisect import *
def main():
n,q,c=map(int,input().split())
a=[[[0 for i in range(101)] for j in range(101)] for k in range(11)]
for i in range(n):
x,y,s=map(int,input().split())
for k in range(11):
a[k][x][y]=(s+k if s+k<=c else 0)
for k in range(11):
for i in range(101):
for j in range(1,101):
a[k][i][j]+=a[k][i][j-1]
for k in range(11):
for i in range(1,101):
for j in range(101):
a[k][i][j]+=a[k][i-1][j]
for i in range(q):
t,x1,y1,x2,y2=map(int,input().split())
z=t%(c+1)
print(a[z][x2][y2]-a[z][x1-1][y2]-a[z][x2][y1-1]+a[z][x1-1][y1-1])
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
```
|
instruction
| 0
| 98,343
| 3
| 196,686
|
No
|
output
| 1
| 98,343
| 3
| 196,687
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
n, q, c = [int(i) for i in input().split()]
c += 1
stars = [[[0 for u in range(c)] for i in range(101)] for j in range(101)]
for i in range(n):
x, y, s = [int(j) for j in input().split()]
stars[y - 1][x - 1][s] += 1
for i in range(101):
for j in range(101):
'''
if i:
for u in range(c):
stars[i][j][u] += stars[i - 1][j][u]
if j:
for u in range(c):
stars[i][j][u] += stars[i][j - 1][u]
if i and j:
for u in range(c):
stars[i][j][u] -= stars[i - 1][j - 1][u]
'''
for u in range(c):
if i:
stars[i][j][u] += stars[i - 1][j][u]
if j:
stars[i][j][u] += stars[i][j - 1][u]
if i and j:
stars[i][j][u] -= stars[i - 1][j - 1][u]
for i in range(q):
t, x1, y1, x2, y2 = [int(j) for j in input().split()]
x1 -= 1
y1 -= 1
x2 -= 1
y2 -= 1
'''
data = [0 for i in range(c)]
for j in range(c):
data[j] = stars[y2][x2][j]
if y1:
for j in range(c):
data[j] -= stars[y1 - 1][x2][j]
if x1:
for j in range(c):
data[j] -= stars[y2][x1 - 1][j]
if x1 and y1:
for j in range(c):
data[j] += stars[y1 - 1][x1 - 1][j]
ret = 0
for j in range(c):
ret += ((j + t) % c) * data[j]
'''
ret = 0
for j in range(c):
box = stars[y2][x2][j]
if y1:
box -= stars[y1 - 1][x2][j]
if x1:
box -= stars[y2][x1 - 1][j]
if y1 and x2:
box += stars[y1 - 1][x1 - 1][j]
ret += (j + t) % c * box
print(ret)
```
|
instruction
| 0
| 98,344
| 3
| 196,688
|
No
|
output
| 1
| 98,344
| 3
| 196,689
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Cartesian coordinate system is set in the sky. There you can see n stars, the i-th has coordinates (xi, yi), a maximum brightness c, equal for all stars, and an initial brightness si (0 β€ si β€ c).
Over time the stars twinkle. At moment 0 the i-th star has brightness si. Let at moment t some star has brightness x. Then at moment (t + 1) this star will have brightness x + 1, if x + 1 β€ c, and 0, otherwise.
You want to look at the sky q times. In the i-th time you will look at the moment ti and you will see a rectangle with sides parallel to the coordinate axes, the lower left corner has coordinates (x1i, y1i) and the upper right β (x2i, y2i). For each view, you want to know the total brightness of the stars lying in the viewed rectangle.
A star lies in a rectangle if it lies on its border or lies strictly inside it.
Input
The first line contains three integers n, q, c (1 β€ n, q β€ 105, 1 β€ c β€ 10) β the number of the stars, the number of the views and the maximum brightness of the stars.
The next n lines contain the stars description. The i-th from these lines contains three integers xi, yi, si (1 β€ xi, yi β€ 100, 0 β€ si β€ c β€ 10) β the coordinates of i-th star and its initial brightness.
The next q lines contain the views description. The i-th from these lines contains five integers ti, x1i, y1i, x2i, y2i (0 β€ ti β€ 109, 1 β€ x1i < x2i β€ 100, 1 β€ y1i < y2i β€ 100) β the moment of the i-th view and the coordinates of the viewed rectangle.
Output
For each view print the total brightness of the viewed stars.
Examples
Input
2 3 3
1 1 1
3 2 0
2 1 1 2 2
0 2 1 4 5
5 1 1 5 5
Output
3
0
3
Input
3 4 5
1 1 2
2 3 0
3 3 1
0 1 1 100 100
1 2 2 4 4
2 2 1 4 7
1 50 50 51 51
Output
3
3
5
0
Note
Let's consider the first example.
At the first view, you can see only the first star. At moment 2 its brightness is 3, so the answer is 3.
At the second view, you can see only the second star. At moment 0 its brightness is 0, so the answer is 0.
At the third view, you can see both stars. At moment 5 brightness of the first is 2, and brightness of the second is 1, so the answer is 3.
Submitted Solution:
```
from sys import stdin, stdout
n,q,c=map(int,stdin.readline().split())
cs=[[[0]*101 for _ in range(101)] for _ in range(11)]
for k in range(n):
x,y,s=map(int,stdin.readline().split())
cs[s][x][y]+=1
for i in range(1,101):
for j in range(1,101):
for k in range(11):
cs[k][i][j]+=max(cs[k][i-1][j-1],cs[k][i-1][j],cs[k][i][j-1])
for _ in range(q):
t,x1,y1,x2,y2=map(int,stdin.readline().split())
totalb=0
for k in range(11):
totalb+=((k+t)%(c+1))*(cs[k][x2][y2]-cs[k][x2][y1-1]-cs[k][x1-1][y2]+cs[k][x1-1][y1-1])
print(totalb)
```
|
instruction
| 0
| 98,345
| 3
| 196,690
|
No
|
output
| 1
| 98,345
| 3
| 196,691
|
Provide a correct Python 3 solution for this coding contest problem.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
|
instruction
| 0
| 98,529
| 3
| 197,058
|
"Correct Solution:
```
from collections import deque
while 1:
N = int(input())
if N == 0:
break
G = [[] for i in range(N)]
for i in range(N-1):
a, b, t = map(int, input().split())
a -= 1; b -= 1
G[a].append((b, t))
G[b].append((a, t))
D = [-1]*N; P = [0]*N
que = deque([0])
D[0] = 0
while que:
v = que.popleft()
c = D[v]
for w, d in G[v]:
if D[w] != -1:
continue
D[w] = c + d
P[w] = d
que.append(w)
ans = 0
m = 0
for i in range(N):
if not i or len(G[i]) > 1:
ans += P[i]*2
m = max(m, D[i])
ans -= m
print(ans)
```
|
output
| 1
| 98,529
| 3
| 197,059
|
Provide a correct Python 3 solution for this coding contest problem.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
|
instruction
| 0
| 98,530
| 3
| 197,060
|
"Correct Solution:
```
while True:
n = int(input())
if n == 0:break
edges = [[] for _ in range(n)]
for _ in range(n - 1):
a, b, t = map(int, input().split())
a -= 1
b -= 1
edges[a].append([b, t])
edges[b].append([a, t])
used = [False] * n
is_leaf = [False] * n
for i in range(1, n):
if len(edges[i]) == 1:is_leaf[i] = True
def check(x):
used[x] = True
times = [0]
max_path = 0
for to, t in edges[x]:
if not used[to] and not is_leaf[to]:
time, path = check(to)
times.append(time + t * 2)
max_path = max(max_path, path + t)
return sum(times), max_path
total_time, max_path = check(0)
print(total_time - max_path)
```
|
output
| 1
| 98,530
| 3
| 197,061
|
Provide a correct Python 3 solution for this coding contest problem.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
|
instruction
| 0
| 98,531
| 3
| 197,062
|
"Correct Solution:
```
while 1:
N = int(input())
if N == 0:break
R = [[0 for i in range(N+1)] for i in range(N+1)]
def dfs_max(cur, pre):
_max = -R[cur][pre]
for i in range(N+1):
if R[cur][i] > 0 and i != pre:
_max = max(_max, dfs_max(i, cur) + R[cur][i])
# print('max : %d' % _max)
return _max
total = 0
for i in range(N-1):
a, b, t = list(map(int, input().split()))
R[a][b] = t
R[b][a] = t
total += (t * 2)
for i in range(2, N+1):
spam = [x for x in R[i] if x > 0]
if(len(spam) <= 1):
total -= (spam[0] * 2)
print((total - dfs_max(1, 0)))
```
|
output
| 1
| 98,531
| 3
| 197,063
|
Provide a correct Python 3 solution for this coding contest problem.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
|
instruction
| 0
| 98,532
| 3
| 197,064
|
"Correct Solution:
```
def tree_walk_1(start, parent=None):
for i, t in adj[start]:
if i != parent:
P[i] = (start, t)
C[start].append((i, t))
tree_walk_1(i, start)
def tree_walk_2(start):
global time
notVisited[start] = False
for c, t1 in C[start]:
if notVisited[c]:
time += 2 * t1
tree_walk_2(c)
p, t2 = P[start]
if notVisited[p]:
time += t2
tree_walk_2(p)
from sys import stdin
f_i = stdin
while True:
N = int(f_i.readline())
if N == 0:
break
adj = [[] for i in range(N)]
for i in range(N - 1):
a, b, t = map(int, f_i.readline().split())
a -= 1
b -= 1
adj[a].append((b, t))
adj[b].append((a, t))
# leaf cutting
lf = []
for i, a in enumerate(adj[1:], start=1):
if len(a) == 1:
lf.append(i)
for l in lf:
i, t = adj[l].pop()
adj[i].remove((l, t))
# root candidate
rc = [i for i, a in enumerate(adj[1:], start=1) if len(a) == 1]
if not rc:
print(0)
continue
time_rec = []
for r in rc:
P = [None] * N
P[r] = (r, 0)
C = [[] for i in range(N)]
tree_walk_1(r) #making a tree
time = 0
notVisited = [True] * N
tree_walk_2(0)
time_rec.append(time)
print(min(time_rec))
```
|
output
| 1
| 98,532
| 3
| 197,065
|
Provide a correct Python 3 solution for this coding contest problem.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
|
instruction
| 0
| 98,533
| 3
| 197,066
|
"Correct Solution:
```
def dfs1(v, pv):
for nv, _ in adj_list[v]:
if nv==pv:
continue
is_leaf[v] = False
dfs1(nv, v)
return is_leaf
def dfs2(v, pv, d):
dist[v] = d
for nv, w in adj_list[v]:
if nv==pv:
continue
dfs2(nv, v, d+w)
return dist
while True:
N = int(input())
if N==0:
break
a, b, t = [], [], []
adj_list = [[] for _ in range(N)]
for _ in range(N-1):
ai, bi, ti = map(int, input().split())
a.append(ai-1)
b.append(bi-1)
t.append(ti)
adj_list[ai-1].append((bi-1, ti))
adj_list[bi-1].append((ai-1, ti))
is_leaf = [True]*N
dist = [-1]*N
dfs1(0, -1)
dfs2(0, -1, 0)
tmp = 0
for ai, bi, ti in zip(a, b, t):
if (not is_leaf[ai]) and (not is_leaf[bi]):
tmp += 2*ti
ans = tmp
for i in range(N):
if not is_leaf[i]:
ans = min(ans, tmp-dist[i])
print(ans)
```
|
output
| 1
| 98,533
| 3
| 197,067
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
Submitted Solution:
```
N = int(input())
R = [[0 for i in range(N+1)] for i in range(N+1)]
def dfs_max(cur, pre):
_max = -R[cur][pre]
for i in range(N+1):
if R[cur][i] > 0 and i != pre:
_max = max(_max, dfs_max(i, cur) + R[cur][i])
# print('max : %d' % _max)
return _max
total = 0
for i in range(N-1):
a, b, t = list(map(int, input().split()))
R[a][b] = t
R[b][a] = t
total += (t * 2)
for i in range(2, N+1):
spam = [x for x in R[i] if x > 0]
if(len(spam) <= 1):
total -= (spam[0] * 2)
print((total - dfs_max(1, 0)))
```
|
instruction
| 0
| 98,534
| 3
| 197,068
|
No
|
output
| 1
| 98,534
| 3
| 197,069
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Under the command "Save Sergeant Ryan," Aiz's rescue team fought fierce battles with enemy forces in the floating city of Lee, Germany. They successfully joined the sergeant, but there were many enemy tanks and they could not call a rescue herio. So, in order to confuse the enemy tanks, they decided to carry out an operation to blow up all the bridges in the city.
The operation was immediately communicated to HQ and preparations for a rescue helicopter were underway. In order to fly the rescue herio, you have to predict when all the bridges will be blown up. As a military programmer, your mission is to calculate the time the rescue team will need to blow up all the bridges.
The floating city is made up of N islands, with a bridge between the islands. All the islands are connected in a tree shape (see the figure below). There is only one route from one island to another. It takes a fixed amount of time to cross each bridge, and it is possible to cross the bridge in either direction at that time.
Rescue units do not have the means to move on the water, such as boats, so the only way to move between islands is through a bridge. Rescue units can instantly blow up the bridges adjacent to the island at that time. What is the minimum time required for a rescue unit to blow up all the bridges? However, we do not consider the travel time within the island.
Create a program that inputs the number of islands and information on each bridge and outputs the minimum time required to blow up all the bridges. Each island is represented by a number from 1 to N. There are N-1 bridges. The bridge information consists of the numbers (a, b) of the two islands adjacent to the bridge and the time t required to cross the bridge. Rescue units shall start on the island with island number 1.
<image>
Input
A sequence of multiple datasets is given as input. The end of the input is indicated by a single line of zeros. Each dataset is given in the following format.
N
a1 b1 t1
a2 b2 t2
::
aN-1 bN-1 tN-1
All inputs are given as integers. The number of islands N (2 β€ N β€ 20) is given on the first line.
The following N-1 line gives information on the i-th bridge. ai, bi, ti (1 β€ ti β€ 500) means that we can move between island ai and island bi in time ti through the i-th bridge.
The number of datasets does not exceed 100.
Output
For each dataset, print the minimum time required to blow up all the bridges on one line.
Example
Input
7
1 2 5
2 3 2
3 4 3
2 5 3
5 6 3
5 7 8
0
Output
12
Submitted Solution:
```
N = int(input())
R = [[0 for i in range(N+1)] for i in range(N+1)]
def dfs_max(cur, pre):
print(cur)
_max = -R[cur][pre]
for i in range(N+1):
if R[cur][i] > 0 and i != pre:
_max = max(_max, dfs_max(i, cur) + R[cur][i])
print('max : %d' % _max)
return _max
total = 0
for i in range(N-1):
a, b, t = list(map(int, input().split()))
R[a][b] = t
R[b][a] = t
total += (t * 2)
for i in range(2, N+1):
spam = [x for x in R[i] if x > 0]
if(len(spam) <= 1):
total -= (spam[0] * 2)
print((total - dfs_max(1, 0)))
```
|
instruction
| 0
| 98,535
| 3
| 197,070
|
No
|
output
| 1
| 98,535
| 3
| 197,071
|
Provide a correct Python 3 solution for this coding contest problem.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
|
instruction
| 0
| 98,536
| 3
| 197,072
|
"Correct Solution:
```
# A106633
def f(n):
res=1+2*n
i=1
while i*i<=n:
res+=1+(n-i*i)//i*2
i+=1
return res
while 1:
n=int(input())
if n==0: break
print(8*f(n//2-1)+8*n)
```
|
output
| 1
| 98,536
| 3
| 197,073
|
Provide a correct Python 3 solution for this coding contest problem.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
|
instruction
| 0
| 98,537
| 3
| 197,074
|
"Correct Solution:
```
while 1:
n=int(input())
if n==0:break
a=0;i=1;b=n//2
while i*i<b:a+=((b-1)//i+1)-i-1;i+=1
a=(a+b-1)*2+i
print(8*(a+n))
```
|
output
| 1
| 98,537
| 3
| 197,075
|
Provide a correct Python 3 solution for this coding contest problem.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
|
instruction
| 0
| 98,538
| 3
| 197,076
|
"Correct Solution:
```
# AOJ 1026 Hedro's Hexahedron
# Python3 2018.7.5 bal4u
while True:
n = int(input())
if n == 0: break
ans = s = n >> 1
i, k = 1, 2
while i*i < s:
ans += (n+k-1)//k
i += 1
k += 2
ans = ans*2 - i*i
if n & 1: ans += 1
print((ans+n) << 3)
```
|
output
| 1
| 98,538
| 3
| 197,077
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
Submitted Solution:
```
while 1:
n=int(input())
if n==0:break
a=0;i=1;b=n//2
while i*i<b:a+=((b-1)/i+1)-i-1;i+=1
a=int((a+b-1)*2+i)
print(8*(a+n))
```
|
instruction
| 0
| 98,539
| 3
| 197,078
|
No
|
output
| 1
| 98,539
| 3
| 197,079
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
Submitted Solution:
```
while 1:
n=int(input())
if n==0:break
a=n//2
b=int(n**0.5)
i=1
while i*i<n//2:a+=((n//2)+i-1)//i;i+=1
print(8*(n + (a*2 - b*b)))
```
|
instruction
| 0
| 98,540
| 3
| 197,080
|
No
|
output
| 1
| 98,540
| 3
| 197,081
|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Dr. Hedro is astonished. According to his theory, we can make sludge that can dissolve almost everything on the earth. Now he's trying to produce the sludge to verify his theory.
The sludge is produced in a rectangular solid shaped tank whose size is N Γ N Γ 2. Let coordinate of two corner points of tank be (-N/2, -N/2, -1), (N/2, N/2, 1) as shown in Figure 1.
<image>
Figure 1
Doctor pours liquid that is ingredient of the sludge until height of the liquid becomes 1. Next, he get a lid on a tank and rotates slowly, without ruffling, with respect to z axis (Figure 2). After rotating enough long time, sludge is produced. Volume of liquid never changes through this operation.
<image>
Figure 2
Needless to say, ordinary materials cannot be the tank. According to Doctor's theory, there is only one material that is not dissolved by the sludge on the earth. Doctor named it finaldefenceproblem (for short, FDP). To attach FDP tiles inside the tank allows to produce the sludge.
Since to produce FDP is very difficult, the size of FDP tiles are limited to 1 * 1. At first, doctor tried to cover entire the entire inside of the tank. However, it turned out that to make enough number FDP tiles that can cover completely is impossible because it takes too long time. Therefore, he decided to replace FDP tiles where an area the sludge touches is zero with those of ordinary materials. All tiles are very thin, so never affects height of the sludge.
How many number of FDP tiles does doctor need? He has imposed this tough problem on you, his helper.
Constraints
* Judge data consists of at most 150 datasets.
* 2 β€ N β€ 1012
* N is even number
Input
Input file contains several data sets. Each data set has one integer that describes N.
Input ends when N = 0. You should output nothing for this case.
Output
For each data set, print the number of tiles in a line.
Example
Input
2
4
0
Output
24
64
Submitted Solution:
```
while 1:
n=int(input())
if n==0:break
a=0
for i in range(1,n//2):a+=(n+2*i-1)//(2*i)-1
print(8*(2*n-1+a))
```
|
instruction
| 0
| 98,541
| 3
| 197,082
|
No
|
output
| 1
| 98,541
| 3
| 197,083
|
Provide a correct Python 3 solution for this coding contest problem.
Two experienced climbers are planning a first-ever attempt: they start at two points of the equal altitudes on a mountain range, move back and forth on a single route keeping their altitudes equal, and finally meet with each other at a point on the route. A wise man told them that if a route has no point lower than the start points (of the equal altitudes) there is at least a way to achieve the attempt. This is the reason why the two climbers dare to start planning this fancy attempt.
The two climbers already obtained altimeters (devices that indicate altitude) and communication devices that are needed for keeping their altitudes equal. They also picked up a candidate route for the attempt: the route consists of consequent line segments without branches; the two starting points are at the two ends of the route; there is no point lower than the two starting points of the equal altitudes. An illustration of the route is given in Figure E.1 (this figure corresponds to the first dataset of the sample input).
<image>
Figure E.1: An illustration of a route
The attempt should be possible for the route as the wise man said. The two climbers, however, could not find a pair of move sequences to achieve the attempt, because they cannot keep their altitudes equal without a complex combination of both forward and backward moves. For example, for the route illustrated above: a climber starting at p1 (say A) moves to s, and the other climber (say B) moves from p6 to p5; then A moves back to t while B moves to p4; finally A arrives at p3 and at the same time B also arrives at p3. Things can be much more complicated and thus they asked you to write a program to find a pair of move sequences for them.
There may exist more than one possible pair of move sequences, and thus you are requested to find the pair of move sequences with the shortest length sum. Here, we measure the length along the route surface, i.e., an uphill path from (0, 0) to (3, 4) has the length of 5.
Input
The input is a sequence of datasets.
The first line of each dataset has an integer indicating the number of points N (2 β€ N β€ 100) on the route. Each of the following N lines has the coordinates (xi, yi) (i = 1, 2, ... , N) of the points: the two start points are (x1, y1) and (xN, yN); the line segments of the route connect (xi, yi) and (xi+1, yi+1) for i = 1, 2, ... , N - 1. Here, xi is the horizontal distance along the route from the start point x1, and yi is the altitude relative to the start point y1. All the coordinates are non-negative integers smaller than 1000, and inequality xi < xi+1 holds for i = 1, 2, .. , N - 1, and 0 = y1 = yN β€ yi for i = 2, 3, ... , N - 1.
The end of the input is indicated by a line containing a zero.
Output
For each dataset, output the minimum sum of lengths (along the route) of move sequences until the two climbers meet with each other at a point on the route. Each output value may not have an error greater than 0.01.
Example
Input
6
0 0
3 4
9 12
17 6
21 9
33 0
5
0 0
10 0
20 0
30 0
40 0
10
0 0
1 2
3 0
6 3
9 0
11 2
13 0
15 2
16 2
18 0
7
0 0
150 997
300 1
450 999
600 2
750 998
900 0
0
Output
52.5
40.0
30.3356209304689
10078.072814085803
|
instruction
| 0
| 98,545
| 3
| 197,090
|
"Correct Solution:
```
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N = int(readline())
if N == 0:
return False
P = [tuple(map(int, readline().split())) for i in range(N)]
YS = set(y for x, y in P)
Q = P[:]
for i in range(N-1):
x0, y0 = P[i]; x1, y1 = P[i+1]
if y0 != y1:
for y in YS:
if y0 < y < y1 or y1 < y < y0:
x = (x1 - x0)/(y1 - y0)*(y - y0) + x0
assert x0 < x < x1 or x1 < x < x0
Q.append((x, y))
Q.sort()
def f(px, py, qx, qy):
if py == qy:
return abs(px - qx)
return ((px - qx)**2 + (py - qy)**2)**.5
L = len(Q)
INF = 10**18
que = [(0, 0, L-1)]
dist = {(0, L-1): 0}
dd = ((1, -1), (1, 0), (0, -1), (-1, 0), (0, 1), (1, 1), (-1, -1), (-1, 1))
while que:
cost, a, b = heappop(que)
if cost < dist[a, b]:
continue
if a == b:
write("%.16f\n" % cost)
break
ax, ay = Q[a]; bx, by = Q[b]
for da, db in dd:
na = a + da; nb = b + db
if not 0 <= na <= nb < L:
continue
cx, cy = Q[na]; dx, dy = Q[nb]
if cy != dy:
continue
n_cost = cost + f(ax, ay, cx, cy) + f(bx, by, dx, dy)
key = (na, nb)
if n_cost < dist.get(key, INF):
dist[key] = n_cost
heappush(que, (n_cost, na, nb))
else:
write("-1\n")
return True
while solve():
...
```
|
output
| 1
| 98,545
| 3
| 197,091
|
Provide a correct Python 3 solution for this coding contest problem.
Wind Corridor is a covered passageway where strong wind is always blowing. It is a long corridor of width W, and there are several pillars in it. Each pillar is a right prism and its face is a polygon (not necessarily convex).
In this problem, we consider two-dimensional space where the positive x-axis points the east and the positive y-axis points the north. The passageway spans from the south to the north, and its length is infinity. Specifically, it covers the area 0 β€ x β€ W. The outside of the passageway is filled with walls. Each pillar is expressed as a polygon, and all the pillars are located within the corridor without conflicting or touching each other.
Wind blows from the south side of the corridor to the north. For each second, w unit volume of air can be flowed at most if the minimum width of the path of the wind is w. Note that the path may fork and merge, but never overlaps with pillars and walls.
Your task in this problem is to write a program that calculates the maximum amount of air that can be flowed through the corridor per second.
Input
The input consists of multiple datasets. Each dataset has the following format:
The first line of the input contains two integers W and N. W is the width of the corridor, and N is the number of pillars. W and N satisfy the following condition: 1 β€ W β€ 104 and 0 β€ N β€ 200.
Then, N specifications of each pillar follow. Each specification starts with a line that contains a single integer M, which is the number of the vertices of a polygon (3 β€ M β€ 40). The following M lines describe the shape of the polygon. The i-th line (1 β€ i β€ M) contains two integers xi and yi that denote the coordinate of the i-th vertex (0 < xi < W, 0 < yi < 104).
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, your program should print a line that contains the maximum amount of air flow per second, in unit volume. The output may contain arbitrary number of digits after the decimal point, but the absolute error must not exceed 10-6.
Example
Input
5 2
4
1 1
1 2
2 2
2 1
4
3 3
3 4
4 4
4 3
0 0
Output
3.41421356
|
instruction
| 0
| 98,547
| 3
| 197,094
|
"Correct Solution:
```
from heapq import heappush, heappop
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def cross2(p, q):
return p[0]*q[1] - p[1]*q[0]
def dot2(p, q):
return p[0]*q[0] + p[1]*q[1]
def dist2(p):
return p[0]**2 + p[1]**2
def segment_line_dist(x, p0, p1):
z0 = (p1[0] - p0[0], p1[1] - p0[1])
z1 = (x[0] - p0[0], x[1] - p0[1])
if 0 <= dot2(z0, z1) <= dist2(z0):
return cross2(z0, z1)**2 / dist2(z0)
z2 = (x[0] - p1[0], x[1] - p1[1])
return min(dist2(z1), dist2(z2))
def solve():
W, N = map(int, readline().split())
if W == N == 0:
return False
PS = []
for i in range(N):
M = int(readline())
P = [list(map(int, readline().split())) for i in range(M)]
PS.append(P)
G = [[] for i in range(N+2)]
for i in range(N):
Pi = PS[i]
ni = len(Pi)
for j in range(i+1, N):
Pj = PS[j]
r = 10**18
nj = len(Pj)
for p1 in Pi:
for k in range(nj):
q1 = Pj[k-1]; q2 = Pj[k]
r = min(r, segment_line_dist(p1, q1, q2))
for q1 in Pj:
for k in range(ni):
p1 = Pi[k-1]; p2 = Pi[k]
r = min(r, segment_line_dist(q1, p1, p2))
d = r**.5
G[i].append((j, d))
G[j].append((i, d))
d = min(x for x, y in Pi)
G[i].append((N, d))
G[N].append((i, d))
d = W - max(x for x, y in Pi)
G[i].append((N+1, d))
G[N+1].append((i, d))
G[N].append((N+1, W))
G[N+1].append((N, W))
que = [(0, N)]
dist = [10**18]*(N+2)
dist[N] = 0
while que:
cost, v = heappop(que)
if dist[v] < cost:
continue
for w, d in G[v]:
if cost + d < dist[w]:
dist[w] = cost + d
heappush(que, (cost + d, w))
write("%.16f\n" % dist[N+1])
return True
while solve():
...
```
|
output
| 1
| 98,547
| 3
| 197,095
|
Provide a correct Python 3 solution for this coding contest problem.
Wind Corridor is a covered passageway where strong wind is always blowing. It is a long corridor of width W, and there are several pillars in it. Each pillar is a right prism and its face is a polygon (not necessarily convex).
In this problem, we consider two-dimensional space where the positive x-axis points the east and the positive y-axis points the north. The passageway spans from the south to the north, and its length is infinity. Specifically, it covers the area 0 β€ x β€ W. The outside of the passageway is filled with walls. Each pillar is expressed as a polygon, and all the pillars are located within the corridor without conflicting or touching each other.
Wind blows from the south side of the corridor to the north. For each second, w unit volume of air can be flowed at most if the minimum width of the path of the wind is w. Note that the path may fork and merge, but never overlaps with pillars and walls.
Your task in this problem is to write a program that calculates the maximum amount of air that can be flowed through the corridor per second.
Input
The input consists of multiple datasets. Each dataset has the following format:
The first line of the input contains two integers W and N. W is the width of the corridor, and N is the number of pillars. W and N satisfy the following condition: 1 β€ W β€ 104 and 0 β€ N β€ 200.
Then, N specifications of each pillar follow. Each specification starts with a line that contains a single integer M, which is the number of the vertices of a polygon (3 β€ M β€ 40). The following M lines describe the shape of the polygon. The i-th line (1 β€ i β€ M) contains two integers xi and yi that denote the coordinate of the i-th vertex (0 < xi < W, 0 < yi < 104).
The last dataset is followed by a line containing two zeros. This line is not a part of any dataset and should not be processed.
Output
For each dataset, your program should print a line that contains the maximum amount of air flow per second, in unit volume. The output may contain arbitrary number of digits after the decimal point, but the absolute error must not exceed 10-6.
Example
Input
5 2
4
1 1
1 2
2 2
2 1
4
3 3
3 4
4 4
4 3
0 0
Output
3.41421356
|
instruction
| 0
| 98,548
| 3
| 197,096
|
"Correct Solution:
```
def solve():
from itertools import combinations
from heapq import heappush, heappop
def dot(c1, c2):
return c1.real * c2.real + c1.imag * c2.imag
def cross(c1, c2):
return c1.real * c2.imag - c1.imag * c2.real
# get distance between segment and point
def d_sp(sp1, sp2, p):
a = sp2 - sp1
b = p - sp1
if dot(a, b) < 0:
return abs(b)
c = sp1 - sp2
d = p - sp2
if dot(c, d) < 0:
return abs(d)
return abs(cross(a, b) / a)
# get distance between two segments
def d_s(p1, p2, p3, p4):
return min(d_sp(p1, p2, p3), d_sp(p1, p2, p4), d_sp(p3, p4, p1), \
d_sp(p3, p4, p2))
from sys import stdin
file_input = stdin
while True:
W, N = map(int, file_input.readline().split())
if W == 0:
break
if N == 0:
print(W)
continue
polygons = []
adj = [[] for i in range(N + 1)]
adj_s = adj[0]
goal = N + 1
for i in range(1, N + 1):
M = int(file_input.readline())
p = [i]
s_d = W
g_d = W
for j in range(M):
x, y = map(int, file_input.readline().split())
p.append(x + y * 1j)
s_d = min(s_d, x)
g_d = min(g_d, W - x)
adj_s.append((i, s_d))
adj[i].append((goal, g_d))
p.append(p[1])
polygons.append(p)
for p1, p2 in combinations(polygons, 2):
i = p1[0]
j = p2[0]
d = [d_s(v1, v2, v3, v4) for v3, v4 in zip(p2[1:], p2[2:]) \
for v1, v2 in zip(p1[1:], p1[2:])]
d = min(d)
adj[i].append((j, d))
adj[j].append((i, d))
# Dijkstra's algorithm
PQ = [(0, 0)]
isVisited = [False] * (N + 2)
distance = [W] * (N + 2)
distance[0] = 0
while PQ:
u_cost, u = heappop(PQ)
if u == goal:
print(u_cost)
break
if u_cost > distance[u]:
continue
isVisited[u] = True
for v, v_cost in adj[u]:
if isVisited[v]:
continue
t_cost = distance[u] + v_cost
if t_cost < distance[v]:
distance[v] = t_cost
heappush(PQ, (t_cost, v))
solve()
```
|
output
| 1
| 98,548
| 3
| 197,097
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.