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 |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,899 | 15 | 159,798 |
"Correct Solution:
```
S = input()
cur = 'A'
ans = 0
for i in range(len(S)):
if(S[i] == cur):
ans += 1
else:
if(cur > S[i]):
ans += 1
cur = S[i]
print(ans)
``` | output | 1 | 79,899 | 15 | 159,799 |
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,900 | 15 | 159,800 |
"Correct Solution:
```
# AOJ 2838: A-Z-
# Python3 2018.7.12 bal4u
S = input()
ans = p = 0
for s in S:
k = ord(s)-ord('A')
if k <= p: ans += 1
p = k
print(ans)
``` | output | 1 | 79,900 | 15 | 159,801 |
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,901 | 15 | 159,802 |
"Correct Solution:
```
S = input()
cnt, x = 0, 65
for c in S:
cnt = cnt + (x >= ord(c))
x = ord(c)
print(cnt)
``` | output | 1 | 79,901 | 15 | 159,803 |
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,902 | 15 | 159,804 |
"Correct Solution:
```
now=0
ans=0
for i in input():
j=ord(i)-ord("A")
if now>=j:ans+=1
now=j
print(ans)
``` | output | 1 | 79,902 | 15 | 159,805 |
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,903 | 15 | 159,806 |
"Correct Solution:
```
s = input()
print((s[0]=='A')+sum(s[i] >= s[i+1] for i in range(len(s)-1)))
``` | output | 1 | 79,903 | 15 | 159,807 |
Provide a correct Python 3 solution for this coding contest problem.
A: A-Z-
problem
There is a circular board of 26 squares, each square with one capital letter of the alphabet written clockwise in alphabetical order. That is, the clockwise side of the'A'square is the'B' square, the next side of the'B'square is the'C'square, and ..., the clockwise side of the'Z'square is the'A'. It's a square.
<image>
Also, the board has one piece in the'A'square.
You receive the string S and manipulate the pieces by looking at each character from the beginning of S. The i-th operation is as follows.
* At that point, move the pieces clockwise one by one, aiming at the square of the letter i of the letter S from the square with the piece. At this time, at least one square is assumed to move. So, for example, when moving from an'A'square to an'A' square, you have to go around the board once.
As a result of the above operation, please answer how many times the piece stepped on the'A'square. "Stepping on the'A'square" means advancing the piece from the'Z'square to the'A' square.
Input format
Input is given on one line.
S
S represents the string you receive.
Constraint
* 1 \ leq | S | \ leq 100
* S consists of uppercase letters only.
Output format
Output in one line how many times you stepped on the'A'square.
Input example 1
AIZU
Output example 1
2
* A-> A (once here)
* A-> I (once so far)
* I-> Z (once so far)
* Z-> U (twice so far)
Input example 2
HOKKAIDO
Output example 2
Four
Example
Input
AIZU
Output
2 | instruction | 0 | 79,904 | 15 | 159,808 |
"Correct Solution:
```
S = input()
alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
Now = 0
ans = 0
for s in S:
Next = alpha.find(s)
# print(s, Now, Next)
if(Now < Next):
pass
else:
ans += 1
Now = Next
print(ans)
``` | output | 1 | 79,904 | 15 | 159,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,336 | 15 | 160,672 |
Tags: dp
Correct Solution:
```
from sys import stdin, stdout
mvalue = 1000
n, m, fold = map(int, stdin.readline().split())
fold += 1
dp = [[[False for k in range(mvalue)] for j in range(m + 1)] for i in range(n + 1)]
values = []
for i in range(n):
values.append(list(map(int, list(stdin.readline().strip()))))
for j in range(m):
dp[n - 1][j][values[n - 1][j]] = True
for i in range(n - 2, -1, -1):
for j in range(m):
for k in range(mvalue):
dp[i][j][k] = max(dp[i][j][k], max(dp[i + 1][j + 1][k - values[i][j]], dp[i + 1][j - 1][k - values[i][j]]))
ans = -1
x, y = 0, 0
for j in range(m):
for k in range(mvalue):
if dp[0][j][k] and not k % fold and k > ans:
ans = k
x = j
steps = []
stdout.write(str(ans) + '\n')
if ans != -1:
while y != n - 1:
if dp[y + 1][x - 1][ans - values[y][x]]:
steps.append('R')
ans -= values[y][x]
y += 1
x -= 1
else:
steps.append('L')
ans -= values[y][x]
y += 1
x += 1
stdout.write(str(x + 1) + '\n' + ''.join(steps[::-1]))
``` | output | 1 | 80,336 | 15 | 160,673 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,337 | 15 | 160,674 |
Tags: dp
Correct Solution:
```
n, m, k = map(int, input().split())
board = [[0] * m for i in range(n)]
for i in range(n):
s = input().rstrip()
for j in range(m):
board[i][j] = int(s[j])
board.reverse()
dp = [[[-10 ** 9] * (k + 1) for i in range(m)] for j in range(n)]
prev = [[[(0, 0)] * (k + 1) for i in range(m)] for j in range(n)]
for i in range(m):
dp[0][i][board[0][i] % (k + 1)] = board[0][i]
for i in range(n - 1):
for j in range(m):
for l in range(k + 1):
a, b = i + 1, j - 1
c, d = i + 1, j + 1
for x in ((a, b), (c, d)):
x1, y1 = x[0], x[1]
if 0 <= x1 < n and 0 <= y1 < m:
new_val = dp[i][j][l] + board[x1][y1]
if dp[x1][y1][new_val % (k + 1)] < new_val:
dp[x1][y1][new_val % (k + 1)] = new_val
prev[x1][y1][new_val % (k + 1)] = (i, j)
ans = -1
end = (0, 0)
for i in range(m):
if ans < dp[n - 1][i][0]:
ans = dp[n - 1][i][0]
end = (n - 1, i)
print(ans)
if ans == -1:
exit()
cur = end
res = []
while cur[0] != 0:
if prev[cur[0]][cur[1]][ans % (k + 1)][1] == cur[1] - 1:
res.append("R")
else:
res.append("L")
ans, cur = ans - board[cur[0]][cur[1]], prev[cur[0]][cur[1]][ans % (k + 1)]
res.reverse()
print(cur[1] + 1)
print("".join(res))
``` | output | 1 | 80,337 | 15 | 160,675 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,338 | 15 | 160,676 |
Tags: dp
Correct Solution:
```
n, m, k = map(int, input().split())
board = [[0] * m for i in range(n)]
for i in range(n):
s = input().rstrip()
for j in range(m):
board[i][j] = int(s[j])
board.reverse()
dp = [[[-10 ** 9] * (k + 1) for i in range(m)] for j in range(n)]
prev = [[[(0, 0)] * (k + 1) for i in range(m)] for j in range(n)]
for i in range(m):
dp[0][i][board[0][i] % (k + 1)] = board[0][i]
for i in range(n - 1):
for j in range(m):
for l in range(k + 1):
a, b = i + 1, j - 1
c, d = i + 1, j + 1
for x in ((a, b), (c, d)):
x1, y1 = x[0], x[1]
if 0 <= x1 < n and 0 <= y1 < m:
new_val = dp[i][j][l] + board[x1][y1]
if dp[x1][y1][new_val % (k + 1)] < new_val:
dp[x1][y1][new_val % (k + 1)] = new_val
prev[x1][y1][new_val % (k + 1)] = (i, j)
ans = -1
end = (0, 0)
for i in range(m):
if ans < dp[n - 1][i][0]:
ans = dp[n - 1][i][0]
end = (n - 1, i)
print(ans)
if ans == -1:
exit()
cur = end
res = []
while cur[0] != 0:
if prev[cur[0]][cur[1]][ans % (k + 1)][1] == cur[1] - 1:
res.append("R")
else:
res.append("L")
ans, cur = ans - board[cur[0]][cur[1]], prev[cur[0]][cur[1]][ans % (k + 1)]
res.reverse()
print(cur[1] + 1)
print("".join(res))
# Made By Mostafa_Khaled
``` | output | 1 | 80,338 | 15 | 160,677 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,339 | 15 | 160,678 |
Tags: dp
Correct Solution:
```
a,b,k = map(int, input().split())
k += 1
m = [[ord(c)-48 for c in input()] for i in range(a)][-1::-1]
dp = [[[-1 for t in range(k)] for j in range(b)] for i in range(a)]
pr = [[[0 for t in range(k)] for j in range(b)] for i in range(a)]
for i in range(a):
for j in range(b):
if i==0:
dp[i][j][m[i][j]%k] = m[i][j]
continue
for c in range(k):
l = dp[i-1][j-1][(c-m[i][j])%k]+m[i][j] if j and dp[i-1][j-1][(c-m[i][j])%k]>-1 else -1
r = dp[i-1][j+1][(c-m[i][j])%k]+m[i][j] if j+1<b and dp[i-1][j+1][(c-m[i][j])%k]>-1 else -1
dp[i][j][c] = max(l,r)
pr[i][j][c] = -1 if l>r else 1
mx = -1
ep = -1
for j in range(b):
if dp[a-1][j][0]<=mx: continue
mx = dp[a-1][j][0]
ep = j
if mx==-1:
print(-1)
exit(0)
print(mx)
path = ""
x, y = a-1, ep
while 1:
if x==0: break
path += "R" if pr[x][y][mx%k]==-1 else 'L'
c = mx
mx -= m[x][y]
y += -1 if pr[x][y][c%k]==-1 else 1
x -= 1
print(y+1)
print(path[-1::-1])
``` | output | 1 | 80,339 | 15 | 160,679 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,340 | 15 | 160,680 |
Tags: dp
Correct Solution:
```
def restore_path(i, j):
vi, vj, vmod = i, j, 0
ans = []
while prev[vi][vj][vmod] is not None:
if prev[vi][vj][vmod][1] == vj - 1:
ans.append('L')
else:
ans.append('R')
vi, vj, vmod = prev[vi][vj][vmod]
return ''.join(ans)
n, m, k = [int(i) for i in input().split()]
k += 1
a = [[int(i) for i in input()] for i in range(n)]
d = [[[float('-inf')] * k for i in range(m)] for i in range(n)]
prev = [[[None] * k for i in range(m)] for i in range(n)]
for i in range(m):
d[0][i][a[0][i] % k] = a[0][i]
for i in range(1, n):
for j in range(m):
for mod in range(k):
if j > 0 and d[i - 1][j - 1][(mod + 10 * k - a[i][j]) % k] + a[i][j] > d[i][j][mod]:
d[i][j][mod] = d[i - 1][j - 1][(mod + 10 * k - a[i][j]) % k] + a[i][j]
prev[i][j][mod] = (i - 1, j - 1, (mod + 10 * k - a[i][j]) % k)
if j < m - 1 and d[i - 1][j + 1][(mod + 10 * k - a[i][j]) % k] + a[i][j] > d[i][j][mod]:
d[i][j][mod] = d[i - 1][j + 1][(mod + 10 * k - a[i][j]) % k] + a[i][j]
prev[i][j][mod] = (i - 1, j + 1, (mod + 10 * k - a[i][j]) % k)
maxx = max(d[n - 1], key=lambda x: x[0])
if maxx[0] == float('-inf'):
print(-1)
else:
print(maxx[0])
print(d[n - 1].index(maxx) + 1)
print(restore_path(n - 1, d[n - 1].index(maxx)))
``` | output | 1 | 80,340 | 15 | 160,681 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,341 | 15 | 160,682 |
Tags: dp
Correct Solution:
```
if __name__ == '__main__':
n, m, k = map(int, input().split())
chessboard = tuple(tuple(map(int, input())) for _ in range(n))
costs = [m * [0] for _ in range(n)]
for i in range(m):
costs[0][i] = {i: (-1, "") for i in range(k + 1)}
costs[0][i][chessboard[0][i] % (k + 1)] = (chessboard[0][i], "")
for i in range(1, n):
for j in range(m):
costs[i][j] = {i: (-1, "") for i in range(k + 1)}
for mod in range(k + 1):
next_mod = (chessboard[i][j] + mod) % (k + 1)
next = (-1, "")
if j + 1 < m \
and costs[i - 1][j + 1][mod][0] >= 0 \
and (j == 0 or costs[i - 1][j + 1][mod] > costs[i - 1][j - 1][mod]):
next = costs[i - 1][j + 1][mod]
next = (next[0] + chessboard[i][j], "R" + next[1])
elif j - 1 >= 0 and costs[i - 1][j - 1][mod][0] >= 0:
next = costs[i - 1][j - 1][mod]
next = (next[0] + chessboard[i][j], "L" + next[1])
costs[i][j][next_mod] = max(costs[i][j][next_mod], next)
# print(max(costs[m - 1][i][0][0] for i in range(n)))
i_max = max(range(m), key=lambda i: costs[n - 1][i][0][0])
print(costs[n - 1][i_max][0][0])
if costs[n - 1][i_max][0][0] >= 0:
print(i_max + 1)
print(costs[n - 1][i_max][0][1])
``` | output | 1 | 80,341 | 15 | 160,683 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,342 | 15 | 160,684 |
Tags: dp
Correct Solution:
```
#Récupération des données
n_m_k = input();
n, m, k = [int(s) for s in n_m_k.split()];
k+=1;
##if n<=1 or m<=1 or k <1:
## print(-1)
## exit()
plateau = [[0]*m for _ in range(n)];
for i in range(n):
new_line = input();
plateau[i] = [int(new_line[j]) for j in range(m)];
#On traite par pd
optimaux = [[[(-1, "")]*k for i in range(m)] for j in range(n)];
for j in range(m):
peas = plateau[0][j]
optimaux[0][j][peas%k] = peas, ""
for i in range(1, n):
for j in range(m):
add_peas = plateau[i][j];
#A gauche
if j:
prec = optimaux[i-1][j-1];
for peas, path in prec:
if peas != -1:
optimaux[i][j][(peas+add_peas) % k] = peas+add_peas, "L"+path
#A droite
if j != m-1:
prec = optimaux[i-1][j+1];
for peas, path in prec:
if peas != -1:
prec = optimaux[i][j][(peas+add_peas) % k][0]
new = peas+add_peas
if prec < new:
optimaux[i][j][new % k] = new, "R"+path
#On récupère l'optimal
best = -1;
path = "";
depart = -1
for j in range(m):
new, path2 = optimaux[-1][j][0];
if new > best:
best = new;
depart = j+1
path = path2;
if best == -1:
print(-1)
else:
print(best)
print(depart)
print(path)
``` | output | 1 | 80,342 | 15 | 160,685 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1 | instruction | 0 | 80,343 | 15 | 160,686 |
Tags: dp
Correct Solution:
```
from sys import stdin, stdout
mvalue = 1000
n, m, fold = map(int, stdin.readline().split())
fold += 1
dp = [[[False for k in range(mvalue)] for j in range(m + 1)] for i in range(n + 1)]
values = []
for i in range(n):
values.append(list(map(int, list(stdin.readline().strip()))))
for j in range(m):
dp[n - 1][j][values[n - 1][j]] = True
for i in range(n - 2, -1, -1):
for j in range(m):
for k in range(mvalue):
dp[i][j][k] = max(dp[i + 1][j + 1][k - values[i][j]], dp[i + 1][j - 1][k - values[i][j]])
ans = -1
x, y = 0, 0
for j in range(m):
for k in range(mvalue):
if dp[0][j][k] and not k % fold and k > ans:
ans = k
x = j
steps = []
stdout.write(str(ans) + '\n')
if ans != -1:
while y != n - 1:
if dp[y + 1][x - 1][ans - values[y][x]]:
steps.append('R')
ans -= values[y][x]
y += 1
x -= 1
else:
steps.append('L')
ans -= values[y][x]
y += 1
x += 1
stdout.write(str(x + 1) + '\n' + ''.join(steps[::-1]))
``` | output | 1 | 80,343 | 15 | 160,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1
Submitted Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n, m, k = map(int, input().split())
k += 1
a = [tuple(map(int, input().rstrip())) for _ in range(n)]
empty = -1
dp = [[[empty] * k for _ in range(m)] for _ in range(n)]
prev = [[[(-1, -1, '*')] * k for _ in range(m)] for _ in range(n)]
for i in range(m):
dp[-1][i][a[-1][i] % k] = a[-1][i]
for i in range(n - 1, 0, -1):
for j in range(m):
for mod in range(k):
if dp[i][j][mod] == empty:
continue
val = dp[i][j][mod]
for tj in (j - 1, j + 1):
if 0 <= tj < m and dp[i - 1][tj][(mod + a[i - 1][tj]) % k] < val + a[i - 1][tj]:
dp[i - 1][tj][(mod + a[i - 1][tj]) % k] = val + a[i - 1][tj]
prev[i - 1][tj][(mod + a[i - 1][tj]) % k] = (j, mod, 'L' if tj < j else 'R')
ans, p_j, p_mod, path = empty, 0, 0, ''
for j in range(m):
if ans < dp[0][j][0]:
ans = dp[0][j][0]
p_j, p_mod, path = prev[0][j][0]
if ans == empty:
print('-1')
exit()
for i in range(1, n - 1):
path += prev[i][p_j][p_mod][2]
p_j, p_mod = prev[i][p_j][p_mod][:2]
print(ans)
print(p_j + 1)
print(path[::-1])
``` | instruction | 0 | 80,344 | 15 | 160,688 |
Yes | output | 1 | 80,344 | 15 | 160,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1
Submitted Solution:
```
#Récupération des données
n_m_k = input();
n, m, k = [int(s) for s in n_m_k.split()];
k+=1;
if n<=1 or m<=1 or k <1 or m!=n:
print(-1)
exit()
plateau = [[0]*m for _ in range(n)];
for i in range(n):
new_line = input();
plateau[i] = [int(new_line[j]) for j in range(m)];
#On traite par pd
optimaux = [[[(-1, "")]*k for i in range(m)] for j in range(n)];
for j in range(m):
peas = plateau[0][j]
optimaux[0][j][peas%k] = peas, ""
for i in range(1, n):
for j in range(m):
add_peas = plateau[i][j];
#A gauche
if j:
prec = optimaux[i-1][j-1];
for peas, path in prec:
if peas != -1:
optimaux[i][j][(peas+add_peas) % k] = peas+add_peas, path + "R"
#A droite
if j != n-1:
prec = optimaux[i-1][j+1];
for peas, path in prec:
if peas != -1:
prec = optimaux[i][j][(peas+add_peas) % k][0]
new = peas+add_peas
if prec < new:
optimaux[i][j][new % k] = new, path + "L"
#On récupère l'optimal
best = -1;
path = "";
depart = -1
for j in range(m):
new, path2 = optimaux[-1][j][0];
if new > best:
best = new;
depart = j+1
path = path2;
if best == -1:
print(-1)
else:
print(best)
print(depart)
print(path)
``` | instruction | 0 | 80,345 | 15 | 160,690 |
No | output | 1 | 80,345 | 15 | 160,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1
Submitted Solution:
```
S=str(input())
l=S.split(" ")
n,m,k=int(l[0]),int(l[1]),int(l[2])
L=[]
M=[]
for j in range(n):
M=[int(i) for i in list(input())]
L+=[M]
s=-1
r=-1
P=''
T=[[j+1,M[j],''] for j in range(m)]
for i in T:
t=len(i)
if t-2==n:
if i[-2]%(k+1)==0 and i[-2]>r:
s=i[0]
r=i[-2]
P=i[-1]
else:
if i[-3]>1 and i[-3]<m:
T+=[i[:-2]+[i[-3]+1]+[i[-2]+L[1-t][i[-3]-1]]+[i[-1]+'R']]
T+=[i[:-2]+[i[-3]-1]+[i[-2]+L[1-t][i[-3]-1]]+[i[-1]+'L']]
elif i[-3]==1:
T+=[i[:-2]+[i[-3]+1]+[i[-2]+L[1-t][i[-3]-1]]+[i[-1]+'R']]
elif i[-3]==m:
T+=[i[:-2]+[i[-3]-1]+[i[-2]+L[1-t][i[-3]-1]]+[i[-1]+'L']]
print(r)
if r!=-1:
print(s)
print(P)
``` | instruction | 0 | 80,346 | 15 | 160,692 |
No | output | 1 | 80,346 | 15 | 160,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1
Submitted Solution:
```
#! /usr/bin/python3
# http://codeforces.com/problemset/problem/41/D
import string
def solve():
n, m, k = map(int, input().strip().split())
a = []
step = []
s = []
for i in range(0, n):
r = input().strip()
p = []
for j in range(0, m):
p.append(r[j])
q = [-1] * 102
a.append(q)
q = [0] * 105
step.append(q)
s.append(p)
t = n - 1
div = (k + 1)
for j in range(0, m):
v = int(s[t][j])
# print('t = ', t, ' j = ', j, ' value = ', s[t][j], ' v = ', v)
if (v % div == 0):
a[t][j] = v // div
t = n - 2
while (t >= 0):
p = t + 1
for j in range(0, m):
r = 0
v = int(s[t][j])
if v % div != 0:
continue;
a[t][j] = (v // div)
r = 0
print('t = ', t, ' j = ', j, ' value = ', a[t][j])
q = j - 1
if (j > 0) and (a[p][q] > r):
# print('1 = ', a[p][q])
r = a[p][q]
step[t][j] = 1
q = j + 1
if (j < m - 1) and (a[p][q] > r):
# print('2 = ', a[p][q])
r = a[p][q]
step[t][j] = 2
print('old value = ', a[t][j], ' new value = ', r + a[t][j], ' prev = ', r)
a[t][j] = a[t][j] + r
#print(' new value = ', a[t][j])
t = t - 1
t = -1
j = -1
for i in range(0, m):
if a[0][i] > t:
t = a[0][i]
j = i
if t != -1:
print(t * div)
else:
print(-1)
i = 0
result = []
if (t != -1):
while i < n - 1:
if (step[i][j] == 1):
result.append('R')
j = j - 1
else:
result.append('L')
j = j + 1
i = i + 1
print(j + 1)
i = n - 2
while i >= 0:
print(result[i], end='')
i = i - 1
print()
solve()
``` | instruction | 0 | 80,347 | 15 | 160,694 |
No | output | 1 | 80,347 | 15 | 160,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
On some square in the lowest row of a chessboard a stands a pawn. It has only two variants of moving: upwards and leftwards or upwards and rightwards. The pawn can choose from which square of the lowest row it can start its journey. On each square lay from 0 to 9 peas. The pawn wants to reach the uppermost row having collected as many peas as possible. As there it will have to divide the peas between itself and its k brothers, the number of peas must be divisible by k + 1. Find the maximal number of peas it will be able to collect and which moves it should make to do it.
The pawn cannot throw peas away or leave the board. When a pawn appears in some square of the board (including the first and last square of the way), it necessarily takes all the peas.
Input
The first line contains three integers n, m, k (2 ≤ n, m ≤ 100, 0 ≤ k ≤ 10) — the number of rows and columns on the chessboard, the number of the pawn's brothers. Then follow n lines containing each m numbers from 0 to 9 without spaces — the chessboard's description. Each square is described by one number — the number of peas in it. The first line corresponds to the uppermost row and the last line — to the lowest row.
Output
If it is impossible to reach the highest row having collected the number of peas divisible by k + 1, print -1.
Otherwise, the first line must contain a single number — the maximal number of peas the pawn can collect given that the number must be divisible by k + 1. The second line must contain a single number — the number of the square's column in the lowest row, from which the pawn must start its journey. The columns are numbered from the left to the right with integral numbers starting from 1. The third line must contain a line consisting of n - 1 symbols — the description of the pawn's moves. If the pawn must move upwards and leftwards, print L, if it must move upwards and rightwards, print R. If there are several solutions to that problem, print any of them.
Examples
Input
3 3 1
123
456
789
Output
16
2
RL
Input
3 3 0
123
456
789
Output
17
3
LR
Input
2 2 10
98
75
Output
-1
Submitted Solution:
```
#Récupération des données
n_m_k = input();
n, m, k = [int(s) for s in n_m_k.split()];
k+=1;
if n<=1 or m<=1 or k <1:
print(-1)
exit()
plateau = [[0]*m for _ in range(n)];
for i in range(n):
new_line = input();
plateau[i] = [int(new_line[j]) for j in range(m)];
#On traite par pd
optimaux = [[[(-1, "")]*k for i in range(m)] for j in range(n)];
for j in range(m):
peas = plateau[0][j]
optimaux[0][j][peas%k] = peas, ""
for i in range(1, n):
for j in range(m):
add_peas = plateau[i][j];
#A gauche
if j:
prec = optimaux[i-1][j-1];
for peas, path in prec:
if peas != -1:
optimaux[i][j][(peas+add_peas) % k] = peas+add_peas, path + "R"
#A droite
if j != m-1:
prec = optimaux[i-1][j+1];
for peas, path in prec:
if peas != -1:
prec = optimaux[i][j][(peas+add_peas) % k][0]
new = peas+add_peas
if prec < new:
optimaux[i][j][new % k] = new, path + "L"
#On récupère l'optimal
best = -1;
path = "";
depart = -1
for j in range(m):
new, path2 = optimaux[-1][j][0];
if new > best:
best = new;
depart = j+1
path = path2;
if best == -1:
print(-1)
else:
print(best)
print(depart)
print(path)
``` | instruction | 0 | 80,348 | 15 | 160,696 |
No | output | 1 | 80,348 | 15 | 160,697 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given positions (X_i, Y_i) of N enemy rooks on an infinite chessboard. No two rooks attack each other (at most one rook per row or column).
You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.
You can't enter a cell that is being attacked by a rook. Additionally, you can't move diagonally to an empty cell (but you can beat a rook diagonally).
(So this king moves like a superpawn that beats diagonally in 4 directions and moves horizontally/vertically in 4 directions.)
For each rook, consider replacing it with a king, and find the minimum possible number of moves needed to beat the maximum possible number of rooks.
Constraints
* 2 \leq N \leq 200\,000
* 1 \leq X_i, Y_i \leq 10^6
* X_i \neq X_j
* Y_i \neq Y_j
* All values in input are integers.
Input
Input is given from Standard Input in the following format.
N
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print N lines. The i-th line is for scenario of replacing the rook at (X_i, Y_i) with your king. This line should contain one integer: the minimum number of moves to beat M_i rooks where M_i denotes the maximum possible number of beaten rooks in this scenario (in infinite time).
Examples
Input
6
1 8
6 10
2 7
4 4
9 3
5 1
Output
5
0
7
5
0
0
Input
5
5 5
100 100
70 20
81 70
800 1
Output
985
985
1065
1034
0
Input
10
2 5
4 4
13 12
12 13
14 17
17 19
22 22
16 18
19 27
25 26
Output
2
2
9
9
3
3
24
5
0
25
Submitted Solution:
```
print("わかりましぇん")
``` | instruction | 0 | 80,602 | 15 | 161,204 |
No | output | 1 | 80,602 | 15 | 161,205 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given positions (X_i, Y_i) of N enemy rooks on an infinite chessboard. No two rooks attack each other (at most one rook per row or column).
You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.
You can't enter a cell that is being attacked by a rook. Additionally, you can't move diagonally to an empty cell (but you can beat a rook diagonally).
(So this king moves like a superpawn that beats diagonally in 4 directions and moves horizontally/vertically in 4 directions.)
For each rook, consider replacing it with a king, and find the minimum possible number of moves needed to beat the maximum possible number of rooks.
Constraints
* 2 \leq N \leq 200\,000
* 1 \leq X_i, Y_i \leq 10^6
* X_i \neq X_j
* Y_i \neq Y_j
* All values in input are integers.
Input
Input is given from Standard Input in the following format.
N
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print N lines. The i-th line is for scenario of replacing the rook at (X_i, Y_i) with your king. This line should contain one integer: the minimum number of moves to beat M_i rooks where M_i denotes the maximum possible number of beaten rooks in this scenario (in infinite time).
Examples
Input
6
1 8
6 10
2 7
4 4
9 3
5 1
Output
5
0
7
5
0
0
Input
5
5 5
100 100
70 20
81 70
800 1
Output
985
985
1065
1034
0
Input
10
2 5
4 4
13 12
12 13
14 17
17 19
22 22
16 18
19 27
25 26
Output
2
2
9
9
3
3
24
5
0
25
Submitted Solution:
```
#
``` | instruction | 0 | 80,603 | 15 | 161,206 |
No | output | 1 | 80,603 | 15 | 161,207 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given positions (X_i, Y_i) of N enemy rooks on an infinite chessboard. No two rooks attack each other (at most one rook per row or column).
You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.
You can't enter a cell that is being attacked by a rook. Additionally, you can't move diagonally to an empty cell (but you can beat a rook diagonally).
(So this king moves like a superpawn that beats diagonally in 4 directions and moves horizontally/vertically in 4 directions.)
For each rook, consider replacing it with a king, and find the minimum possible number of moves needed to beat the maximum possible number of rooks.
Constraints
* 2 \leq N \leq 200\,000
* 1 \leq X_i, Y_i \leq 10^6
* X_i \neq X_j
* Y_i \neq Y_j
* All values in input are integers.
Input
Input is given from Standard Input in the following format.
N
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print N lines. The i-th line is for scenario of replacing the rook at (X_i, Y_i) with your king. This line should contain one integer: the minimum number of moves to beat M_i rooks where M_i denotes the maximum possible number of beaten rooks in this scenario (in infinite time).
Examples
Input
6
1 8
6 10
2 7
4 4
9 3
5 1
Output
5
0
7
5
0
0
Input
5
5 5
100 100
70 20
81 70
800 1
Output
985
985
1065
1034
0
Input
10
2 5
4 4
13 12
12 13
14 17
17 19
22 22
16 18
19 27
25 26
Output
2
2
9
9
3
3
24
5
0
25
Submitted Solution:
```
# -*- coding: utf-8 -*-
# 整数の入力
a = int(input())
# スペース区切りの整数の入力
r_x = []
r_y _ []
for i in range(a):
x, y = map(int, input().split())
r_x.append(x)
r_y.append(y)
def detect(x, y):
min_x = -10000000
max_x = 10000000
min_y = -10000000
max_y = 10000000
for x_ in r_x:
x__= x_ - x
if x__ > 0 and x__ < max_x:
max_x = x__
elif x__ < 0 and x__ > min_x:
min_x = x__
for y_ in r_y:
y__= y_ - y
if y__ > 0 and y__ < max_y:
max_y = y__
elif y__ < 0 and y__ > min_y:
min_y = y__
return min_x, min_y, max_x, max_y
for x, y in zip(r_x, r_y):
min_x, min_y, max_x, max_y = detect(x, y)
# 出力
print("{} {}".format(a+b+c, s))
``` | instruction | 0 | 80,604 | 15 | 161,208 |
No | output | 1 | 80,604 | 15 | 161,209 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given positions (X_i, Y_i) of N enemy rooks on an infinite chessboard. No two rooks attack each other (at most one rook per row or column).
You're going to replace one rook with a king and then move the king repeatedly to beat as many rooks as possible.
You can't enter a cell that is being attacked by a rook. Additionally, you can't move diagonally to an empty cell (but you can beat a rook diagonally).
(So this king moves like a superpawn that beats diagonally in 4 directions and moves horizontally/vertically in 4 directions.)
For each rook, consider replacing it with a king, and find the minimum possible number of moves needed to beat the maximum possible number of rooks.
Constraints
* 2 \leq N \leq 200\,000
* 1 \leq X_i, Y_i \leq 10^6
* X_i \neq X_j
* Y_i \neq Y_j
* All values in input are integers.
Input
Input is given from Standard Input in the following format.
N
X_1 Y_1
X_2 Y_2
\vdots
X_N Y_N
Output
Print N lines. The i-th line is for scenario of replacing the rook at (X_i, Y_i) with your king. This line should contain one integer: the minimum number of moves to beat M_i rooks where M_i denotes the maximum possible number of beaten rooks in this scenario (in infinite time).
Examples
Input
6
1 8
6 10
2 7
4 4
9 3
5 1
Output
5
0
7
5
0
0
Input
5
5 5
100 100
70 20
81 70
800 1
Output
985
985
1065
1034
0
Input
10
2 5
4 4
13 12
12 13
14 17
17 19
22 22
16 18
19 27
25 26
Output
2
2
9
9
3
3
24
5
0
25
Submitted Solution:
```
import os
import sys
import numpy as np
def solve(inp):
n = inp[0]
xxx = inp[1::2]
yyy = inp[2::2]
xxx_idx = np.argsort(xxx)
yyy_idx = np.argsort(yyy)
# print('xxx_idx', xxx_idx)
# print('yyy_idx', yyy_idx)
xxx_num = np.argsort(xxx_idx)
yyy_num = np.argsort(yyy_idx)
# print('xxx_num', xxx_num)
# print('yyy_num', yyy_num)
# i: 入力順のルークの番号
# xi: x座標昇順にソートしたときの順番
# xxx_idx[xi] = i
# xxx_num[i] = xi
def get_xy_by_xi(xi):
i = xxx_idx[xi]
return xxx[i], yyy[i]
def calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt):
lpx, lpy = get_xy_by_xi(lpxi)
rnx, rny = get_xy_by_xi(rnxi)
diag_t = abs(rnx - lpx) + abs(rny - lpy) - rook_cnt
lllt = llt + abs(rnx - lx) + abs(rny - ly) + diag_t
llrt = llt + abs(lx - lpx) + abs(ly - lpy) + diag_t
lrlt = lrt + abs(rnx - rx) + abs(rny - ry) + diag_t
lrrt = lrt + abs(rx - lpx) + abs(ry - lpy) + diag_t
rllt = rlt + abs(rnx - lx) + abs(rny - ly) + diag_t
rlrt = rlt + abs(lx - lpx) + abs(ly - lpy) + diag_t
rrlt = rrt + abs(rnx - rx) + abs(rny - ry) + diag_t
rrrt = rrt + abs(rx - lpx) + abs(ry - lpy) + diag_t
llt = min(lllt, lrlt)
lrt = min(llrt, lrrt)
rlt = min(rllt, rrlt)
rrt = min(rlrt, rrrt)
# print('upd', lpx, lpy, rnx, rny)
# print('upd', llt, lrt, rlt, rrt)
# print('upd', lllt, llrt, lrlt, lrrt, rllt, rlrt, rrlt, rrrt)
return lpx, lpy, rnx, rny, llt, lrt, rlt, rrt
# free[xi] = xi+1 のルークと初期状態から互いに取り合える関係にあるか(0/1)
free = np.zeros(n, dtype=np.int8)
for i in range(n):
xi = xxx_num[i]
yi = yyy_num[i]
px_i = -1 if xi == 0 else xxx_idx[xi - 1]
nx_i = -2 if xi == n - 1 else xxx_idx[xi + 1]
py_i = -3 if yi == 0 else yyy_idx[yi - 1]
ny_i = -4 if yi == n - 1 else yyy_idx[yi + 1]
if px_i == py_i or px_i == ny_i:
free[xi - 1] = 1
if nx_i == py_i or nx_i == ny_i:
free[xi] = 1
# freeが連続する箇所は、どこから始めても互いに全て取り合える
# これを「グループ」とする
# グループの左端と右端のxiを求める
free_l = np.zeros(n, dtype=np.int64)
free_r = np.zeros(n, dtype=np.int64)
l = 0
for xi in range(n - 1):
if free[xi] == 0:
l = xi + 1
free_l[xi + 1] = l
r = n - 1
free_r[r] = r
for xi in range(n - 2, -1, -1):
if free[xi] == 0:
r = xi
free_r[xi] = r
# print(free)
# print(free_l)
# print(free_r)
# グループ内のルークを全部取った時点を0として、追加で取れるルークを取るのにかかる時間
# グループ内のルークを取り終わったのが、左端、右端のいずれかで2通り計算
# 同グループに属するルークはこの情報を共有できるので、一番左端のルークの位置に記録
# Key: xi
extra_l = np.zeros(n, dtype=np.int64)
extra_r = np.zeros(n, dtype=np.int64)
INF = 10 ** 18
lxi = 0
while lxi < n:
rxi = free_r[lxi]
if lxi == rxi:
lxi = rxi + 1
continue
li = xxx_idx[lxi]
ri = xxx_idx[rxi]
lyi = yyy_num[li]
ryi = yyy_num[ri]
lyi, ryi = min(lyi, ryi), max(lyi, ryi)
original_li = lxi
lx = xxx[li]
ly = yyy[li]
rx = xxx[ri]
ry = yyy[ri]
llt, lrt, rlt, rrt = 0, INF, INF, 0
# print('li', li, 'ri', ri, 'lxi', lxi, 'lyi', lyi, 'rxi', rxi, 'ryi', ryi)
while True:
px_i = -1 if lxi == 0 else xxx_idx[lxi - 1]
py_i = -2 if lyi == 0 else yyy_idx[lyi - 1]
nx_i = -3 if rxi == n - 1 else xxx_idx[rxi + 1]
ny_i = -4 if ryi == n - 1 else yyy_idx[ryi + 1]
# print(px_i, py_i, nx_i, ny_i)
if px_i == py_i:
lpxi = free_l[lxi - 1]
rook_cnt = lxi - lpxi
if nx_i == ny_i:
rnxi = free_r[rxi + 1]
rook_cnt += rnxi - rxi
# print(0, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
lx, ly, rx, ry, llt, lrt, rlt, rrt = \
calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt)
lxi = lpxi
rxi = rnxi
lyi = yyy_num[xxx_idx[lxi]]
ryi = yyy_num[xxx_idx[rxi]]
lyi, ryi = min(lyi, ryi), max(lyi, ryi)
# print(0, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
else:
# print(1, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
lx, ly, rx, ry, llt, lrt, rlt, rrt = \
calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, lpxi, rook_cnt)
lxi = lpxi
lyi = yyy_num[xxx_idx[lxi]]
lyi, ryi = min(lyi, ryi), max(lyi, ryi)
# print(1, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
elif px_i == ny_i:
lpxi = free_l[lxi - 1]
rook_cnt = lxi - lpxi
if nx_i == py_i:
rnxi = free_r[rxi + 1]
rook_cnt += rnxi - rxi
# print(2, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
lx, ly, rx, ry, llt, lrt, rlt, rrt = \
calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, rnxi, rook_cnt)
lxi = lpxi
rxi = rnxi
lyi = yyy_num[xxx_idx[lxi]]
ryi = yyy_num[xxx_idx[rxi]]
lyi, ryi = min(lyi, ryi), max(lyi, ryi)
# print(2, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
else:
# print(3, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, llt, lrt, rlt, rrt)
lx, ly, rx, ry, llt, lrt, rlt, rrt = \
calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, lpxi, lpxi, rook_cnt)
lxi = lpxi
uyi = yyy_num[xxx_idx[lxi]]
lyi, ryi = min(uyi, lyi, ryi), max(uyi, lyi, ryi)
# print(3, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, llt, lrt, rlt, rrt)
elif nx_i == ny_i or nx_i == py_i:
rnxi = free_r[rxi + 1]
rook_cnt = rnxi - rxi
# print(4, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
lx, ly, rx, ry, llt, lrt, rlt, rrt = \
calc_time(lx, ly, rx, ry, llt, lrt, rlt, rrt, rnxi, rnxi, rook_cnt)
rxi = rnxi
ryi = yyy_num[xxx_idx[rxi]]
lyi, ryi = min(lyi, ryi), max(lyi, ryi)
# print(4, lxi, rxi, lyi, ryi, '|', lx, ly, rx, ry, lt, rt)
else:
extra_l[original_li] = min(llt, lrt)
extra_r[original_li] = min(rlt, rrt)
break
lxi = rxi + 1
# print(extra_l)
# print(extra_r)
ans = np.zeros(n, dtype=np.int64)
for i in range(n):
xi = xxx_num[i]
x = xxx[i]
y = yyy[i]
lxi = free_l[xi]
lx = xxx[xxx_idx[lxi]]
ly = yyy[xxx_idx[lxi]]
rxi = free_r[xi]
rx = xxx[xxx_idx[rxi]]
ry = yyy[xxx_idx[rxi]]
lt = extra_l[lxi]
rt = extra_r[lxi]
diag = abs(rx - lx) + abs(ry - ly) - (rxi - lxi)
rlt = abs(rx - x) + abs(ry - y) + diag
lrt = abs(x - lx) + abs(y - ly) + diag
ans[i] = min(lt + rlt, rt + lrt)
return ans
if sys.argv[-1] == 'ONLINE_JUDGE':
from numba.pycc import CC
cc = CC('my_module')
cc.export('solve', '(i8[:],)')(solve)
cc.compile()
exit()
if os.name == 'posix':
# noinspection PyUnresolvedReferences
from my_module import solve
else:
from numba import njit
solve = njit('(i8[:],)', cache=True)(solve)
print('compiled', file=sys.stderr)
inp = np.fromstring(sys.stdin.read(), dtype=np.int64, sep=' ')
ans = solve(inp)
print('\n'.join(map(str, ans)))
``` | instruction | 0 | 80,605 | 15 | 161,210 |
No | output | 1 | 80,605 | 15 | 161,211 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,638 | 15 | 161,276 |
"Correct Solution:
```
from collections import deque
n,m=map(int,input().split())
edge = [[] for i in range(n+1)]
#edge[i] : iから出る道の[行先]の配列
for _ in range(m):
u, v = map(int, input().split())
edge[u].append(v)
s,t = map(int, input().split())
queue = deque()
queue.append((s, 0))
visited = [[False] * 3 for _ in range(n+1)]
while queue:
u, d = queue.popleft()
if visited[u][d % 3]:
continue
visited[u][d % 3] = True
if d % 3 == 0 and u == t:
print(d // 3);exit()
for v in edge[u]:
queue.append((v, d+1))
print(-1)
``` | output | 1 | 80,638 | 15 | 161,277 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,639 | 15 | 161,278 |
"Correct Solution:
```
import heapq
N,M=map(int,input().split())
G=[set() for i in range(N)]
for i in range(M):
u,v=map(int,input().split())
G[u-1].add(v-1)
#print(G)
S,T=map(int,input().split())
S-=1;T-=1
#dp[i][j]:i番目の頂点をmod 3=jで行けるかどうか
dist=[[10**10 for i in range(3)] for i in range(N)]
dist[S][0]=0
q=[]
heapq.heappush(q,(dist[S][0],S,0))
while(len(q)>0):
d,r,j=heapq.heappop(q)
if dist[r][j]<d:
continue
for p in G[r]:
if dist[p][(j+1)%3]>dist[r][j]+1:
dist[p][(j+1)%3]=dist[r][j]+1
heapq.heappush(q,(dist[p][(j+1)%3],p,(j+1)%3))
#print(dist)
if dist[T][0]==10**10:
print(-1)
else:
print(dist[T][0]//3)
``` | output | 1 | 80,639 | 15 | 161,279 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,640 | 15 | 161,280 |
"Correct Solution:
```
from collections import deque
N,M = map(int,input().split())
adj = [ [] for _ in range(N) ]
for _ in range(M):
a,b = map(int,input().split())
a -= 1
b -= 1
adj[a].append(b)
S,T = map(int,input().split())
S -= 1
T -= 1
INF = float('inf')
dist = [ [INF]*3 for _ in range(N) ]
q = deque([(S,0)])
dist[S][0] = 0
while q:
n,d = q.popleft()
for v in adj[n]:
nd = (d+1)%3
if dist[v][nd] != INF: continue
dist[v][nd] = dist[n][d]+1
q.append((v,nd))
if dist[T][0] == INF:
print(-1)
else:
print(dist[T][0]//3)
``` | output | 1 | 80,640 | 15 | 161,281 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,641 | 15 | 161,282 |
"Correct Solution:
```
N, M = map(int, input().split())
E = [[] for _ in range(N+1)]
for _ in range(M):
u, v = map(int, input().split())
E[u].append(v)
Closed = [[False]*(N+1) for _ in range(3)]
S, T = map(int, input().split())
st = [(S, 0)]
Closed[0][S] = True
ans = 0
while len(st):
st_new = []
for v, n in st:
if v==T and n==0:
print(ans // 3)
exit()
n1 = (n+1)%3
Cl = Closed[n1]
for u in E[v]:
if not Cl[u]:
st_new.append((u, n1))
Cl[u] = True
st = st_new
ans += 1
print(-1)
``` | output | 1 | 80,641 | 15 | 161,283 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,642 | 15 | 161,284 |
"Correct Solution:
```
import copy
n, m = map(int,input().split())
edge = []
graph = [[] for i in range(n+1)]
for i in range(m):
edge.append(list(map(int,input().split())))
graph[edge[-1][0]].append(edge[-1][1])
s, g = map(int,input().split())
INF = 10**11
ans = [[INF, INF, INF] for i in range(n+1)]
q = [s]
d = 0
while q:
nq = []
d += 1
p = d % 3
for cf in q:
for ct in graph[cf]:
if ans[ct][p] == INF:
ans[ct][p] = d
nq.append(ct)
q = copy.deepcopy(nq)
if ans[g][0] == INF:
print(-1)
else:
print(ans[g][0]//3)
``` | output | 1 | 80,642 | 15 | 161,285 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,643 | 15 | 161,286 |
"Correct Solution:
```
# ABC132 E
from collections import deque
f=lambda:map(int,input().split())
N,M=f()
G=[[] for _ in [0]*(N+1)]
for _ in [0]*M:
a,b=f()
G[a].append(b)
S,T=f()
S=(S,0)
T=(T,0)
q=deque()
q.append(S)
F=set()
res=-1
while q:
node,r=q.popleft()
if (node,r%3) in F:
continue
if (node,r%3) == T:
res=r//3
break
F.add((node,r%3))
for next_node in G[node]:
if (next_node,(r+1)%3) in F:
continue
q.append((next_node,r+1))
print(res)
``` | output | 1 | 80,643 | 15 | 161,287 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,644 | 15 | 161,288 |
"Correct Solution:
```
import queue
N, M = list(map(int, input().split()))
uv = [list(map(int, input().split())) for _ in range(M)]
S, T = list(map(int, input().split()))
V = [[0, 0, 0] for _ in range(N + 1)]
R = {}
for u, v in uv:
if u not in R:
R[u] = [v]
else:
R[u].append(v)
q = queue.Queue()
put = q.put
get = q.get
put([S, 0, 2])
ans = -1
while not q.empty():
t = get()
if t[0] == T and t[2] == 2:
ans = t[1]
break
k = (t[2] + 1) % 3
m = t[1]
if t[2] == 2:
m += 1
if t[0] not in R: continue
for i in R[t[0]]:
if V[i][k] == 0:
V[i][k] = 1
put([i, m, k])
print(ans)
``` | output | 1 | 80,644 | 15 | 161,289 |
Provide a correct Python 3 solution for this coding contest problem.
Ken loves ken-ken-pa (Japanese version of hopscotch). Today, he will play it on a directed graph G. G consists of N vertices numbered 1 to N, and M edges. The i-th edge points from Vertex u_i to Vertex v_i.
First, Ken stands on Vertex S. He wants to reach Vertex T by repeating ken-ken-pa. In one ken-ken-pa, he does the following exactly three times: follow an edge pointing from the vertex on which he is standing.
Determine if he can reach Vertex T by repeating ken-ken-pa. If the answer is yes, find the minimum number of ken-ken-pa needed to reach Vertex T. Note that visiting Vertex T in the middle of a ken-ken-pa does not count as reaching Vertex T by repeating ken-ken-pa.
Constraints
* 2 \leq N \leq 10^5
* 0 \leq M \leq \min(10^5, N (N-1))
* 1 \leq u_i, v_i \leq N(1 \leq i \leq M)
* u_i \neq v_i (1 \leq i \leq M)
* If i \neq j, (u_i, v_i) \neq (u_j, v_j).
* 1 \leq S, T \leq N
* S \neq T
Input
Input is given from Standard Input in the following format:
N M
u_1 v_1
:
u_M v_M
S T
Output
If Ken cannot reach Vertex T from Vertex S by repeating ken-ken-pa, print -1. If he can, print the minimum number of ken-ken-pa needed to reach vertex T.
Examples
Input
4 4
1 2
2 3
3 4
4 1
1 3
Output
2
Input
3 3
1 2
2 3
3 1
1 2
Output
-1
Input
2 0
1 2
Output
-1
Input
6 8
1 2
2 3
3 4
4 5
5 1
1 4
1 5
4 6
1 6
Output
2 | instruction | 0 | 80,645 | 15 | 161,290 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
N, M = map(int, input().split())
graph = [[] for _ in range(N)]
for _ in range(M):
a, b = map(int, input().split())
graph[a-1].append(b-1)
#graph[b-1].append(a-1)
S, T = map(int, input().split())
S -= 1; T -= 1
D = [[-1]*3 for _ in range(N)]
D[S][0] = 0
q = [(S, 0)]
while q:
qq = []
for p, d in q:
for np in graph[p]:
nd = (d+1)%3
if D[np][nd] == -1:
D[np][nd] = D[p][d] + 1
qq.append((np, nd))
q = qq
if D[T][0] == -1:
print(-1)
else:
print(D[T][0]//3)
``` | output | 1 | 80,645 | 15 | 161,291 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,065 | 15 | 162,130 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
MAX_N = 105
root = [0 for _ in range(MAX_N)]
n = int(input().strip())
x = []
y = []
def findRoot(u):
if u == root[u]:
return u
else:
root[u] = findRoot(root[u])
return root[u]
for i in range(n):
valx, valy = map(int, input().strip().split())
x.append(valx)
y.append(valy)
for i in range(n):
root[i] = i
res = n
for i in range(n):
for j in range(i + 1, n):
if x[i] == x[j] or y[i] == y[j]:
rootu = findRoot(i)
rootv = findRoot(j)
if rootu != rootv:
res -= 1
root[rootu] = rootv
print(res - 1)
``` | output | 1 | 81,065 | 15 | 162,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,067 | 15 | 162,134 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
# WeirdBugsButOkay
n = int(input())
p = []
def dfs(i) :
p[i][2] = z
for j in range (0, n) :
if p[j][2] == -1 and (p[j][0] == p[i][0] or p[j][1] == p[i][1]) :
dfs(j)
for i in range (0, n) :
x1, y1 = list(map(int, input().split()))
p.append([x1,y1,-1])
z = -1
for i in range (0, n) :
if p[i][2] == -1 :
z += 1
dfs(i)
print(z)
``` | output | 1 | 81,067 | 15 | 162,135 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,068 | 15 | 162,136 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
def neighbour(v):
global vs, used
ns = []
for i in range(len(vs)):
if v[2] != i and (vs[i][0] == v[0] or vs[i][1] == v[1]) and used[vs[i][2]] == False:
ns.append(vs[i])
return ns
def dfs(v):
global vs, used
used[v[2]] = True
for elem in neighbour(v):
dfs(elem)
vs = []
n = int(input())
for i in range(n):
x, y = map(int, input().split())
vs.append([x, y, i])
used = [False] * n
res = 0
for i in range(n):
if used[i] == False:
dfs(vs[i])
res += 1
print(res-1)
``` | output | 1 | 81,068 | 15 | 162,137 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,069 | 15 | 162,138 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
n = int(input())
p = []
def dfs(i):
p[i][-1] = res
for j in range(n):
if p[j][-1] == -1 and (p[i][0] == p[j][0] or p[i][1] == p[j][1]):
dfs(j)
res = -1
for i in range(n):
x, y = map(int, input().split())
p.append([x, y, -1])
for i in range(n):
if p[i][-1] == -1:
res += 1
dfs(i)
print(res)
``` | output | 1 | 81,069 | 15 | 162,139 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,071 | 15 | 162,142 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
n = int(input())
G = [[0,0] for _ in range(n)]
f = list(range(n+1))
def fd(a):
if f[a]!=a:f[a] = fd(f[a])
return f[a]
def un(a,b):
ra,rb = fd(a),fd(b)
if ra==rb:return
f[ra] = rb
for i in range(n):
x,y = map(int,input().split())
G[i] = [x,y]
for i in range(n):
for j in range(i):
if G[i][0] == G[j][0] or G[i][1] == G[j][1]:
un(i+1,j+1)
print(sum(1 for i in range(1,n+1) if f[i]==i)-1)
``` | output | 1 | 81,071 | 15 | 162,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0 | instruction | 0 | 81,072 | 15 | 162,144 |
Tags: brute force, dfs and similar, dsu, graphs
Correct Solution:
```
def dfs(start):
prev[start] = True
for i in mas[start]:
if not prev[i]:
dfs(i)
n = int(input())
mas = []
for i in range(2000):
mas.append([])
prev = [True] * 2000
for i in range(n):
x, y = map(int, input().split())
mas[x - 1].append(y + 1000 - 1)
mas[y + 1000 - 1].append(x - 1)
prev[x - 1] = False
prev[y + 1000 - 1] = False
count = 0
for i in range(2000):
if not prev[i]:
dfs(i)
count += 1
print(count - 1)
``` | output | 1 | 81,072 | 15 | 162,145 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
__author__ = 'Juan Barros'
'''
http://codeforces.com/problemset/problem/217/A
'''
def solve(A, n):
V = [[0]*(1000 + 1) for i in range(1000 + 1)]
for i in range(n):
r, c = A[i]
V[c][r] = 1
listAdj = {}
for i in range(n):
r, c = A[i]
listAdj[(r,c)] = []
for j in range(1000 +1):
if j != r and V[c][j] == 1:
listAdj[(r, c)].append((j, c))
for j in range(1000 +1):
if j != c and V[j][r] == 1:
listAdj[(r, c)].append((r, j))
vis = {}
pred = {}
for key in listAdj.keys():
vis[key] = "BRANCO"
pred[key] = None
count = -1
for key in listAdj.keys():
if vis[key] == "BRANCO":
vis, pred = visitaDfs(vis, pred, listAdj, key)
vis[key] = "PRETO"
count += 1
return count
def visitaDfs(vis, pred, listAdj, atual):
vis[atual] = "CINZA"
for adj in listAdj[atual]:
if vis[adj] == "BRANCO":
pred[adj] = atual
vis, pred = visitaDfs(vis, pred, listAdj, adj)
vis[atual] = "PRETO"
return vis, pred
if __name__ == "__main__":
n = int(input())
aux = []
for i in range(n):
aux.append(list(map(int, input().split())))
print(solve(aux, n))
``` | instruction | 0 | 81,073 | 15 | 162,146 |
Yes | output | 1 | 81,073 | 15 | 162,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
def main():
mode="filee"
if mode=="file":f=open("test.txt","r")
get = lambda :[int(x) for x in (f.readline() if mode=="file" else input()).split()]
[n]=get()
ax={}
for z in range(n):
[x,y]=get()
if x in ax:ax[x].append(y)
else:ax[x]=[y]
count=0
axx=[]
for i in ax.keys():axx.append([i,len(ax[i])])
axx.reverse()
visitedy = set(ax[axx[0][0]])
axx.remove(axx[0])
while len(axx)>0:
record=-1
for i,j in axx:
if visitedy.isdisjoint(set(ax[i]))==False:
visitedy = visitedy.union(set(ax[i]))
axx.remove([i,j])
record=i
break
if record==-1:
count+=1
visitedy = visitedy.union(set(ax[axx[0][0]]))
print(count)
if mode=="file":f.close()
if __name__=="__main__":
main()
``` | instruction | 0 | 81,075 | 15 | 162,150 |
Yes | output | 1 | 81,075 | 15 | 162,151 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
n = int(input())
a = [list(map(int, input().split())) for _ in range(n)]
arr = [i for i in range(n)]
for i1 in range(n):
s = set()
for i2 in range(n):
if a[i1][0] == a[i2][0] or a[i1][1] == a[i2][1]:
s.add(arr[i2])
mn = min(s)
for e in s:
arr[e] = mn
print(len(set(arr)) - 1)
``` | instruction | 0 | 81,079 | 15 | 162,158 |
No | output | 1 | 81,079 | 15 | 162,159 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Bajtek is learning to skate on ice. He's a beginner, so his only mode of transportation is pushing off from a snow drift to the north, east, south or west and sliding until he lands in another snow drift. He has noticed that in this way it's impossible to get from some snow drifts to some other by any sequence of moves. He now wants to heap up some additional snow drifts, so that he can get from any snow drift to any other one. He asked you to find the minimal number of snow drifts that need to be created.
We assume that Bajtek can only heap up snow drifts at integer coordinates.
Input
The first line of input contains a single integer n (1 ≤ n ≤ 100) — the number of snow drifts. Each of the following n lines contains two integers xi and yi (1 ≤ xi, yi ≤ 1000) — the coordinates of the i-th snow drift.
Note that the north direction coinсides with the direction of Oy axis, so the east direction coinсides with the direction of the Ox axis. All snow drift's locations are distinct.
Output
Output the minimal number of snow drifts that need to be created in order for Bajtek to be able to reach any snow drift from any other one.
Examples
Input
2
2 1
1 2
Output
1
Input
2
2 1
4 1
Output
0
Submitted Solution:
```
n = int(input())
l = []
for i in range(n):
coordinates = list(map(int, input().split()))
l.append(coordinates)
drifts = -1
for i in range(n):
if l[i]:
drifts += 1
passed_x, passed_y = l[i]
l[i] = 0
for j in range(n):
if l[j] and (passed_x == l[j][0] or passed_y == l[j][1]):
l[j] = 0
print (drifts)
``` | instruction | 0 | 81,080 | 15 | 162,160 |
No | output | 1 | 81,080 | 15 | 162,161 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,276 | 15 | 162,552 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = input()
v = [int(i) for i in input().split(' ')]
used = set()
curr = 0
while True:
if curr in used:
print('INFINITE')
break
used.add(curr)
curr += (v[curr])*(1 if s[curr]=='>' else -1)
if curr<0 or curr>=n:
print('FINITE')
break
``` | output | 1 | 81,276 | 15 | 162,553 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,277 | 15 | 162,554 |
Tags: implementation
Correct Solution:
```
##import math
class codeforces:
## def presents(self,a):
## if a==1 or a==2:
## ans=1
## else:
## ans=(math.floor(a/3))*2
## if a%3!=0:
## ans+=1
## print(int(ans))
## return int(ans)
def grasshopper(self,n,dir,step):
## print(n)
## print(dir)
## print(step)
visit=[]
for x in range(n):
visit.append(0)
## print(visit)
visit[0]=1
response=0
pos=0
while 1:
if dir[pos]=='>':
pos+=step[pos]
if pos>=n:
response=0
break
else:
if visit[pos]==0:
visit[pos]=1
else:
response=1
break
else:
pos-=step[pos]
if pos<0:
response=0
break
else:
if visit[pos]==0:
visit[pos]=1
else:
response=1
break
## print(visit)
if response==0:
print('FINITE')
return 'FINITE'
else:
print('INFINITE')
return 'INFINITE'
s=codeforces()
##a=int(input())
##s.presents(a)
n=int(input())
dir=[x for x in input().strip()]
step=[int(x) for x in input().split()]
##n=2;dir=['>','<'];step=[1,2]
##n=3;dir=['>','>','<'];step=[2,1,1]
s.grasshopper(n,dir,step)
``` | output | 1 | 81,277 | 15 | 162,555 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,278 | 15 | 162,556 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = input()
A = list(map(int, input().split()))
k = 1
B = [True for i in range(n)]
while True:
napr = s[k - 1]
if B[k - 1] == False:
print('INFINITE')
break
elif napr == '>' and B[k - 1] == True:
B[k - 1] = False
k += A[k - 1]
elif napr == '<' and B[k - 1] == True:
B[k - 1] = False
k -= A[k - 1]
if k < 1 or k > n:
print('FINITE')
break
``` | output | 1 | 81,278 | 15 | 162,557 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,279 | 15 | 162,558 |
Tags: implementation
Correct Solution:
```
n=int(input())
a=input()
b=[int(i) for i in input().split()]
i=0
temp=0
while True:
if i < 0 or i >= n:
print("FINITE")
break
if b[i]==0:
print("INFINITE")
break
temp=b[i]
if a[i]=='<':
temp=-1*temp
b[i]=0
i+=temp
``` | output | 1 | 81,279 | 15 | 162,559 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,280 | 15 | 162,560 |
Tags: implementation
Correct Solution:
```
def main():
n = int(input())
l = [j - i if c == "<" else j + i for c, i, j in zip(input(), map(int, input().split()), range(n))]
v, i = [True] * n, 0
while 0 <= i < n:
if v[i]:
v[i] = False
else:
print("INFINITE")
return
i = l[i]
print("FINITE")
if __name__ == "__main__":
main()
``` | output | 1 | 81,280 | 15 | 162,561 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,281 | 15 | 162,562 |
Tags: implementation
Correct Solution:
```
n = int(input())
s = list(1 if x == '>' else -1 for x in input())
l = list(map(int, input().split()))
summ = 1
cur = 0
next = 0
for i in range(n):
if cur < 0 or cur > n - 1:
print('FINITE')
exit()
if l[cur] == 0:
print('INFINITE')
exit()
next += l[cur] * s[cur]
l[cur] = 0
cur = next
print('INFINITE' if 0 <= cur < n else 'FINITE')
``` | output | 1 | 81,281 | 15 | 162,563 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,282 | 15 | 162,564 |
Tags: implementation
Correct Solution:
```
class CodeforcesTask641ASolution:
def __init__(self):
self.result = ''
self.n = 0
self.directions = []
self.jump_lengths = []
def read_input(self):
self.n = int(input())
self.directions = input()
self.jump_lengths = [int(x) for x in input().split(" ")]
def process_task(self):
jumps = 0
pos = 1
out = False
while jumps < self.n * 10 and not out:
jumps += 1
pos += (-1 if self.directions[pos - 1] == "<" else 1) * self.jump_lengths[pos - 1]
if pos < 1 or pos > self.n:
out = True
self.result = "FINITE" if out else "INFINITE"
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask641ASolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 81,282 | 15 | 162,565 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite. | instruction | 0 | 81,283 | 15 | 162,566 |
Tags: implementation
Correct Solution:
```
n = int(input())
l = [1 if x == ">" else -1 for x in input()]
c = list(map(int, input().split()))
for i in range(len(c)):
l[i] *= c[i]
ret = True
i = 0
vis = {i}
while True:
if i < 0 or i >= n:
ret = False
break
i += l[i]
if i in vis:
ret = True
break
vis.add(i)
if ret:
print("INFINITE")
else:
print("FINITE")
``` | output | 1 | 81,283 | 15 | 162,567 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Little Artem found a grasshopper. He brought it to his house and constructed a jumping area for him.
The area looks like a strip of cells 1 × n. Each cell contains the direction for the next jump and the length of that jump. Grasshopper starts in the first cell and follows the instructions written on the cells. Grasshopper stops immediately if it jumps out of the strip. Now Artem wants to find out if this will ever happen.
Input
The first line of the input contains a single integer n (1 ≤ n ≤ 100 000) — length of the strip.
Next line contains a string of length n which consists of characters "<" and ">" only, that provide the direction of the jump from the corresponding cell. Next line contains n integers di (1 ≤ di ≤ 109) — the length of the jump from the i-th cell.
Output
Print "INFINITE" (without quotes) if grasshopper will continue his jumps forever. Otherwise print "FINITE" (without quotes).
Examples
Input
2
><
1 2
Output
FINITE
Input
3
>><
2 1 1
Output
INFINITE
Note
In the first sample grasshopper starts from the first cell and jumps to the right on the next cell. When he is in the second cell he needs to jump two cells left so he will jump out of the strip.
Second sample grasshopper path is 1 - 3 - 2 - 3 - 2 - 3 and so on. The path is infinite.
Submitted Solution:
```
def mp(): return map(int,input().split())
def lt(): return list(map(int,input().split()))
def pt(x): print(x)
def ip(): return input()
def it(): return int(input())
def sl(x): return [t for t in x]
def spl(x): return x.split()
def aj(liste, item): liste.append(item)
def bin(x): return "{0:b}".format(x)
def listring(l): return ' '.join([str(x) for x in l])
def printlist(l): print(' '.join([str(x) for x in l]))
n = it()
s = list(input())
a = lt()
visited = [False for i in range(n)]
k = 0
while 0 <= k and k < n and not visited[k]:
visited[k] = True
if s[k] == ">":
k += a[k]
else:
k -= a[k]
if k < 0 or k >= n:
print("FINITE")
else:
print("INFINITE")
``` | instruction | 0 | 81,284 | 15 | 162,568 |
Yes | output | 1 | 81,284 | 15 | 162,569 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.