message stringlengths 2 19.9k | message_type stringclasses 2
values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
x,k,d = map(int,input().split())
if abs(x) >= k*d:
print(abs(x)-k*d)
exit()
x = abs(x)
r = x%d
if ((x-r)//d)%2 == k%2:
print(r)
else:
print(abs(r-d))
``` | instruction | 0 | 77,350 | 15 | 154,700 |
Yes | output | 1 | 77,350 | 15 | 154,701 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
x, k, d = map(int, input().split())
x = abs(x)
if x-k*d >=0:
print(x-k*d)
else:
y = round((k-x/d)/2)
print(abs(x-(k-2*y)*d))
``` | instruction | 0 | 77,351 | 15 | 154,702 |
Yes | output | 1 | 77,351 | 15 | 154,703 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
X,K,D = map(int,input().split())
X = abs(X)
if X >= K * D:
print(X-K*D)
exit()
K -= X // D
X = X % D
print(D-X if K%2 else X)
``` | instruction | 0 | 77,352 | 15 | 154,704 |
Yes | output | 1 | 77,352 | 15 | 154,705 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
#!/usr/bin/env python3
import sys
sys.setrecursionlimit(10**8)
from bisect import bisect_left
from itertools import product
def input(): return sys.stdin.readline().strip()
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LI(): return list(map(int, input().split()))
def LI_(): return list(map(lambda x: int(x)-1, input().split()))
def LF(): return list(map(float, input().split()))
def LC(): return [c for c in input().split()]
def LLI(n): return [LI() for _ in range(n)]
def NSTR(n): return [input() for _ in range(n)]
def array2d(N, M, initial=0):
return [[initial]*M for _ in range(N)]
def copy2d(orig, N, M):
ret = array2d(N, M)
for i in range(N):
for j in range(M):
ret[i][j] = orig[i][j]
return ret
INF = float("inf")
MOD = 10**9 + 7
def main():
X, K, D = MAP()
# 到達候補は0に近い正と負の二つの数
d, m = divmod(X, D)
cand = (m, m-D)
if X >= 0:
if K <= d:
print(X-K*D)
return
else:
rest = (K-d)
if rest % 2 == 0:
print(cand[0])
return
else:
print(-cand[1])
return
else:
if K <= -d-1:
print(X+K*D)
return
else:
rest = K-(-d-1)
if rest % 2 == 0:
print(-cand[1])
return
else:
print(cand[0])
return
return
if __name__ == '__main__':
main()
``` | instruction | 0 | 77,353 | 15 | 154,706 |
No | output | 1 | 77,353 | 15 | 154,707 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
x,k,d = map(int,input().split())
#print(x,k,d)
if x <= 0:#開始座標が0か負
if x + k*d <=0:#一方向にだけ動かせるとき
ans= abs(x + k*d)
else:
kk=abs(x)//d
tmp=x+kk*d#負の座標間で0に最大まで近づける
tmp2=x+d#正の座標間で0に最大まで近づける
if tmp==0:
tmp=d
tmp2=d
if tmp==tmp2 :#4回移動でループ
if (k-kk)%2==1:
ans=abs(tmp)
else:
ans=0
else:#値が違うとき2回移動でループ
if (k-kk)%2==0:
ans=abs(tmp)
else:
ans=abs(tmp2)
else:#開始座標が正
if x - k*d >=0:#一方向にだけ動かせるとき
ans=abs(x - k*d)
else:
kk=abs(x)//d
tmp=x-kk*d#正の座標間で0に最大まで近づける
tmp2=x-d#負の座標間で0に最大まで近づける
if tmp==0:
tmp=d
tmp2=d
if tmp==tmp2 :#4回移動でループ
if (k-kk)%2==1:
ans=abs(tmp)
else:
ans=0
else:#値が違うとき2回移動でループ
if (k-kk)%2==0:
ans=abs(tmp)
else:
ans=abs(tmp2)
print(ans)
``` | instruction | 0 | 77,354 | 15 | 154,708 |
No | output | 1 | 77,354 | 15 | 154,709 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Takahashi, who lives on the number line, is now at coordinate X. He will make exactly K moves of distance D in the positive or negative direction.
More specifically, in one move, he can go from coordinate x to x + D or x - D.
He wants to make K moves so that the absolute value of the coordinate of the destination will be the smallest possible.
Find the minimum possible absolute value of the coordinate of the destination.
Constraints
* -10^{15} \leq X \leq 10^{15}
* 1 \leq K \leq 10^{15}
* 1 \leq D \leq 10^{15}
* All values in input are integers.
Input
Input is given from Standard Input in the following format:
X K D
Output
Print the minimum possible absolute value of the coordinate of the destination.
Examples
Input
6 2 4
Output
2
Input
7 4 3
Output
1
Input
10 1 2
Output
8
Input
1000000000000000 1000000000000000 1000000000000000
Output
1000000000000000
Submitted Solution:
```
x, k, d = map(int, input().split())
x = abs(x)
if x > d:
# print("a")
times = x // d
k = k - times
x = x - times * d
if k % 2 == 0:
print(x)
else:
print(abs(x - d))
else:
if k % 2 == 0:
print(x)
else:
print(abs(x - d))
``` | instruction | 0 | 77,356 | 15 | 154,712 |
No | output | 1 | 77,356 | 15 | 154,713 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,511 | 15 | 155,022 |
"Correct Solution:
```
def search(x, y, imap, acc):
imap[x][y] = 0
acc += 1
ret = acc
a = b = c = d = 0
if imap[x - 1][y]:
a = search(x - 1, y, imap, acc)
if ret < a:
ret = a
if imap[x + 1][y]:
b = search(x + 1, y, imap, acc)
if ret < b:
ret = b
if imap[x][y - 1]:
c = search(x, y - 1, imap, acc)
if ret < c:
ret = c
if imap[x][y + 1]:
d = search(x, y + 1, imap, acc)
if ret < d:
ret = d
imap[x][y] = 1
return ret
def solve():
while True:
m, n = int(input()), int(input())
if not m:
break
ices = [[0] + list(map(int,input().split())) + [0] for _ in range(n)]
ices.insert(0, [0] * (m + 2),)
ices.append([0] * (m + 2))
score = [[0] * (m + 2) for _ in range(n + 2)]
for x in range(1, n + 1):
for y in range(1, m + 1):
if ices[x][y]:
score[x - 1][y] += 1
score[x + 1][y] += 1
score[x][y - 1] += 1
score[x][y + 1] += 1
ans = 0
for x in range(1, n + 1):
for y in range(1, m + 1):
if score[x][y] in [1, 2] and ices[x][y]:
a = search(x, y, ices, 0)
if ans < a:
ans = a
print(ans)
solve()
``` | output | 1 | 77,511 | 15 | 155,023 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,512 | 15 | 155,024 |
"Correct Solution:
```
def b(M,x,y,n=1):
M[x][y]='0';t=[]
if'1'==M[x-1][y]:t+=[b(M,x-1,y,n+1)]
if'1'==M[x][y-1]:t+=[b(M,x,y-1,n+1)]
if'1'==M[x+1][y]:t+=[b(M,x+1,y,n+1)]
if'1'==M[x][y+1]:t+=[b(M,x,y+1,n+1)]
M[x][y]='1'
return max([n]+t)
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[['0']*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=input().split()
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)if'1'==P[i][j]))
``` | output | 1 | 77,512 | 15 | 155,025 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,513 | 15 | 155,026 |
"Correct Solution:
```
import sys
r=sys.stdin.readline
def s():
def b(M,x,y,n=1):
M[x][y]=0;a=n
if M[x-1][y]:a=max(a,b(M,x-1,y,n+1))
if M[x][y-1]:a=max(a,b(M,x,y-1,n+1))
if M[x+1][y]:a=max(a,b(M,x+1,y,n+1))
if M[x][y+1]:a=max(a,b(M,x,y+1,n+1))
M[x][y]=1
return a
for e in iter(r,'0\n'):
n,m=int(e),int(r())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,r().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)if P[i][j]))
if'__main__'==__name__:s()
``` | output | 1 | 77,513 | 15 | 155,027 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,514 | 15 | 155,028 |
"Correct Solution:
```
# -*- coding: utf-8 -*-
"""
"""
import sys
from sys import stdin
from collections import deque
input = stdin.readline
def bfs(H, W, maze, sx, sy):
max_ans = 1
# 上下左右に移動する場合の座標の変化量
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
path = [(sx, sy)] # 切り取りに含める切手の座標 (まずは探索開始地点のみからスタート)
Q = deque()
Q.append((sx, sy, path))
while Q:
cx, cy, path = Q.popleft() # 現在地の座標と探索状況
for i in range(len(dx)):
nx = cx + dx[i]
ny = cy + dy[i]
# 移動先まで通行可能 かつ 既に探索済でなければ、その先でも探索を続ける
if 0 <= nx < W and 0 <= ny < H and not (nx, ny) in path and maze[ny][nx] == 1:
t = path[:]
t.append((nx, ny))
ans = len(t)
if ans > max_ans:
max_ans = ans
Q.append((nx, ny, t[:]))
return max_ans
def solve(H, W, maze):
# 全てのマスを起点にして、条件を満たす切り取り方をチェックする
ans = 0
for y in range(H):
for x in range(W):
if maze[y][x] == 1:
t = bfs(H, W, maze, x, y) # 座標x, yを起点にした解の一覧
ans = max(ans, t)
return ans
def main(args):
while True:
W = int(input())
H = int(input())
if W == 0 and H == 0:
break
maze = []
for _ in range(H):
maze.append([int(x) for x in input().split()])
ans = solve(H, W, maze)
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
``` | output | 1 | 77,514 | 15 | 155,029 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,515 | 15 | 155,030 |
"Correct Solution:
```
def s():
def b(M,x,y,n=0):
if M[x][y]==0:return n
M[x][y]=0
a=max(b(M,x-1,y,n+1),b(M,x,y-1,n+1),b(M,x+1,y,n+1),b(M,x,y+1,n+1))
M[x][y]=1
return a
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,input().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)))
if'__main__'==__name__:s()
``` | output | 1 | 77,515 | 15 | 155,031 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,516 | 15 | 155,032 |
"Correct Solution:
```
def s():
def b(M,x,y,n=0):
if M[x][y]==0:return n
M[x][y]=0
a=max(b(M,x+s,y+t,n+1)for s,t in[(-1,0),(0,-1),(1,0),(0,1)])
M[x][y]=1
return a
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,input().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)))
if'__main__'==__name__:s()
``` | output | 1 | 77,516 | 15 | 155,033 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,517 | 15 | 155,034 |
"Correct Solution:
```
def s():
def b(M,x,y,n):
M[x][y]=0;a=n
if M[x-1][y]:a=max(a,b(M,x-1,y,n+1))
if M[x][y-1]:a=max(a,b(M,x,y-1,n+1))
if M[x+1][y]:a=max(a,b(M,x+1,y,n+1))
if M[x][y+1]:a=max(a,b(M,x,y+1,n+1))
M[x][y]=1
return a
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,input().split())
print(max(b(P,i,j,1)for i in range(1,m+1)for j in range(1,n+1)if P[i][j]))
if'__main__'==__name__:s()
``` | output | 1 | 77,517 | 15 | 155,035 |
Provide a correct Python 3 solution for this coding contest problem.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None | instruction | 0 | 77,518 | 15 | 155,036 |
"Correct Solution:
```
def solve():
while True:
m, n = int(input()), int(input())
if not m:
break
ices = [[0] + list(map(int,input().split())) + [0] for _ in range(n)]
ices.insert(0, [0] * (m + 2),)
ices.append([0] * (m + 2))
score = [[0] * (m + 2) for _ in range(n + 2)]
for x in range(1, n + 1):
for y in range(1, m + 1):
score[x][y] = ices[x - 1][y] + ices[x + 1][y] + ices[x][y - 1] + ices[x][y + 1]
def search(x, y, imap, acc):
imap[x][y] = 0
acc += 1
a = b = c = d = 0
if imap[x - 1][y]:
a = search(x - 1, y, imap, acc)
if imap[x + 1][y]:
b = search(x + 1, y, imap, acc)
if imap[x][y - 1]:
c = search(x, y - 1, imap, acc)
if imap[x][y + 1]:
d = search(x, y + 1, imap, acc)
imap[x][y] = 1
return max(acc, a, b, c, d)
ans = 0
for x in range(1, n + 1):
for y in range(1, m + 1):
if score[x][y] in [1, 2] and ices[x][y]:
a = search(x, y, ices, 0)
if ans < a:
ans = a
print(ans)
solve()
``` | output | 1 | 77,518 | 15 | 155,037 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
def solve():
while True:
m, n = int(input()), int(input())
if not m:
break
ices = [[0] + list(map(int,input().split())) + [0] for _ in range(n)]
ices.insert(0, [0] * (m + 2),)
ices.append([0] * (m + 2))
# score = [[0] * (m + 2) for _ in range(n + 2)]
#
# for x in range(1, n + 1):
# for y in range(1, m + 1):
# if ices[x][y]:
# score[x][y] += (ices[x - 1][y] + ices[x + 1][y] + ices[x][y - 1] + ices[x][y + 1])
def bfs(x, y, imap, acc):
imap[x][y] = 0
acc += 1
a = b = c = d = 0
if imap[x - 1][y]:
a = bfs(x - 1, y, imap, acc)
if imap[x + 1][y]:
b = bfs(x + 1, y, imap, acc)
if imap[x][y - 1]:
c = bfs(x, y - 1, imap, acc)
if imap[x][y + 1]:
d = bfs(x, y + 1, imap, acc)
imap[x][y] = 1
return max(acc, a, b, c, d)
ans = 0
for x in range(1, n + 1):
for y in range(1, m + 1):
#if score[x][y] in [1, 2] and ices[x][y]:
if ices[x][y]:
a = bfs(x, y, ices, 0)
if ans < a:
ans = a
print(ans)
solve()
``` | instruction | 0 | 77,519 | 15 | 155,038 |
Yes | output | 1 | 77,519 | 15 | 155,039 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
while True:
m = int(input())
n = int(input())
if m==n==0: exit()
graph = []
for _ in range(n):
graph.append(list(map(int,input().split())))
res = 0
def dfs(r,c,ice):
global res
ice += 1
graph[r][c] = 0
for x,y in [(0,1), (1,0), (0,-1), (-1,0)]:
nr,nc = r+x,c+y
if nr<0 or nc<0 or nr>=n or nc>=m: continue
if graph[nr][nc] == 1:
dfs(nr,nc,ice)
else:
graph[r][c] = 1
res = max(res, ice)
for i in range(n):
for j in range(m):
if graph[i][j] == 1:
dfs(i,j,0)
print(res)
``` | instruction | 0 | 77,520 | 15 | 155,040 |
Yes | output | 1 | 77,520 | 15 | 155,041 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
while 1:
M = int(input())
N = int(input())
if M == N == 0:
break
S = [list(map(int, input().split())) for i in range(N)]
used=[[0]*M for i in range(N)]
def dfs(x, y, dd=((-1,0),(0,-1),(1,0),(0,1))):
r = 0
for dx, dy in dd:
nx = x + dx; ny = y + dy
if 0 <= nx < M and 0 <= ny < N and S[ny][nx] and not used[ny][nx]:
used[ny][nx] = 1
r = max(r, dfs(nx, ny)+1)
used[ny][nx] = 0
return r
ans = 0
for i in range(N):
for j in range(M):
if S[i][j]:
used[i][j] = 1
ans = max(ans, dfs(j, i)+1)
used[i][j] = 0
print(ans)
``` | instruction | 0 | 77,521 | 15 | 155,042 |
Yes | output | 1 | 77,521 | 15 | 155,043 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
def s():
def b(M,x,y,n=1):
M[x][y]=0;a=n
for p,q in[(-1,0),(0,-1),(1,0),(0,1)]:
if M[x+p][y+q]:
t=b(M,x+p,y+q,n+1)
if a<t:a=t
M[x][y]=1
return a
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,input().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)if P[i][j]))
if'__main__'==__name__:s()
``` | instruction | 0 | 77,522 | 15 | 155,044 |
Yes | output | 1 | 77,522 | 15 | 155,045 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
# -*- coding: utf-8 -*-
"""
"""
import sys
from sys import stdin
from collections import deque
input = stdin.readline
def bfs(H, W, maze, sx, sy):
# 幅優先探索で切手の切り取りパタンをチェックする
ans = 1
max_ans = 0
# 上下左右に移動する場合の座標の変化量
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
Q = deque()
Q.append((ans, sx, sy, maze))
while Q:
ans, cx, cy, maze = Q.popleft() # 現在地の座標と探索状況
for i in range(len(dx)):
nx = cx + dx[i]
ny = cy + dy[i]
# 移動先まで通行可能 かつ 既に探索済でなければ、その先でも探索を続ける
if 0 <= nx < W and 0 <= ny < H and maze[ny][nx] == 1:
ans += 1
max_ans = max(max_ans, ans)
t = maze[:]
t[ny][nx] = 0
Q.append((ans, nx, ny, t))
return max_ans
def solve(H, W, maze):
# 全てのマスを起点にして、条件を満たす切り取り方をチェックする
ans = 0
for y in range(H):
for x in range(W):
if maze[y][x] == 1:
t = bfs(H, W, maze, x, y) # 座標x, yを起点にした解の一覧
ans = max(ans, t)
return ans
def main(args):
while True:
W = int(input())
H = int(input())
if W == 0 and H == 0:
break
maze = []
for _ in range(H):
maze.append([int(x) for x in input().split()])
ans = solve(H, W, maze)
print(ans)
if __name__ == '__main__':
main(sys.argv[1:])
``` | instruction | 0 | 77,523 | 15 | 155,046 |
No | output | 1 | 77,523 | 15 | 155,047 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
def s():
def b(M,x,y,n=1):
M[x][y]=0;a=n
if M[x-1][y]:
t=b(M,x-1,y,n+1)
if a<t:a=t
if M[x][y-1]:
t=b(M,x,y-1,n+1)
if a<t:a=t
if M[x+1][y]:
t=b(M,x+1,y1,n+1)
if a<t:a=t
if M[x][y+1]:
t=b(M,x,y+1,n+1)
if a<t:a=t
M[x][y]=1
return a
for e in iter(input,'0'):
n,m=int(e),int(input())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,input().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)if P[i][j]))
if'__main__'==__name__:s()
``` | instruction | 0 | 77,524 | 15 | 155,048 |
No | output | 1 | 77,524 | 15 | 155,049 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
while 1:
M = int(input())
N = int(input())
if M == N == 0:
break
S = [list(map(int, input().split())) for i in range(N)]
used=[[0]*M for i in range(N)]
def dfs(x, y, dd=((-1,0),(0,-1),(1,0),(0,1))):
r = 0
for dx, dy in dd:
nx = x + dx; ny = y + dy
if 0 <= nx < M and 0 <= ny < N and S[ny][nx] and not used[ny][nx]:
used[ny][nx] = 1
r = max(r, dfs(nx, ny)+1)
used[ny][nx] = 0
return r
ans = 0
for i in range(N):
for j in range(M):
if S[i][j]:
used[i][j] = 1
ans = max(ans, dfs(i, j)+1)
used[i][j] = 0
print(ans)
``` | instruction | 0 | 77,525 | 15 | 155,050 |
No | output | 1 | 77,525 | 15 | 155,051 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
problem
One day in the cold winter, JOI Taro decided to break the thin ice in the plaza and play. The square is rectangular and is divided into m sections in the east-west direction and n sections in the north-south direction, that is, m × n. In addition, there are sections with and without thin ice. JOI Taro decided to move the plot while breaking the thin ice according to the following rules.
* You can start breaking thin ice from any compartment with thin ice.
* Adjacent to either north, south, east, or west, you can move to a section with thin ice that has not yet been broken.
* Be sure to break the thin ice in the area you moved to.
Create a program to find the maximum number of sections that JOI Taro can move while breaking thin ice. However, 1 ≤ m ≤ 90 and 1 ≤ n ≤ 90. With the input data given, there are no more than 200,000 ways to move.
input
The input consists of multiple datasets. Each dataset is given in the following format.
The input is n + 2 lines. The integer m is written on the first line. The integer n is written on the second line. In each line from the 3rd line to the n + 2nd line, m 0s or 1s are written, separated by blanks, and indicates whether or not there is thin ice in each section. If we write the i-th section from the north and the j-th section from the west as (i, j) (1 ≤ i ≤ n, 1 ≤ j ≤ m), the j-th value on the second line of i + 2 is It is 1 if there is thin ice in compartment (i, j) and 0 if there is no thin ice in compartment (i, j).
When both m and n are 0, it indicates the end of input. The number of data sets does not exceed 5.
output
Output the maximum number of sections that can be moved for each data set on one line.
Examples
Input
3
3
1 1 0
1 0 1
1 1 0
5
3
1 1 1 0 1
1 1 0 0 0
1 0 0 0 1
0
0
Output
5
5
Input
None
Output
None
Submitted Solution:
```
import sys
r=sys.stdin.readline
def s():
def b(M,x,y,n=1):
M[x][y]=0;a=n
if M[x-1][y]:a=max(a,b(M,x-1,y,n+1))
if M[x][y-1]:a=max(a,b(M,x,y-1,n+1))
if M[x+1][y]:a=max(a,b(M,x+1,y,n+1))
if M[x][y+1]:a=max(a,b(M,x,y+1,n+1))
M[x][y]=1
return a
for e in iter(r,'0'):
n,m=int(e),int(r())
P=[[0]*(n+2)for _ in[0]*(m+2)]
for i in range(m):P[i+1][1:-1]=map(int,r().split())
print(max(b(P,i,j)for i in range(1,m+1)for j in range(1,n+1)if P[i][j]))
if'__main__'==__name__:s()
``` | instruction | 0 | 77,526 | 15 | 155,052 |
No | output | 1 | 77,526 | 15 | 155,053 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i.
You would like to put together some boxes. Putting together boxes with indices in the segment [l, r] means that you will move some of them in such a way that their positions will form some segment [x, x + (r - l)].
In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose i and change a_i by 1, all positions should remain distinct). You spend w_i units of energy moving the box i by one cell. You can move any box any number of times, in arbitrary order.
Sometimes weights of some boxes change, so you have queries of two types:
1. id nw — weight w_{id} of the box id becomes nw.
2. l r — you should compute the minimum total energy needed to put together boxes with indices in [l, r]. Since the answer can be rather big, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7. Note that the boxes are not moved during the query, you only should compute the answer.
Note that you should minimize the answer, not its remainder modulo 10^9 + 7. So if you have two possible answers 2 ⋅ 10^9 + 13 and 2 ⋅ 10^9 + 14, you should choose the first one and print 10^9 + 6, even though the remainder of the second answer is 0.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of boxes and the number of queries.
The second line contains n integers a_1, a_2, ... a_n (1 ≤ a_i ≤ 10^9) — the positions of the boxes. All a_i are distinct, a_{i - 1} < a_i holds for all valid i.
The third line contains n integers w_1, w_2, ... w_n (1 ≤ w_i ≤ 10^9) — the initial weights of the boxes.
Next q lines describe queries, one query per line.
Each query is described in a single line, containing two integers x and y. If x < 0, then this query is of the first type, where id = -x, nw = y (1 ≤ id ≤ n, 1 ≤ nw ≤ 10^9). If x > 0, then the query is of the second type, where l = x and r = y (1 ≤ l_j ≤ r_j ≤ n). x can not be equal to 0.
Output
For each query of the second type print the answer on a separate line. Since answer can be large, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7.
Example
Input
5 8
1 2 6 7 10
1 1 1 1 2
1 1
1 5
1 3
3 5
-3 5
-1 10
1 4
2 5
Output
0
10
3
4
18
7
Note
Let's go through queries of the example:
1. 1\ 1 — there is only one box so we don't need to move anything.
2. 1\ 5 — we can move boxes to segment [4, 8]: 1 ⋅ |1 - 4| + 1 ⋅ |2 - 5| + 1 ⋅ |6 - 6| + 1 ⋅ |7 - 7| + 2 ⋅ |10 - 8| = 10.
3. 1\ 3 — we can move boxes to segment [1, 3].
4. 3\ 5 — we can move boxes to segment [7, 9].
5. -3\ 5 — w_3 is changed from 1 to 5.
6. -1\ 10 — w_1 is changed from 1 to 10. The weights are now equal to w = [10, 1, 5, 1, 2].
7. 1\ 4 — we can move boxes to segment [1, 4].
8. 2\ 5 — we can move boxes to segment [5, 8].
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from bisect import *
def rint():
return map(int, sys.stdin.readline().split())
"""
BIT : Binary Index Tree, Fenwick Tree
level means power of 2, which is equal to lengh of items to be summed in fw_tree[i]
01234567
oxoxoxoxoxoxoxox : level 0
ooxxooxxooxxooxx : level 1
ooooxxxxooooxxxx : level 2
ooooooooxxxxxxxx : level 3
"""
# start of BIT
def fw_level(i):
i += 1
return i&~i - 1
def fw_add(fwt, i, v):
while i < n:
fwt[i] += v
i += 2**fw_level(i)
# get sum of values of items [0 ~ i] inclusive
def fw_get_sum(fwt, i):
s = 0
while i >= 0:
s += fwt[i]
i -= 2**fw_level(i)
return s
# get sum of values of items [l ~ r]
def fw_get_sum_range(fwt, l, r):
return fw_get_sum(fwt, r) - fw_get_sum(fwt, l-1)
def init_fw_tree(n):
return [0]*n
# [l, r) range fw bisect
def fw_bisect(fwt, v, l, r):
while l < r:
mid = (l+r)//2
if v < fw_get_sum(fwt, mid):
r = mid
else:
l = mid+1
return l
# end of BIT
#div version fw
div_val = 10**9 + 7
def fw_add_div(fwt, i, v):
while i < n:
fwt[i] += v
fwt[i] %= div_val
i += 2**fw_level(i)
def fw_get_sum_div(fwt, i):
s = 0
while i >= 0:
s += fwt[i]
s %= div_val
i -= 2**fw_level(i)
return s
def fw_get_sum_range_div(fwt, l, r):
return fw_get_sum_div(fwt, r) - fw_get_sum_div(fwt, l-1)
def get_fixed_item_index(l, r):
mid_sum = fw_get_sum_range(fwt_w, l, r)/2
#print("mid_sum : ", mid_sum)
mid_sum += fw_get_sum(fwt_w, l-1)
#print("mid_sum : ", mid_sum)
return fw_bisect(fwt_w, mid_sum, l, r+1)
def find_min(l, r):
min_sum = 0
si = get_fixed_item_index(l,r)
#print("si l r : ", si, l, r)
# for i in range(l, si):
# min_sum += w(i)*(a[si] - a[i] - 1 - (si - i - 1))
# min_sum += wsum(l, si-1)*(a[si] - si) + wai_sum(l,si-1)
min_sum += (a[si] - si)*fw_get_sum_range(fwt_w, l, si-1) - \
fw_get_sum_range_div(fwt_awi, l, si-1)
# for i in range(si+1, ri+1):
# min_sum += w(i)*(a[i] - a[si] - 1 - (i - si - 1))
# min_sum += w(i)*(a[i] - a[si] - 1 - (i - si - 1))
# min_sum += wsum(si+1, r)*(si - a[si]) - wai_sum(si+1, r)
min_sum += -(a[si]-si)*fw_get_sum_range(fwt_w, si+1, r) + \
fw_get_sum_range_div(fwt_awi, si+1, r)
if min_sum < 0:
min_sum += ((-min_sum)//div_val+1)*div_val
return min_sum % div_val
def update_w(ni, nw):
delta = nw - w[ni]
w[ni] = nw
fw_add(fwt_w, ni, delta)
fw_add_div(fwt_awi, ni, delta*(a[ni]-ni))
n, q = rint()
a = list(rint())
w = list(rint())
fwt_w = init_fw_tree(n)
fwt_awi = init_fw_tree(n)
for i in range(n):
fw_add(fwt_w, i, w[i])
for i in range(n):
fw_add_div(fwt_awi, i, w[i]*(a[i]-i))
for _ in range(q):
x, y = rint()
if x > 0:
l = x-1
r = y-1
#for i in range(n):
# print("sum until ", i, fw_get_sum(fwt_w, i))
print(find_min(l, r))
else:
i = -x-1
nw = y
update_w(i, nw)
``` | instruction | 0 | 77,567 | 15 | 155,134 |
No | output | 1 | 77,567 | 15 | 155,135 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i.
You would like to put together some boxes. Putting together boxes with indices in the segment [l, r] means that you will move some of them in such a way that their positions will form some segment [x, x + (r - l)].
In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose i and change a_i by 1, all positions should remain distinct). You spend w_i units of energy moving the box i by one cell. You can move any box any number of times, in arbitrary order.
Sometimes weights of some boxes change, so you have queries of two types:
1. id nw — weight w_{id} of the box id becomes nw.
2. l r — you should compute the minimum total energy needed to put together boxes with indices in [l, r]. Since the answer can be rather big, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7. Note that the boxes are not moved during the query, you only should compute the answer.
Note that you should minimize the answer, not its remainder modulo 10^9 + 7. So if you have two possible answers 2 ⋅ 10^9 + 13 and 2 ⋅ 10^9 + 14, you should choose the first one and print 10^9 + 6, even though the remainder of the second answer is 0.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of boxes and the number of queries.
The second line contains n integers a_1, a_2, ... a_n (1 ≤ a_i ≤ 10^9) — the positions of the boxes. All a_i are distinct, a_{i - 1} < a_i holds for all valid i.
The third line contains n integers w_1, w_2, ... w_n (1 ≤ w_i ≤ 10^9) — the initial weights of the boxes.
Next q lines describe queries, one query per line.
Each query is described in a single line, containing two integers x and y. If x < 0, then this query is of the first type, where id = -x, nw = y (1 ≤ id ≤ n, 1 ≤ nw ≤ 10^9). If x > 0, then the query is of the second type, where l = x and r = y (1 ≤ l_j ≤ r_j ≤ n). x can not be equal to 0.
Output
For each query of the second type print the answer on a separate line. Since answer can be large, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7.
Example
Input
5 8
1 2 6 7 10
1 1 1 1 2
1 1
1 5
1 3
3 5
-3 5
-1 10
1 4
2 5
Output
0
10
3
4
18
7
Note
Let's go through queries of the example:
1. 1\ 1 — there is only one box so we don't need to move anything.
2. 1\ 5 — we can move boxes to segment [4, 8]: 1 ⋅ |1 - 4| + 1 ⋅ |2 - 5| + 1 ⋅ |6 - 6| + 1 ⋅ |7 - 7| + 2 ⋅ |10 - 8| = 10.
3. 1\ 3 — we can move boxes to segment [1, 3].
4. 3\ 5 — we can move boxes to segment [7, 9].
5. -3\ 5 — w_3 is changed from 1 to 5.
6. -1\ 10 — w_1 is changed from 1 to 10. The weights are now equal to w = [10, 1, 5, 1, 2].
7. 1\ 4 — we can move boxes to segment [1, 4].
8. 2\ 5 — we can move boxes to segment [5, 8].
Submitted Solution:
```
u=list(map(input,range(11)))
print('''0
10
3
4
18
7
''')
``` | instruction | 0 | 77,568 | 15 | 155,136 |
No | output | 1 | 77,568 | 15 | 155,137 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i.
You would like to put together some boxes. Putting together boxes with indices in the segment [l, r] means that you will move some of them in such a way that their positions will form some segment [x, x + (r - l)].
In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose i and change a_i by 1, all positions should remain distinct). You spend w_i units of energy moving the box i by one cell. You can move any box any number of times, in arbitrary order.
Sometimes weights of some boxes change, so you have queries of two types:
1. id nw — weight w_{id} of the box id becomes nw.
2. l r — you should compute the minimum total energy needed to put together boxes with indices in [l, r]. Since the answer can be rather big, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7. Note that the boxes are not moved during the query, you only should compute the answer.
Note that you should minimize the answer, not its remainder modulo 10^9 + 7. So if you have two possible answers 2 ⋅ 10^9 + 13 and 2 ⋅ 10^9 + 14, you should choose the first one and print 10^9 + 6, even though the remainder of the second answer is 0.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of boxes and the number of queries.
The second line contains n integers a_1, a_2, ... a_n (1 ≤ a_i ≤ 10^9) — the positions of the boxes. All a_i are distinct, a_{i - 1} < a_i holds for all valid i.
The third line contains n integers w_1, w_2, ... w_n (1 ≤ w_i ≤ 10^9) — the initial weights of the boxes.
Next q lines describe queries, one query per line.
Each query is described in a single line, containing two integers x and y. If x < 0, then this query is of the first type, where id = -x, nw = y (1 ≤ id ≤ n, 1 ≤ nw ≤ 10^9). If x > 0, then the query is of the second type, where l = x and r = y (1 ≤ l_j ≤ r_j ≤ n). x can not be equal to 0.
Output
For each query of the second type print the answer on a separate line. Since answer can be large, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7.
Example
Input
5 8
1 2 6 7 10
1 1 1 1 2
1 1
1 5
1 3
3 5
-3 5
-1 10
1 4
2 5
Output
0
10
3
4
18
7
Note
Let's go through queries of the example:
1. 1\ 1 — there is only one box so we don't need to move anything.
2. 1\ 5 — we can move boxes to segment [4, 8]: 1 ⋅ |1 - 4| + 1 ⋅ |2 - 5| + 1 ⋅ |6 - 6| + 1 ⋅ |7 - 7| + 2 ⋅ |10 - 8| = 10.
3. 1\ 3 — we can move boxes to segment [1, 3].
4. 3\ 5 — we can move boxes to segment [7, 9].
5. -3\ 5 — w_3 is changed from 1 to 5.
6. -1\ 10 — w_1 is changed from 1 to 10. The weights are now equal to w = [10, 1, 5, 1, 2].
7. 1\ 4 — we can move boxes to segment [1, 4].
8. 2\ 5 — we can move boxes to segment [5, 8].
Submitted Solution:
```
n, q = map(int, input().split())
boxPos = list(map(int, input().split()))
weights = list(map(int, input().split()))
MOD = 10**9 + 7
for i in range(n):
boxPos[i] -= i
for qta in range(q):
x, y = map(int, input().split())
if x < 0:
x = - (x + 1)
weights[x] = y
else:
x -= 1
y -= 1
ans = 10**100
for cp in range(x, y + 1):
convergeCost = 0
for box in range(x, y + 1):
convergeCost += weights[box] * abs(boxPos[box] - boxPos[cp])
ans = min(ans, convergeCost)
print(ans)
``` | instruction | 0 | 77,569 | 15 | 155,138 |
No | output | 1 | 77,569 | 15 | 155,139 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is an infinite line consisting of cells. There are n boxes in some cells of this line. The i-th box stands in the cell a_i and has weight w_i. All a_i are distinct, moreover, a_{i - 1} < a_i holds for all valid i.
You would like to put together some boxes. Putting together boxes with indices in the segment [l, r] means that you will move some of them in such a way that their positions will form some segment [x, x + (r - l)].
In one step you can move any box to a neighboring cell if it isn't occupied by another box (i.e. you can choose i and change a_i by 1, all positions should remain distinct). You spend w_i units of energy moving the box i by one cell. You can move any box any number of times, in arbitrary order.
Sometimes weights of some boxes change, so you have queries of two types:
1. id nw — weight w_{id} of the box id becomes nw.
2. l r — you should compute the minimum total energy needed to put together boxes with indices in [l, r]. Since the answer can be rather big, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7. Note that the boxes are not moved during the query, you only should compute the answer.
Note that you should minimize the answer, not its remainder modulo 10^9 + 7. So if you have two possible answers 2 ⋅ 10^9 + 13 and 2 ⋅ 10^9 + 14, you should choose the first one and print 10^9 + 6, even though the remainder of the second answer is 0.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 2 ⋅ 10^5) — the number of boxes and the number of queries.
The second line contains n integers a_1, a_2, ... a_n (1 ≤ a_i ≤ 10^9) — the positions of the boxes. All a_i are distinct, a_{i - 1} < a_i holds for all valid i.
The third line contains n integers w_1, w_2, ... w_n (1 ≤ w_i ≤ 10^9) — the initial weights of the boxes.
Next q lines describe queries, one query per line.
Each query is described in a single line, containing two integers x and y. If x < 0, then this query is of the first type, where id = -x, nw = y (1 ≤ id ≤ n, 1 ≤ nw ≤ 10^9). If x > 0, then the query is of the second type, where l = x and r = y (1 ≤ l_j ≤ r_j ≤ n). x can not be equal to 0.
Output
For each query of the second type print the answer on a separate line. Since answer can be large, print the remainder it gives when divided by 1000 000 007 = 10^9 + 7.
Example
Input
5 8
1 2 6 7 10
1 1 1 1 2
1 1
1 5
1 3
3 5
-3 5
-1 10
1 4
2 5
Output
0
10
3
4
18
7
Note
Let's go through queries of the example:
1. 1\ 1 — there is only one box so we don't need to move anything.
2. 1\ 5 — we can move boxes to segment [4, 8]: 1 ⋅ |1 - 4| + 1 ⋅ |2 - 5| + 1 ⋅ |6 - 6| + 1 ⋅ |7 - 7| + 2 ⋅ |10 - 8| = 10.
3. 1\ 3 — we can move boxes to segment [1, 3].
4. 3\ 5 — we can move boxes to segment [7, 9].
5. -3\ 5 — w_3 is changed from 1 to 5.
6. -1\ 10 — w_1 is changed from 1 to 10. The weights are now equal to w = [10, 1, 5, 1, 2].
7. 1\ 4 — we can move boxes to segment [1, 4].
8. 2\ 5 — we can move boxes to segment [5, 8].
Submitted Solution:
```
#!/usr/bin/env python3
import sys
from bisect import *
def rint():
return map(int, sys.stdin.readline().split())
"""
BIT : Binary Index Tree, Fenwick Tree
level means power of 2, which is equal to lengh of items to be summed in fw_tree[i]
01234567
oxoxoxoxoxoxoxox : level 0
ooxxooxxooxxooxx : level 1
ooooxxxxooooxxxx : level 2
ooooooooxxxxxxxx : level 3
"""
# start of BIT
def fw_level(i):
i += 1
return i&~i - 1
def fw_add(fwt, i, v):
while i < n:
fwt[i] += v
i += 2**fw_level(i)
# get sum of values of items [0 ~ i] inclusive
def fw_get_sum(fwt, i):
s = 0
while i >= 0:
s += fwt[i]
i -= 2**fw_level(i)
return s
# get sum of values of items [l ~ r]
def fw_get_sum_range(fwt, l, r):
return fw_get_sum(fwt, r) - fw_get_sum(fwt, l-1)
def init_fw_tree(n):
return [0]*n
# [l, r) range fw bisect
def fw_bisect(fwt, v, l, r):
while l < r:
mid = (l+r)//2
if v < fw_get_sum(fwt, mid):
r = mid
else:
l = mid+1
return l
# end of BIT
#div version fw
div_val = 10**9 + 7
def fw_add_div(fwt, i, v):
while i < n:
fwt[i] += v
if fwt[i] < 0:
fwt[i] += ((-fwt[i])//div_val+1)*div_val
fwt[i] %= div_val
i += 2**fw_level(i)
def fw_get_sum_div(fwt, i):
s = 0
while i >= 0:
s += fwt[i]
s %= div_val
i -= 2**fw_level(i)
return s
def fw_get_sum_range_div(fwt, l, r):
return fw_get_sum_div(fwt, r) - fw_get_sum_div(fwt, l-1)
def get_fixed_item_index(l, r):
mid_sum = fw_get_sum_range(fwt_w, l, r)/2
#print("mid_sum : ", mid_sum)
mid_sum += fw_get_sum(fwt_w, l-1)
#print("mid_sum : ", mid_sum)
return fw_bisect(fwt_w, mid_sum, l, r+1)
def find_min(l, r):
min_sum = 0
si = get_fixed_item_index(l,r)
#print("si l r : ", si, l, r)
# for i in range(l, si):
# min_sum += w(i)*(a[si] - a[i] - 1 - (si - i - 1))
# min_sum += wsum(l, si-1)*(a[si] - si) + wai_sum(l,si-1)
min_sum += (a[si] - si)*fw_get_sum_range(fwt_w, l, si-1) - \
fw_get_sum_range_div(fwt_awi, l, si-1)
# for i in range(si+1, ri+1):
# min_sum += w(i)*(a[i] - a[si] - 1 - (i - si - 1))
# min_sum += w(i)*(a[i] - a[si] - 1 - (i - si - 1))
# min_sum += wsum(si+1, r)*(si - a[si]) - wai_sum(si+1, r)
min_sum += -(a[si]-si)*fw_get_sum_range(fwt_w, si+1, r) + \
fw_get_sum_range_div(fwt_awi, si+1, r)
if min_sum < 0:
min_sum += ((-min_sum)//div_val+1)*div_val
return min_sum % div_val
def update_w(ni, nw):
delta = nw - w[ni]
w[ni] = nw
fw_add(fwt_w, ni, delta)
fw_add_div(fwt_awi, ni, delta*(a[ni]-ni))
n, q = rint()
a = list(rint())
w = list(rint())
fwt_w = init_fw_tree(n)
fwt_awi = init_fw_tree(n)
for i in range(n):
fw_add(fwt_w, i, w[i])
for i in range(n):
fw_add_div(fwt_awi, i, w[i]*(a[i]-i))
for _ in range(q):
x, y = rint()
if x > 0:
l = x-1
r = y-1
#for i in range(n):
# print("sum until ", i, fw_get_sum(fwt_w, i))
print(find_min(l, r))
else:
i = -x-1
nw = y
update_w(i, nw)
``` | instruction | 0 | 77,570 | 15 | 155,140 |
No | output | 1 | 77,570 | 15 | 155,141 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,609 | 15 | 155,218 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
def main():
h, v = hv = ([0], [0])
f = {'W': (v, -1), 'S': (v, 1), 'A': (h, -1), 'D': (h, 1)}.get
for _ in range(int(input())):
del h[1:], v[1:]
for l, d in map(f, input()):
l.append(l[-1] + d)
x = y = 1
for l in hv:
lh, a, n = (min(l), max(l)), 200001, 0
for b in filter(lh.__contains__, l):
if a != b:
a = b
n += 1
le = lh[1] - lh[0] + 1
x, y = y * le, x * (le - (n < 3 <= le))
print(x if x < y else y)
if __name__ == '__main__':
main()
``` | output | 1 | 77,609 | 15 | 155,219 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,610 | 15 | 155,220 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
import sys
def work(c,c1, s):
maxlast, maxfirst,minlast,minfirst = 0,0,0,0
max = 0
min = 0
y = 0
for i in range(len(s)):
if s[i] == c:
y += 1
elif s[i] == c1:
y -=1
if max < y:
maxfirst,maxlast = i,i
max = y
elif max ==y :
maxlast = i
if y < min:
minlast,minfirst =i,i
min = y
elif min == y:
minlast = i
flag = 0
if (maxlast<minfirst or maxfirst>minlast) and max-min > 1:
flag = 1
return max-min+1,flag
count = 0
for line in sys.stdin:
if count == 0:
n = int(line.strip().split(' ')[0])
#k = int(line.strip().split(' ')[1])
#m = int(line.strip().split(' ')[2])
count += 1
continue
s = line.strip()
flag,flag1 =0,0
n,flag = work('W','S', s)
m,flag1 = work('A', 'D', s)
res = n * m
if flag1 and flag:
res = min(n*(m-1),m*(n-1))
elif flag:
res = m*(n-1)
elif flag1:
res = (m-1)*n
print(res)
``` | output | 1 | 77,610 | 15 | 155,221 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,611 | 15 | 155,222 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
for _ in range(int(input())):
s = input().strip()
ans = 10**15
suffix_change = [0]*len(s)
mx_x = mn_x = mx_y = mn_y = 0
curr_x = curr_y = 0
for j in range(len(s)-1,-1,-1):
i = s[j]
if i == 'W':
curr_y -= 1
elif i == 'A':
curr_x += 1
elif i == 'S':
curr_y += 1
elif i == 'D':
curr_x -= 1
mx_x = max(mx_x, curr_x)
mn_x = min(mn_x, curr_x)
mx_y = max(mx_y, curr_y)
mn_y = min(mn_y, curr_y)
suffix_change[j] = [mx_x,mn_x,mx_y,mn_y]
final_x = -curr_x
final_y = -curr_y
ans = (mx_x-mn_x+1)*(mx_y-mn_y+1)
mx_x = mn_x = mx_y = mn_y = 0
curr_x = curr_y = 0
changes = [[0,1],[0,-1],[1,0],[-1,0]]
for j in range(len(s)):
i = s[j]
if i == 'W':
curr_y += 1
elif i == 'A':
curr_x -= 1
elif i == 'S':
curr_y -= 1
elif i == 'D':
curr_x += 1
mx_x = max(mx_x, curr_x)
mn_x = min(mn_x, curr_x)
mx_y = max(mx_y, curr_y)
mn_y = min(mn_y, curr_y)
if j < len(s) - 1:
mx_x2, mn_x2, mx_y2, mn_y2 = suffix_change[j+1]
mx_x2 += final_x
mn_x2 += final_x
mx_y2 += final_y
mn_y2 += final_y
for change in changes:
ans = min(ans, (max(mx_x,mx_x2 + change[0]) - min(mn_x,mn_x2 + change[0]) + 1) * \
(max(mx_y, mx_y2 + change[1]) - min(mn_y, mn_y2 + change[1]) + 1))
print(ans)
``` | output | 1 | 77,611 | 15 | 155,223 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,612 | 15 | 155,224 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
for _ in range(int(input())):
s=input()
ar=["AD","WS"]
nr=[[],[]]
for e in s:
if(e in ar[0]):nr[0].append(e)
else: nr[1].append(e)
b,c=[float('inf')]*2,[float('inf')]*2
for i in range(2):
sm=[0]
for el in nr[i]:sm+=[sm[-1]+(1 if el==ar[i][0] else -1)]
for _ in range(2):
f=sm.index(min(sm))
l=len(sm)-1-sm[::-1].index(max(sm))
bse=sm[l]-sm[f]+1
bst=bse
if(bse>=3 and l<f):bst-=1
b[i]=min(b[i],bse)
c[i]=min(c[i],bst)
for j in range(len(sm)):sm[j]*=-1
print(min(b[0]*c[1],b[1]*c[0]))
``` | output | 1 | 77,612 | 15 | 155,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,613 | 15 | 155,226 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
import sys
input = sys.stdin.readline
Q=int(input())
for testcases in range(Q):
S=input().strip()
X=Y=0
MAXX=MINX=MAXY=MINY=0
for s in S:
if s=="D":
X+=1
MAXX=max(MAXX,X)
elif s=="A":
X-=1
MINX=min(MINX,X)
elif s=="W":
Y+=1
MAXY=max(MAXY,Y)
else:
Y-=1
MINY=min(MINY,Y)
#print(MAXX,MINX,MAXY,MINY)
MAXXLIST=[]
MINXLIST=[]
MAXYLIST=[]
MINYLIST=[]
if MAXX==0:
MAXXLIST.append(0)
if MAXY==0:
MAXYLIST.append(0)
if MINX==0:
MINXLIST.append(0)
if MINY==0:
MINYLIST.append(0)
X=Y=0
for i in range(len(S)):
s=S[i]
if s=="D":
X+=1
if X==MAXX:
MAXXLIST.append(i+1)
elif s=="A":
X-=1
if X==MINX:
MINXLIST.append(i+1)
elif s=="W":
Y+=1
if Y==MAXY:
MAXYLIST.append(i+1)
else:
Y-=1
if Y==MINY:
MINYLIST.append(i+1)
#print(MAXXLIST)
#print(MAXYLIST)
#print(MINXLIST)
#print(MINYLIST)
ANS=(MAXX-MINX+1)*(MAXY-MINY+1)
#print(ANS)
if MAXX-MINX>1:
if MAXXLIST[0]>MINXLIST[-1] or MINXLIST[0]>MAXXLIST[-1]:
ANS=min(ANS,(MAXX-MINX)*(MAXY-MINY+1))
if MAXY-MINY>1:
if MAXYLIST[0]>MINYLIST[-1] or MINYLIST[0]>MAXYLIST[-1]:
ANS=min(ANS,(MAXX-MINX+1)*(MAXY-MINY))
print(ANS)
``` | output | 1 | 77,613 | 15 | 155,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,614 | 15 | 155,228 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
def solve():
i = 0
j = 0
imax = imin = 0
jmax = jmin = 0
fjmin = ljmin = fjmax = ljmax = fimax = limax = fimin = limin = -1
for ind, e in enumerate(input()):
if e == 'W':
i += 1
if i > imax:
imax = i
fimax = ind
limax = ind
elif e == 'S':
i -= 1
if i < imin:
imin = i
fimin = ind
limin = ind
elif e == "A":
j -= 1
if j < jmin:
jmin = j
fjmin = ind
ljmin = ind
elif e == 'D':
j += 1
if j > jmax:
jmax = j
fjmax = ind
ljmax = ind
if j == jmin:
ljmin = ind
if j == jmax:
ljmax = ind
if i == imin:
limin = ind
if i == imax:
limax = ind
ans = 0
if fjmax > ljmin + 1 or fjmin > ljmax + 1:
ans = imax - imin + 1
if fimax > limin + 1 or fimin > limax + 1:
ans = max(ans, jmax - jmin + 1)
print((imax - imin + 1) * (jmax - jmin + 1) - ans)
for _ in range(int(input())):
solve()
``` | output | 1 | 77,614 | 15 | 155,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,615 | 15 | 155,230 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
# coding=utf-8
INF = 1e11
# move = {'W': (0, 0), 'A': (0, 0), 'S': (0, 0), 'D': (0, 0)}
move = {'W': (0, 1), 'A': (-1, 0), 'S': (0, -1), 'D': (1, 0)}
def getExtremes(positions):
minX, minY, maxX, maxY = [positions[0][0]], [positions[0][1]], [positions[0][0]], [positions[0][1]]
for p in positions[1:]:
minX.append(min(minX[-1], p[0]))
minY.append(min(minY[-1], p[1]))
maxX.append(max(maxX[-1], p[0]))
maxY.append(max(maxY[-1], p[1]))
return minX, minY, maxX, maxY
t = int(input())
while t > 0:
t -= 1
s = input()
x, y = 0, 0
positions = [(0, 0)]
for c in s:
x, y = x + move[c][0], y + move[c][1]
positions.append((x, y))
# print(positions)
# print()
minXBeg, minYBeg, maxXBeg, maxYBeg = getExtremes(positions)
# print(minXBeg, minYBeg, maxXBeg, maxYBeg, sep="\n")
# print()
positions.reverse()
minXEnd, minYEnd, maxXEnd, maxYEnd = getExtremes(positions)
minXEnd.reverse()
minYEnd.reverse()
maxXEnd.reverse()
maxYEnd.reverse()
# print(minXEnd, minYEnd, maxXEnd, maxYEnd, sep="\n")
# print()
positions.reverse()
ans = INF
for i in range(len(s)):
for c in move:
minX = min(minXBeg[i], positions[i][0] + move[c][0], minXEnd[i + 1] + move[c][0])
maxX = max(maxXBeg[i], positions[i][0] + move[c][0], maxXEnd[i + 1] + move[c][0])
minY = min(minYBeg[i], positions[i][1] + move[c][1], minYEnd[i + 1] + move[c][1])
maxY = max(maxYBeg[i], positions[i][1] + move[c][1], maxYEnd[i + 1] + move[c][1])
area = (maxX - minX + 1) * (maxY - minY + 1)
# print(i, c, minX, maxX, minY, maxY, area)
ans = min(ans, area)
print(ans)
``` | output | 1 | 77,615 | 15 | 155,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s). | instruction | 0 | 77,616 | 15 | 155,232 |
Tags: brute force, data structures, dp, greedy, implementation, math, strings
Correct Solution:
```
t= int(input())
for _ in range(0,t):
a= list(input())
nowx=0
nowy=0
maxx=0
minx=0
maxy=0
miny=0
tmaxx=0
tminx=0
tmaxy=0
tminy=0
highw=0
highs=0
widthd=0
widtha=0
for i in range (0,len(a)):
if a[i] == 'W':
nowy += 1
if nowy >= maxy:
maxy=nowy
tmaxy=i
elif a[i] == 'S':
nowy -= 1
if nowy <=miny:
miny=nowy
tminy=i
elif a[i] == 'D':
nowx += 1
if nowx >= maxx:
maxx=nowx
tmaxx=i
elif a[i] == 'A':
nowx -= 1
if nowx <=minx:
minx=nowx
tminx=i
highw= max(highw,nowy-miny)
highs= max(highs,maxy-nowy)
widthd=max(widthd,nowx-minx)
widtha=max(widtha,maxx-nowx)
y1= max(highw,highs)
y2= max(highw!=0 or highs!=0, y1- ((highw!=highs)))
x1= max(widthd,widtha)
x2= max(widthd!=0 or widtha!=0, x1-((widthd!=widtha)))
print(min((y1+1)*(x2+1),(1+y2)*(x1+1)))
``` | output | 1 | 77,616 | 15 | 155,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
def main():
hh, vv, r = [0], [0], []
f = {'W': (vv, -1), 'S': (vv, 1), 'A': (hh, -1), 'D': (hh, 1)}.get
for _ in range(int(input())):
del vv[1:], hh[1:], r[:]
for l, d in map(f, input()):
l.append(l[-1] + d)
for l in hh, vv:
mi, ma = min(l), max(l)
a, tmp = mi - 1, []
for b in filter((mi, ma).__contains__, l):
if a != b:
a = b
tmp.append(a)
ma -= mi - 1
r.append(ma)
if len(tmp) < 3 <= ma:
ma -= 1
r.append(ma)
print(min((r[0] * r[3], r[1] * r[2])))
if __name__ == '__main__':
main()
``` | instruction | 0 | 77,617 | 15 | 155,234 |
Yes | output | 1 | 77,617 | 15 | 155,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
t = int(input())
for _ in range(t):
s = input()
n = len(s)
fa, fd, fs, fw = [0], [0], [0], [0]
ba, bd, bs, bw = [0], [0], [0], [0]
cur = [0, 0]
for i in range(n):
if s[i] == "A":
cur[0] -= 1
elif s[i] == "D":
cur[0] += 1
elif s[i] == "S":
cur[1] -= 1
elif s[i] == "W":
cur[1] += 1
fa.append(min(fa[-1], cur[0]))
fd.append(max(fd[-1], cur[0]))
fs.append(min(fs[-1], cur[1]))
fw.append(max(fw[-1], cur[1]))
h = fd[-1]-fa[-1]
v = fw[-1]-fs[-1]
area = (h+1)*(v+1)
cur = [0, 0]
for i in range(n-1, -1, -1):
if s[i] == "D":
cur[0] -= 1
elif s[i] == "A":
cur[0] += 1
elif s[i] == "W":
cur[1] -= 1
elif s[i] == "S":
cur[1] += 1
ba.append(min(ba[-1], cur[0]))
bd.append(max(bd[-1], cur[0]))
bs.append(min(bs[-1], cur[1]))
bw.append(max(bw[-1], cur[1]))
ba.reverse()
bd.reverse()
bs.reverse()
bw.reverse()
#print(fa, fd, fs, fw)
#print(ba, bd, bs, bw)
hok, vok = False, False
for i in range(1, n):
#print(n, i)
if fd[i]-fa[i] < h and abs(bd[i]-ba[i]) < h:
hok = True
if fw[i]-fs[i] < v and abs(bw[i]-bs[i]) < v:
vok = True
if hok:
area = min(area, h*(v+1))
if vok:
area = min(area, v*(h+1))
print(area)
``` | instruction | 0 | 77,618 | 15 | 155,236 |
Yes | output | 1 | 77,618 | 15 | 155,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
n = int(input())
def area(width, height) :
return (width+1) * (height+1)
def calcul(s1, c, s2) :
maxx, maxy, minx, miny = 0, 0, 0, 0
x, y = 0, 0
for k in range(len(s1)) :
if s1[k] == "W" :
y += 1
if s1[k] == "S" :
y -= 1
if s1[k] == "A" :
x -= 1
if s1[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
if c == "W" :
y += 1
elif c == "S" :
y -= 1
elif c == "A" :
x -= 1
elif c == "D" :
x += 1
else :
print(c, "ok")
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
for k in range(len(s2)) :
if s2[k] == "W" :
y += 1
if s2[k] == "S" :
y -= 1
if s2[k] == "A" :
x -= 1
if s2[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = area(diffx, diffy)
return tmp
def pre_calcul(s, moment, pre_avant, date_debut) :
x, y, maxx, minx, maxy, miny = pre_avant
for k in range(date_debut, moment) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
return (x, y, maxx, minx, maxy, miny)
def calcul2(s, c, moment, precalcul) :
x, y, maxx, minx, maxy, miny = precalcul
if c == "W" :
y += 1
elif c == "S" :
y -= 1
elif c == "A" :
x -= 1
elif c == "D" :
x += 1
else :
print(c, "ok")
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
for k in range(moment, len(s)) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = area(diffx, diffy)
return tmp
for _ in range(n) :
s = input()
maxx, maxy, minx, miny = 0, 0, 0, 0
x, y = 0, 0
momentminx, momentmaxx, momentminy, momentmaxy = -1, -1, -1, -1
for k in range(len(s)) :
if s[k] == "W" :
y += 1
if s[k] == "S" :
y -= 1
if s[k] == "A" :
x -= 1
if s[k] == "D" :
x += 1
if x > maxx :
momentmaxx = k
if y > maxy :
momentmaxy = k
if x < minx :
momentminx = k
if y < miny :
momentminy = k
maxx = max(maxx, x)
minx = min(minx, x)
maxy = max(maxy, y)
miny = min(miny, y)
diffx = maxx - minx
diffy = maxy - miny
tmp = 999999999999999999999999999999999999
l = [momentmaxx, momentmaxy, momentminx, momentminy]
l = list(set(l))
l = [i for i in l if i != -1]
l.sort()
if l != [] :
precalcul = pre_calcul(s, l[0], (0, 0, 0, 0, 0, 0), 0)
avant = l[0]
for moment in l :
precalcul = pre_calcul(s, moment, precalcul, avant)
avant = moment
tmp = min(tmp, calcul2(s, 'W', moment, precalcul))
tmp = min(tmp, calcul2(s, 'S', moment, precalcul))
tmp = min(tmp, calcul2(s, 'A', moment, precalcul))
tmp = min(tmp, calcul2(s, 'D', moment, precalcul))
print(tmp)
``` | instruction | 0 | 77,619 | 15 | 155,238 |
Yes | output | 1 | 77,619 | 15 | 155,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
T = int(input())
w = [[-1, 0], [1, 0], [0, 1], [0, -1]]
mp = {'A':0, 'D':1, 'W':2, 'S':3}
while T > 0:
T-=1
s = input()
l = [0]; r = [0];
u = [0]; d = [0];
for dir in s[::-1]:
l.append(l[-1])
r.append(r[-1])
u.append(u[-1])
d.append(d[-1])
if dir == 'A':
l[-1]+=1
if r[-1] > 0: r[-1]-=1
elif dir == 'D':
r[-1]+=1
if l[-1] > 0: l[-1]-=1
elif dir == 'S':
d[-1]+=1
if u[-1] > 0: u[-1]-=1
else:
u[-1]+=1
if d[-1] > 0: d[-1]-=1
l = l[::-1]; r = r[::-1]; u = u[::-1]; d = d[::-1];
x = 0; y = 0
ml = 0; mr = 0; mu = 0; md = 0;
ans = (l[0] + r[0] + 1) * (u[0] + d[0] + 1)
for i in range(len(s)+1):
mml=ml;mmr=mr;mmu=mu;mmd=md;
for j in range(4):
xx=x+w[j][0]
yy=y+w[j][1]
if xx<0: ml=max(ml,-xx)
if xx>0: mr=max(mr,xx)
if yy>0: mu=max(mu,yy)
if yy<0: md=max(md,-yy)
xx-=l[i]
if xx<0: ml=max(ml,-xx)
xx+=r[i]+l[i];
if xx>0: mr=max(mr,xx)
yy-=d[i]
if yy<0: md=max(md,-yy)
yy+=u[i]+d[i]
if yy>0: mu=max(mu,yy)
ans = min(ans, (ml+mr+1)*(mu+md+1))
ml=mml;mr=mmr;mu=mmu;md=mmd;
if i < len(s):
x+=w[mp[s[i]]][0]
y+=w[mp[s[i]]][1]
if x<0: ml=max(ml,-x)
if x>0: mr=max(mr,x)
if y>0: mu=max(mu,y)
if y<0: md=max(md,-y)
print(ans)
``` | instruction | 0 | 77,620 | 15 | 155,240 |
Yes | output | 1 | 77,620 | 15 | 155,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
for i in range(n):
s1=input()
countws=1
countad=1
w=""
s=""
a=""
d=""
for i in range(len(s1)):
if(s1[i]=="W" and len(s)==0):
countws+=1
w=w+"W"
elif(s1[i]=="W" and len(s)!=0):
s=s[:-1]
if(s1[i]=="S" and len(w)==0):
countws+=1
s=s+"S"
elif(s1[i]=="S" and len(w)!=0):
w=w[:-1]
if(s1[i]=="A" and len(d)==0):
countad+=1
a=a+"A"
elif(s1[i]=="A" and len(d)!=0):
d=d[:-1]
if(s1[i]=="D" and len(a)==0):
countad+=1
d=d+"D"
elif(s1[i]=="D" and len(a)!=0):
a=a[:-1]
ans1=0
if(countad>2):
ans1=(countad-1)*countws
else:
ans1=(countad)*countws
ans2=0
if(countws>2):
ans2=(countws-1)*countad
else:
ans2=(countad)*countws
print(min(ans1,ans2))
``` | instruction | 0 | 77,621 | 15 | 155,242 |
No | output | 1 | 77,621 | 15 | 155,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
for _ in range(int(input())):
s = input()
bu = 0
br = 0
mibu = 0
mabu = 0
mibr = 0
mabr = 0
for i in s:
if i == 'W':
bu += 1
elif i == 'D':
bu -= 1
elif i == 'A':
br -= 1
else:
br += 1
mibu = min(mibu, bu)
mabu = max(mabu, bu)
mibr = min(mibr, br)
mabr = max(mabr, br)
m1 = mabu - mibu + 1
m2 = mabr - mibr + 1
cm1 = ((mibu <= -1 and mabu >= 1) or (mabu >= 2) or (mibu <= -2)) and bu
cm2 = ((mibr <= -1 and mabr >= 1) or (mabr >= 2) or (mibr <= -2)) and br
if cm1 and cm2:
print(m1 * m2 - max(m1, m2))
elif cm1:
print(m1 * m2 - m2)
elif cm2:
print(m2 * m2 - m1)
else:
print(m1 * m2)
``` | instruction | 0 | 77,622 | 15 | 155,244 |
No | output | 1 | 77,622 | 15 | 155,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
for q in range(int(input())):
data = input()
mx = [0,0,0,0]
x = 0
y = 0
pos = [[0],[0],[0],[0]]
for i in range(len(data)):
# print(x,y)
d = data[i]
if d == "W":
y += 1
if y >= mx[0]:
if y == mx[0]:
mx[0] = y
pos[0].append(i)
else:
mx[0] = y
pos[0] = [i]
elif d == "S":
y -= 1
if y <= mx[2]:
if y == mx[2]:
mx[2] = y
pos[2].append(i)
else:
mx[2] = y
pos[2] = [i]
elif d == "A":
x -= 1
if x <= mx[1]:
if x == mx[1]:
mx[1] = x
pos[1].append(i)
else:
mx[1] = x
pos[1] = [i]
else:
x += 1
if x >= mx[3]:
if x == mx[3]:
mx[3] = x
pos[3].append(i)
else:
mx[3] = x
pos[3] = [i]
# print(mx)
# print(pos)
wid = mx[3] - mx[1] + 1
hei = mx[0] - mx[2] + 1
ans = wid * hei
if pos[3][0] > pos[1][-1] + 1 or pos[1][0] > pos[3][-1] + 1:
ans -= hei
if wid > hei and pos[0][0] > pos[2][-1] + 1 or pos[2][0] > pos[0][-1] + 1:
ans = min((hei-1)*(wid), ans)
print(ans)
``` | instruction | 0 | 77,623 | 15 | 155,246 |
No | output | 1 | 77,623 | 15 | 155,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have a string s — a sequence of commands for your toy robot. The robot is placed in some cell of a rectangular grid. He can perform four commands:
* 'W' — move one cell up;
* 'S' — move one cell down;
* 'A' — move one cell left;
* 'D' — move one cell right.
Let Grid(s) be the grid of minimum possible area such that there is a position in the grid where you can place the robot in such a way that it will not fall from the grid while running the sequence of commands s. For example, if s = DSAWWAW then Grid(s) is the 4 × 3 grid:
1. you can place the robot in the cell (3, 2);
2. the robot performs the command 'D' and moves to (3, 3);
3. the robot performs the command 'S' and moves to (4, 3);
4. the robot performs the command 'A' and moves to (4, 2);
5. the robot performs the command 'W' and moves to (3, 2);
6. the robot performs the command 'W' and moves to (2, 2);
7. the robot performs the command 'A' and moves to (2, 1);
8. the robot performs the command 'W' and moves to (1, 1).
<image>
You have 4 extra letters: one 'W', one 'A', one 'S', one 'D'. You'd like to insert at most one of these letters in any position of sequence s to minimize the area of Grid(s).
What is the minimum area of Grid(s) you can achieve?
Input
The first line contains one integer T (1 ≤ T ≤ 1000) — the number of queries.
Next T lines contain queries: one per line. This line contains single string s (1 ≤ |s| ≤ 2 ⋅ 10^5, s_i ∈ \{W, A, S, D\}) — the sequence of commands.
It's guaranteed that the total length of s over all queries doesn't exceed 2 ⋅ 10^5.
Output
Print T integers: one per query. For each query print the minimum area of Grid(s) you can achieve.
Example
Input
3
DSAWWAW
D
WA
Output
8
2
4
Note
In the first query you have to get string DSAWW\underline{D}AW.
In second and third queries you can not decrease the area of Grid(s).
Submitted Solution:
```
def main():
import sys
input = sys.stdin.readline
for _ in range(int(input())):
S = input().rstrip('\n')
cnt = [0] * 4
xmin = xmax = ymax = ymin = 0
x = y = 0
for s in S:
if s == 'W':
y += 1
elif s == 'A':
x -= 1
elif s == 'S':
y -= 1
else:
x += 1
xmin = min(xmin, x)
xmax = max(xmax, x)
ymin = min(ymin, y)
ymax = max(ymax, y)
ans = (xmax - xmin + 1) * (ymax - ymin + 1)
if xmax - xmin > 1 and x != xmax:
ans = min(ans, (xmax - (xmin+1) + 1) * (ymax - ymin + 1))
if xmax - xmin > 1 and x != xmin:
ans = min(ans, ((xmax-1) - xmin + 1) * (ymax - ymin + 1))
if ymax - ymin > 1 and y != ymax:
ans = min(ans, (xmax - xmin + 1) * (ymax - (ymin+1) + 1))
if ymax - ymin > 1 and y != ymin:
ans = min(ans, (xmax - xmin + 1) * ((ymax-1) - ymin + 1))
print(ans)
if __name__ == '__main__':
main()
``` | instruction | 0 | 77,624 | 15 | 155,248 |
No | output | 1 | 77,624 | 15 | 155,249 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,836 | 15 | 155,672 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
import sys
n = int(input())
l = list(map(int,input().split()))
c = list(map(int,input().split()))
def gcd(a, b):
while b > 0:
a, b = b, a % b
return a
a = {0:0}
b = [0]
for i in range(n):
for p in b:
d = gcd(p, l[i])
cost = a[p] + c[i]
if d not in a:
a[d] = cost
b.append(d)
elif a[d] > cost: a[d] = cost
if 1 not in a: a[1] = -1
print(a[1])
``` | output | 1 | 77,836 | 15 | 155,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,837 | 15 | 155,674 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
def main():
input()
acc = {0: 0}
for p, c in zip(list(map(int, input().split())),
list(map(int, input().split()))):
adds = []
for b, u in acc.items():
a = p
while b:
a, b = b, a % b
adds.append((a, u + c))
for a, u in adds:
acc[a] = min(u, acc.get(a, 1000000000))
print(acc.get(1, -1))
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | output | 1 | 77,837 | 15 | 155,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,838 | 15 | 155,676 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
def gcd(x,y):
while x % y > 0:
x, y = y, x % y
return y
n = int(input())
a, b, c = [int(x) for x in input().split()], [int(x) for x in input().split()], [{} for i in range(n)]
def f(i,g):
if g == 1:
return 0
if i == n:
return 100000000000
if g in c[i]:
return c[i][g]
A = f(i+1,g)
A = min(A, f(i+1, gcd(g,a[i])) + b[i])
c[i][g] = A
return A
if f(0,0) < 100000000000:
print(f(0,0))
else:
print(-1)
``` | output | 1 | 77,838 | 15 | 155,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,839 | 15 | 155,678 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
import sys
n = int(input())
l = list(map(int,input().split()))
c = list(map(int,input().split()))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
a = {0:0}
for i in range(n):
b = a.copy()
for p in a.items():
d = gcd(p[0], l[i])
cost = p[1] + c[i]
if d not in b: b[d] = cost
elif b[d] > cost: b[d] = cost
a = b.copy()
if 1 not in a: a[1] = -1
print(a[1])
``` | output | 1 | 77,839 | 15 | 155,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,840 | 15 | 155,680 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush,heappop
import math
from collections import *
from functools import reduce,cmp_to_key,lru_cache
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
import sys
# input = sys.stdin.readline
M = mod = 10 ** 9 + 7
def factors(n):return sorted(set(reduce(list.__add__, ([i, n//i] for i in range(1, int(n**0.5) + 1) if n % i == 0))))
def inv_mod(n):return pow(n, mod - 2, mod)
def li():return [int(i) for i in input().rstrip().split()]
def st():return str(input().rstrip())[2:-1]
def val():return int(input().rstrip())
def li2():return [str(i)[2:-1] for i in input().rstrip().split()]
def li3():return [int(i) for i in st()]
n = val()
l = li()
c = li()
element = l[0]
for i in range(1, n):element = math.gcd(element, l[i])
if element != 1:
print(-1)
exit()
myset = {}
for ind, i in enumerate(l):
for j in list(myset):
temp = math.gcd(j, i)
if(temp not in myset):myset[temp] = myset[j] + c[ind]
else:myset[temp] = min(myset[temp], c[ind] + myset[j])
if i not in myset:myset[i] = c[ind]
else:myset[i] = min(myset[i], c[ind])
print(myset[1])
``` | output | 1 | 77,840 | 15 | 155,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,841 | 15 | 155,682 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
import sys
n = int(input())
l = list(map(int,input().split()))
c = list(map(int,input().split()))
def gcd(a, b):
if b == 0: return a
return gcd(b, a % b)
a = {0:0}
b = [0]
for i in range(n):
for p in b:
d = gcd(p, l[i])
cost = a[p] + c[i]
if d not in a:
a[d] = cost
b.append(d)
elif a[d] > cost: a[d] = cost
if 1 not in a: a[1] = -1
print(a[1])
``` | output | 1 | 77,841 | 15 | 155,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,842 | 15 | 155,684 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
from collections import defaultdict
from math import gcd
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
dp = defaultdict(lambda: float("inf"))
for a, b in zip(A, B):
dp[a] = min(dp[a], b)
for d in dp.copy():
cur = gcd(a, d)
dp[cur] = min(dp[cur], dp[a] + dp[d])
if 1 not in dp:
print(-1)
else:
print(dp[1])
``` | output | 1 | 77,842 | 15 | 155,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1. | instruction | 0 | 77,843 | 15 | 155,686 |
Tags: bitmasks, brute force, dp, math
Correct Solution:
```
import fractions
def dfs(s, g) :
global cache, N, L, C
if g == 1 : return 0
if s == N : return float("INF")
if g in cache[s] :
return cache[s][g]
cache[s][g] = min(dfs(s+1, g),dfs(s+1, gcd(g, L[s]))+C[s])
return cache[s][g]
gcd = fractions.gcd
N = int(input())
L = list(map(int, input().split(' ')))
C = list(map(int, input().split(' ')))
cache = [dict() for i in range(N)]
ans = dfs(0, 0)
if ans == float("INF") :
print(-1)
else :
print(ans)
``` | output | 1 | 77,843 | 15 | 155,687 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.