message stringlengths 2 19.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
#D
input()
ok = {0:0}
for p, c in zip(list(map(int, input().split())),
list(map(int, input().split()))):
ad = []
for b, u in ok.items():
a = p
while b:
a,b = b, a % b
ad.append((a, u + c))
for a, u in ad:
ok[a] = min(u, ok.get(a, 1000000000))
print(ok.get(1, -1))
``` | instruction | 0 | 11,170 | 15 | 22,340 |
Yes | output | 1 | 11,170 | 15 | 22,341 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
from collections import defaultdict
from math import gcd
from heapq import heappop, heappush
n = int(input())
A = list(map(int, input().split()))
B = list(map(int, input().split()))
hp = [(0, 0)]
dis = {0: 0}
seen = set()
while hp:
_, x = heappop(hp)
if x == 1:
print(dis[x])
break
if x in seen: continue
seen.add(x)
for a, b in zip(A, B):
y = gcd(x, a)
if y not in dis or dis[y] > dis[x] + b:
dis[y] = dis[x] + b
heappush(hp, (dis[y], y))
else:
print(-1)
``` | instruction | 0 | 11,171 | 15 | 22,342 |
Yes | output | 1 | 11,171 | 15 | 22,343 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var): sys.stdout.write(str(var) + '\n')
from decimal import Decimal
# from fractions import Fraction
# sys.setrecursionlimit(100000)
mod = int(1e9) + 7
INF=float('inf')
n=int(data())
l=mdata()
c=mdata()
d=dict()
for i in range(n):
d[l[i]]=c[i]
for i in l:
lis=list(d.keys())
for j in lis:
g = math.gcd(i, j)
if d.get(g):
d[g]=min(d[g],d[i]+d[j])
else:
d[g] = d[i] + d[j]
if 1 in d:
out(d[1])
else:
out(-1)
``` | instruction | 0 | 11,172 | 15 | 22,344 |
No | output | 1 | 11,172 | 15 | 22,345 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
import sys
from math import gcd
from collections import defaultdict as dd
input=sys.stdin.readline
n=int(input())
l=list(map(int,input().split()))
yakusu=set()
for i in range(n):
ll=l[i]
for j in range(1,int(ll**0.5)+1):
if ll%j==0:
yakusu.add(j)
yakusu.add(ll//j)
c=list(map(int,input().split()))
INF=10**18
dp=[dd(int) for i in range(n)]
for i in range(n):
for x in yakusu:
dp[i][x]=INF
for i in range(n):
dp[i][l[i]]=c[i]
if i>0:
for x in yakusu:
dp[i][x]=min(dp[i][x],dp[i-1][x])
ml=max(l)
for i in range(n):
for j in yakusu:
jl=gcd(j,l[i])
dp[i][jl]=min(dp[i][jl],dp[i-1][jl],dp[i-1][j]+c[i])
if dp[n-1][1]==INF:
print(-1)
else:
print(dp[n-1][1])
``` | instruction | 0 | 11,173 | 15 | 22,346 |
No | output | 1 | 11,173 | 15 | 22,347 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Fox Ciel is playing a game. In this game there is an infinite long tape with cells indexed by integers (positive, negative and zero). At the beginning she is standing at the cell 0.
There are also n cards, each card has 2 attributes: length li and cost ci. If she pays ci dollars then she can apply i-th card. After applying i-th card she becomes able to make jumps of length li, i. e. from cell x to cell (x - li) or cell (x + li).
She wants to be able to jump to any cell on the tape (possibly, visiting some intermediate cells). For achieving this goal, she wants to buy some cards, paying as little money as possible.
If this is possible, calculate the minimal cost.
Input
The first line contains an integer n (1 ≤ n ≤ 300), number of cards.
The second line contains n numbers li (1 ≤ li ≤ 109), the jump lengths of cards.
The third line contains n numbers ci (1 ≤ ci ≤ 105), the costs of cards.
Output
If it is impossible to buy some cards and become able to jump to any cell, output -1. Otherwise output the minimal cost of buying such set of cards.
Examples
Input
3
100 99 9900
1 1 1
Output
2
Input
5
10 20 30 40 50
1 1 1 1 1
Output
-1
Input
7
15015 10010 6006 4290 2730 2310 1
1 1 1 1 1 1 10
Output
6
Input
8
4264 4921 6321 6984 2316 8432 6120 1026
4264 4921 6321 6984 2316 8432 6120 1026
Output
7237
Note
In first sample test, buying one card is not enough: for example, if you buy a card with length 100, you can't jump to any cell whose index is not a multiple of 100. The best way is to buy first and second card, that will make you be able to jump to any cell.
In the second sample test, even if you buy all cards, you can't jump to any cell whose index is not a multiple of 10, so you should output -1.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def ctd(chr): return ord(chr)-ord("a")
mod = 998244353
INF = float('inf')
from math import gcd
# ------------------------------
def main():
n = N()
larr = RLL()
carr = RLL()
dic = {}
dic[0] = 0
for i in range(n):
l, c = larr[i], carr[i]
ndic = dic.copy()
for j in dic:
now = gcd(j, l)
if now not in dic:
ndic[now] = c+dic[j]
else:
ndic[now] = min(ndic[now], dic[j]+c)
dic = ndic
print(dic.get(1, -1))
if __name__ == "__main__":
main()
``` | instruction | 0 | 11,174 | 15 | 22,348 |
No | output | 1 | 11,174 | 15 | 22,349 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | instruction | 0 | 11,289 | 15 | 22,578 |
Tags: *special, dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from collections import deque
n, m, k =map(int, input().split())
grid = []
for i in range(n):
grid.append(input())
for j in range(m):
if grid[i][j] == "X":
pos_i, pos_j = i, j
if k & 1:
print('IMPOSSIBLE')
exit()
order = "DLRU"
order_dir = [(1,0), (0,-1), (0,1), (-1, 0)]
ds = [[float("inf")]*m for _ in range(n)]
ds[pos_i][pos_j] = 0
q = deque()
q.append((pos_i, pos_j))
while len(q):
x, y = q.popleft()
for delta in order_dir:
nx = x + delta[0]
ny = y + delta[1]
if 0 <= nx < n and 0 <= ny < m and ds[nx][ny] == float("inf") and grid[nx][ny] != "*":
q.append((nx, ny))
ds[nx][ny] = ds[x][y] + 1
start_pos_i = pos_i
start_pos_j = pos_j
path = ""
while k:
for i, d in enumerate(order):
ni = pos_i + order_dir[i][0]
nj = pos_j + order_dir[i][1]
if 0 <= ni < n and 0 <= nj < m and ds[ni][nj] <= k-1 and grid[ni][nj] != "*":
path += d
k -= 1
pos_i = ni
pos_j = nj
break
else:
print("IMPOSSIBLE")
exit()
print(path)
``` | output | 1 | 11,289 | 15 | 22,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | instruction | 0 | 11,290 | 15 | 22,580 |
Tags: *special, dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
import math
from collections import deque
def main():
n, m, k = list(map(int, input().split()))
grid = ["" for _ in range(n)]
x, y = 0, 0
for i in range(n):
grid[i] = input()
if 'X' in grid[i]:
x, y = i, grid[i].index('X')
if k % 2 == 1:
print("IMPOSSIBLE")
return
dx = [1, 0, 0, -1]
dy = [0, -1, 1, 0]
names = {(x1, y1): sym for x1, y1, sym in zip(dx, dy, "DLRU")}
rev_names = {x1: y1 for x1, y1 in zip("DLRU", "URLD")}
def ok(x, y):
return (0 <= x < n) and (0 <= y < m) and grid[x][y] != '*'
def bfs(x, y):
MAX_DIST = (1 << 20)
dist = [[MAX_DIST for y in range(m)] for x in range(n)]
dist[x][y] = 0
q = deque()
q.append((x, y))
while len(q) > 0:
x, y = q.popleft()
for x0, y0 in zip(dx, dy):
if ok(x + x0, y + y0) and dist[x][y] + 1 < dist[x + x0][y + y0]:
dist[x + x0][y + y0] = dist[x][y] + 1
q.append((x + x0, y + y0))
return dist
path = []
x_start, y_start = x, y
dist = bfs(x_start, y_start)
for i in range(k // 2):
for x1, y1 in zip(dx, dy):
if ok(x + x1, y + y1):
path.append(names.get((x1, y1)))
x += x1
y += y1
break
else:
print("IMPOSSIBLE")
return
moves = k // 2
for i in range(k // 2):
for x1, y1 in zip(dx, dy):
if ok(x + x1, y + y1) and dist[x + x1][y + y1] <= moves:
path.append(names.get((x1, y1)))
x += x1
y += y1
moves -= 1
break
print("".join(x for x in path))
if __name__ == '__main__':
main()
``` | output | 1 | 11,290 | 15 | 22,581 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | instruction | 0 | 11,291 | 15 | 22,582 |
Tags: *special, dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
import math
from collections import deque
def main():
n, m, k = list(map(int, input().split()))
grid = ["" for _ in range(n)]
x, y = 0, 0
for i in range(n):
grid[i] = input()
if 'X' in grid[i]:
x, y = i, grid[i].index('X')
if k % 2 == 1:
print("IMPOSSIBLE")
return
dx = [1, 0, 0, -1]
dy = [0, -1, 1, 0]
names = {(x1, y1): sym for x1, y1, sym in zip(dx, dy, "DLRU")}
rev_names = {x1: y1 for x1, y1 in zip("DLRU", "URLD")}
def ok(x, y):
return (0 <= x < n) and (0 <= y < m) and grid[x][y] != '*'
def bfs(x, y):
MAX_DIST = (1 << 20)
dist = [[MAX_DIST for y in range(m)] for x in range(n)]
dist[x][y] = 0
q = deque()
q.append((x, y))
while len(q) > 0:
x, y = q.popleft()
for x0, y0 in zip(dx, dy):
if ok(x + x0, y + y0) and dist[x][y] + 1 < dist[x + x0][y + y0]:
dist[x + x0][y + y0] = dist[x][y] + 1
q.append((x + x0, y + y0))
return dist
path = []
x_start, y_start = x, y
dist = bfs(x_start, y_start)
for i in range(k // 2):
for x1, y1 in zip(dx, dy):
if ok(x + x1, y + y1):
path.append(names.get((x1, y1)))
x += x1
y += y1
break
else:
print("IMPOSSIBLE")
return
moves = k // 2
for i in range(k // 2):
for x1, y1 in zip(dx, dy):
if ok(x + x1, y + y1) and dist[x + x1][y + y1] <= moves:
path.append(names.get((x1, y1)))
x += x1
y += y1
moves -= 1
break
print("".join(x for x in path))
if __name__ == '__main__':
main()
# Made By Mostafa_Khaled
``` | output | 1 | 11,291 | 15 | 22,583 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | instruction | 0 | 11,292 | 15 | 22,584 |
Tags: *special, dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
from queue import Queue
import sys
#sys.stdin = open('input.txt')
n, m, k = map(lambda x: int(x), input().split(' '))
if k&1:
print('IMPOSSIBLE')
sys.exit()
s = [None]*n
for i in range(n):
s[i] = [None]*m
t = input()
for j in range(m):
s[i][j] = t[j]
if t[j] == 'X': x, y = j, i
def bfs(x, y):
res = [[10000000]*m for i in range(n)]
if s[y][x] == '*': return res
q = Queue()
q.put((x, y))
step = 0
def add(x, y):
if res[y][x] != 10000000 or s[y][x] == '*' or step >= res[y][x]: return
q.put((x, y))
res[y][x] = step+1
res[y][x] = step
while not q.empty():
x, y = q.get()
step = res[y][x]
#print('-')
if y < n-1: add(x, y+1) #D
if x > 0: add(x-1, y) #L
if x < m-1: add(x+1, y) #R
if y > 0: add(x, y-1) #U
return res
res = bfs(x, y)
path = []
add = lambda s: path.append(s)
for i in range(k):
step = k-i
#print(step, (y, x), k-i)
if y < n-1 and res[y+1][x] <= step: #D
add('D')
y = y+1
elif x > 0 and res[y][x-1] <= step: #L
add('L')
x = x-1
elif x < m-1 and res[y][x+1] <= step: #R
add('R')
x = x+1
elif y > 0 and res[y-1][x] <= step: #U
add('U')
y = y-1
else:
print('IMPOSSIBLE')
sys.exit()
print(str.join('', path))
``` | output | 1 | 11,292 | 15 | 22,585 |
Provide tags and a correct Python 3 solution for this coding contest problem.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles. | instruction | 0 | 11,293 | 15 | 22,586 |
Tags: *special, dfs and similar, graphs, greedy, shortest paths
Correct Solution:
```
#https://codeforces.com/contest/769/problem/C
import collections
lis = input().split()
n,m,k = int(lis[0]),int(lis[1]),int(lis[2])
empty = [[False for i in range(m)] for j in range(n)]
mainrow,maincol = 0,0
for i in range(n):
s = input()
for j in range(m):
if(s[j]=='.'):
empty[i][j] = True
elif (s[j]=='X'):
empty[i][j] = True
mainrow = i
maincol = j
d = [[-1 for i in range(m)] for j in range(n)]
que = collections.deque([(mainrow,maincol)])
d[mainrow][maincol] = 0
changes = [(1,0),(-1,0),(0,1),(0,-1)]
while(que):
(x,y) = que.popleft()
for (i,j) in changes:
xnex = x+i
ynex = y+j
if(xnex>=0 and xnex<n and ynex>=0 and ynex<m and empty[xnex][ynex] and d[xnex][ynex]==-1):
d[xnex][ynex]=d[x][y]+1
que.append((xnex,ynex))
currrow = mainrow
currcol = maincol
lis = []
if(k%2==0):
flag = False
for (i,j) in changes:
xnex = mainrow+i
ynex = maincol+j
if(xnex>=0 and xnex<n and ynex>=0 and ynex<m and empty[xnex][ynex]):
flag = True
if(flag):
while(k):
if(currrow+1<n and empty[currrow+1][currcol] and d[currrow+1][currcol]<k):
lis.append('D')
currrow+=1
elif(currcol-1>=0 and empty[currrow][currcol-1] and d[currrow][currcol-1]<k):
lis.append('L')
currcol-=1
elif(currcol+1<m and empty[currrow][currcol+1] and d[currrow][currcol+1]<k):
lis.append('R')
currcol+=1
else:
lis.append('U')
currrow-=1
k-=1
if(currcol == maincol and currrow == mainrow):
print("".join(lis))
else:
print("IMPOSSIBLE WHY")
else:
print("IMPOSSIBLE")
else:
print("IMPOSSIBLE")
``` | output | 1 | 11,293 | 15 | 22,587 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
Submitted Solution:
```
raw = input()
raw = raw.split(' ')
n = int(raw[0])
m = int(raw[1])
k = int(raw[2])
trip_half = int(k/2)
result = ""
maze = [] # [row[col]]
# populate the maze and find position of X
x_col = 0 # x
x_row = 0 # y
temp_iter = 0
while temp_iter < n:
temp = input()
for i in range(m):
if (temp[i] == "X"):
x_col = i
x_row = temp_iter
maze.append(temp)
temp_iter += 1
# start exploring possible paths
current_col = x_col
current_row = x_row
while trip_half > 0 :
if current_row + 1 < n and maze[current_row + 1][current_col] == ".": # check down
result+="D"
current_row = current_row + 1
trip_half -= 1
elif current_col - 1 >= 0 and maze[current_row][current_col - 1] == ".": # check left
result+="L"
current_col = current_col - 1
trip_half -= 1
elif current_col + 1 < m and maze[current_row][current_col + 1] == ".": # check right
result+="R"
current_col = current_col + 1
trip_half -= 1
elif current_row - 1 >= 0 and maze[current_row - 1][current_col] == ".": # check up
result+="U"
current_row = current_row - 1
trip_half -= 1
else:
print("IMPOSSIBLE")
quit()
trip_half = int(k/2)
for i in range(trip_half - 1, -1, -1):
if result[i] == 'D':
result+='U'
elif result[i] == 'U':
result+='D'
elif result[i] == 'L':
result+='R'
else:
result+='L'
print(result)
``` | instruction | 0 | 11,294 | 15 | 22,588 |
No | output | 1 | 11,294 | 15 | 22,589 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
Submitted Solution:
```
def list_from_input(type=int):
return list(map(int, input().split()))
def read():
return eval(input())
def reversed_string(a_string):
return a_string[::-1]
def no_answer():
print("IMPOSSIBLE")
# i - row index
# j - col index
class Point2D:
def __init__(self, i, j):
self.i = i
self.j = j
def can_step(self, step, maze, maze_size):
new_i = self.i + step[0]
new_j = self.j + step[1]
good_i = 0 <= new_i < maze_size[0]
good_j = 0 <= new_j < maze_size[1]
if good_i and good_j:
return maze[new_i][new_j] is '.'
else:
return False
def step(self, step):
self.i += step[0]
self.j += step[1]
def main():
n, m, k = list_from_input()
maze = [None] * n
for i in range(n):
maze[i] = input()
# Solution idea
# Step by indices
steps = [(+1, 0), (0, -1), (0, +1), (-1, 0)]
costs = ['D', 'L', 'R', 'U']
# Find robot location
robot = None
for i in range(n):
for j in range(m):
if maze[i][j] is 'X':
robot = Point2D(i, j)
break
maze_size = (n, m)
path = []
if k % 2 != 0:
no_answer()
return
while len(path) < k // 2:
for i, step in enumerate(steps):
if robot.can_step(step, maze, maze_size):
robot.step(step)
path.append(i)
break
elif i == 3:
no_answer()
return
back_path = []
for i in reversed_string(path):
back_path.append(3 - i)
complete_path = path + back_path
for i in complete_path:
print(costs[i], end='')
main()
``` | instruction | 0 | 11,295 | 15 | 22,590 |
No | output | 1 | 11,295 | 15 | 22,591 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
Submitted Solution:
```
from collections import deque
n, m, k = [int(x) for x in input().split()]
matrix = []
for _ in range(n):
row = list(input())
matrix.append(row)
def solve(n, m, k, matrix):
directions = {
'D': [1, 0],
'L': [0, -1],
'R': [0, 1],
'U': [-1, 0]
}
if k % 2 == 1:
return "IMPOSSIBLE"
MAX_DISTANCE = n * m + 1
distances = [[MAX_DISTANCE] * m for _ in range(n)]
start_i = -1
start_j = -1
start_found = False
for i in range(n):
for j in range(m):
if matrix[i][j] == 'X':
start_found = True
start_i = i
start_j = j
break
if start_found:
break
queue = deque()
# add to q tuples (i, j, d) where d is distance
queue.appendleft((start_i, start_j, 0))
while queue:
i, j, d = queue.pop()
distances[i][j] = d
for key in directions:
dx, dy = directions[key]
if d < k // 2 + 1 and 0 <= i + dx < n and 0 <= j + dy < m and matrix[i + dx][j + dy] == '.' and \
d + 1 < distances[i + dx][j + dy]:
queue.appendleft((i + dx, j + dy, d + 1))
answer = []
current_i = start_i
current_j = start_j
while k > 0:
k -= 1
for key in directions:
dx, dy = directions[key]
if 0 <= current_i + dx < n and 0 <= current_j + dy < m and distances[current_i + dx][current_j + dy] <= k:
answer.append(key)
current_i = current_i + dx
current_j = current_j + dy
break
else:
return "IMPOSSIBLE"
return ''.join(answer)
print(solve(n, m, k, matrix))
``` | instruction | 0 | 11,296 | 15 | 22,592 |
No | output | 1 | 11,296 | 15 | 22,593 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The Robot is in a rectangular maze of size n × m. Each cell of the maze is either empty or occupied by an obstacle. The Robot can move between neighboring cells on the side left (the symbol "L"), right (the symbol "R"), up (the symbol "U") or down (the symbol "D"). The Robot can move to the cell only if it is empty. Initially, the Robot is in the empty cell.
Your task is to find lexicographically minimal Robot's cycle with length exactly k, which begins and ends in the cell where the Robot was initially. It is allowed to the Robot to visit any cell many times (including starting).
Consider that Robot's way is given as a line which consists of symbols "L", "R", "U" and "D". For example, if firstly the Robot goes down, then left, then right and up, it means that his way is written as "DLRU".
In this task you don't need to minimize the length of the way. Find the minimum lexicographical (in alphabet order as in the dictionary) line which satisfies requirements above.
Input
The first line contains three integers n, m and k (1 ≤ n, m ≤ 1000, 1 ≤ k ≤ 106) — the size of the maze and the length of the cycle.
Each of the following n lines contains m symbols — the description of the maze. If the symbol equals to "." the current cell is empty. If the symbol equals to "*" the current cell is occupied by an obstacle. If the symbol equals to "X" then initially the Robot is in this cell and it is empty. It is guaranteed that the symbol "X" is found in the maze exactly once.
Output
Print the lexicographically minimum Robot's way with the length exactly k, which starts and ends in the cell where initially Robot is. If there is no such way, print "IMPOSSIBLE"(without quotes).
Examples
Input
2 3 2
.**
X..
Output
RL
Input
5 6 14
..***.
*...X.
..*...
..*.**
....*.
Output
DLDDLLLRRRUURU
Input
3 3 4
***
*X*
***
Output
IMPOSSIBLE
Note
In the first sample two cyclic ways for the Robot with the length 2 exist — "UD" and "RL". The second cycle is lexicographically less.
In the second sample the Robot should move in the following way: down, left, down, down, left, left, left, right, right, right, up, up, right, up.
In the third sample the Robot can't move to the neighboring cells, because they are occupied by obstacles.
Submitted Solution:
```
n, m, k = map(int, input().split())
if k % 2 != 0:
print('IMPOSSIBLE')
labyrinth = []
for i in range(n):
labyrinth.append([])
letter = input()
for j in range(m):
if letter[j] == '*':
labyrinth[i].append(1)
elif letter[j] == '.':
labyrinth[i].append(0)
elif letter[j] == 'X':
labyrinth[i].append(0)
start_x, start_y = j, i
commands = 'DLRU'
answer = ''
now_x, now_y = start_x, start_y
for i in range(k // 2):
for j in commands:
if j == 'D':
if now_y + 1 == n or labyrinth[now_y+1][now_x] == 1:
continue
else:
now_y += 1
answer += 'D'
break
elif j == 'L':
if now_x == 0 or labyrinth[now_y][now_x-1] == 1:
continue
else:
now_x -= 1
answer += 'L'
break
elif j == 'R':
if now_x + 1 == m or labyrinth[now_y][now_x+1] == 1:
continue
else:
now_x += 1
answer += 'R'
break
elif j == 'U':
if now_y == 0 or labyrinth[now_y-1][now_x] == 1:
continue
else:
now_y -= 1
answer += 'U'
break
else:
print('IMPOSSIBLE')
break
else:
invert = ''
for i in answer[::-1]:
if i == 'D':
invert += 'U'
if i == 'L':
invert += 'R'
if i == 'R':
invert += 'L'
if i == 'U':
invert += 'D'
print(answer+invert)
``` | instruction | 0 | 11,297 | 15 | 22,594 |
No | output | 1 | 11,297 | 15 | 22,595 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We have a square grid with N rows and M columns. Takahashi will write an integer in each of the squares, as follows:
* First, write 0 in every square.
* For each i=1,2,...,N, choose an integer k_i (0\leq k_i\leq M), and add 1 to each of the leftmost k_i squares in the i-th row.
* For each j=1,2,...,M, choose an integer l_j (0\leq l_j\leq N), and add 1 to each of the topmost l_j squares in the j-th column.
Now we have a grid where each square contains 0, 1, or 2. Find the number of different grids that can be made this way, modulo 998244353. We consider two grids different when there exists a square with different integers.
Constraints
* 1 \leq N,M \leq 5\times 10^5
* N and M are integers.
Input
Input is given from Standard Input in the following format:
N M
Output
Print the number of different grids that can be made, modulo 998244353.
Examples
Input
1 2
Output
8
Input
2 3
Output
234
Input
10 7
Output
995651918
Input
314159 265358
Output
70273732
Submitted Solution:
```
def p(i):
ans = 1
while i != 1:
ans *= i
i -= 1
return ans
def comb_dp_sub(n, r):
global comb_table
if r == 0 or n == r:
return 1
else:
return comb_table[n - 1][r] + comb_table[n - 1][r - 1]
def comb_dp(n, r):
global comb_table
comb_table = [[0] * (n + 1) for _ in range(n + 1)]
for i in range(n + 1):
for j in range(i + 1):
comb_table[i][j] = comb_dp_sub(i, j)
return comb_table[n][r]
n,m = map(int, input().split())
st = ((n+1)**m) * ((m+1)**n)
general = 0
for i in range(1,min(n,m)+1):
general += comb_dp(n,i) * comb_dp(m,i) * p(i)
print(st - general)
``` | instruction | 0 | 12,332 | 15 | 24,664 |
No | output | 1 | 12,332 | 15 | 24,665 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,333 | 15 | 24,666 |
"Correct Solution:
```
h,w = map(int,input().split())
lst = [list(map(int,input().split())) for _ in range(h)]
cnt = 0
ans = []
for i in range(h):
for j in range(w-1):
if lst[i][j] %2 == 1:
lst[i][j] -= 1
lst[i][j+1] += 1
ans.append([i+1,j+1,i+1,j+2])
for i in range(h-1):
if lst[i][-1] %2 == 1:
lst[i][-1] -= 1
lst[i+1][-1] += 1
ans.append([i+1,w,i+2,w])
print(len(ans))
for a in ans:
print(*a)
``` | output | 1 | 12,333 | 15 | 24,667 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,334 | 15 | 24,668 |
"Correct Solution:
```
h, w = map(int, input().split())
A = [[int(i) for i in input().split()] for i in range(h)]
B = []
count = 0
for i in range(h):
for j in range(w-1):
if A[i][j] % 2 == 1:
count += 1
A[i][j+1] += 1
B.append([i+1, j+1, i+1, j+2])
for i in range(h-1):
if A[i][-1] % 2 == 1:
count += 1
A[i+1][-1] += 1
B.append([i+1, w, i+2, w])
print(count)
for b in B:
print(b[0], b[1], b[2], b[3])
``` | output | 1 | 12,334 | 15 | 24,669 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,335 | 15 | 24,670 |
"Correct Solution:
```
def f(i,w):
p = i%w
q = i//w
if q%2 == 1:
p = w-1-p
return [q,p]
h,w = map(int,input().split())
a = [[]]*h
for i in range(h):
a[i] = list(map(int,input().split()))
k = 0
s = []
for i in range(h*w-1):
if a[f(i,w)[0]][f(i,w)[1]]%2 == 1:
k = 1-k
if k == 1:
s += [f(i,w)[0],f(i,w)[1],f(i+1,w)[0],f(i+1,w)[1]]
m = len(s)//4
print(m)
for i in range(m):
print(s[4*i]+1,s[4*i+1]+1,s[4*i+2]+1,s[4*i+3]+1)
``` | output | 1 | 12,335 | 15 | 24,671 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,336 | 15 | 24,672 |
"Correct Solution:
```
H,W = (int(i) for i in input().split())
a = [[int(i) for i in input().split()] for i in range(H)]
ans = []
ans_list = []
for h in range(H):
for w in range(W):
if w!=W-1:
if a[h][w]%2==1:
a[h][w+1]+=1
ans.append([h+1,w+1,h+1,w+2])
else:
if a[h][w]%2==1 and h!=H-1:
a[h+1][w]+=1
ans.append([h+1,w+1,h+2,w+1])
print(len(ans))
for i in range(len(ans)):
print(*ans[i])
``` | output | 1 | 12,336 | 15 | 24,673 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,337 | 15 | 24,674 |
"Correct Solution:
```
H,W=[int(i) for i in input().split()]
a = [[int(i) for i in input().split()] for j in range(H)]
res = []
for h in range(H):
for w in range(W-1):
if a[h][w] % 2 is not 0:
res += ["{0} {1} {2} {3}".format(h+1,w+1,h+1,w+2)]
a[h][w+1] += 1
for h in range(H-1):
w = W - 1
if a[h][w] % 2 is not 0:
res += ["{0} {1} {2} {3}".format(h+1,w+1,h+2,w+1)]
a[h+1][w]+=1
print(len(res))
for t in res:
print(t)
``` | output | 1 | 12,337 | 15 | 24,675 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,338 | 15 | 24,676 |
"Correct Solution:
```
H,W=map(int,input().split())
a=[list(map(int,input().split())) for i in range(H)]
A=[]
for y in range(H):
for x in range(W):
if y%2==0:
A.append([y,x,a[y][x]])
else:
A.append([y,W-1-x,a[y][W-1-x]])
OUTPUT=[]
for i in range(H*W-1):
if A[i][2]%2==1:
OUTPUT.append((A[i][0]+1,A[i][1]+1,A[i+1][0]+1,A[i+1][1]+1))
A[i+1][2]+=1
print(len(OUTPUT))
for out in OUTPUT:
print(*out)
``` | output | 1 | 12,338 | 15 | 24,677 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,339 | 15 | 24,678 |
"Correct Solution:
```
h, w = list(map(int, input().split()))
a = [list(map(int, input().split())) for i in range(h)]
ans = []
for i in range(h):
for j in range(w):
if i==h-1 and j==w-1:
pass
elif j==w-1 and a[i][j]%2==1:
a[i+1][j] += 1
ans.append((i+1, j+1, i+2, j+1))
elif a[i][j]%2==1:
a[i][j+1] += 1
ans.append((i+1, j+1, i+1, j+2))
print(len(ans))
for e in ans:
print(*e)
``` | output | 1 | 12,339 | 15 | 24,679 |
Provide a correct Python 3 solution for this coding contest problem.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4 | instruction | 0 | 12,340 | 15 | 24,680 |
"Correct Solution:
```
H, W = map(int, input().split())
A = [list(map(int, input().split())) for _ in range(H)]
cnt = 0
path = []
for h in range(H):
for w in range(W-1):
if A[h][w]%2:
A[h][w+1] += 1
cnt += 1
path.append((h+1, w+1, h+1, w+2))
for h in range(H-1):
if A[h][-1]%2:
A[h+1][-1] += 1
cnt += 1
path.append((h+1, W, h+2, W))
print(cnt)
for p in path:
print(*p)
``` | output | 1 | 12,340 | 15 | 24,681 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
h,w=map(int,input().split())
a=[]
for _ in range(h):
a.append(list(map(int, input().split())))
ans=[]
cnt=0
for i in range(h):
for j in range(w-1):
if a[i][j]%2==1:
a[i][j+1]+=1
a[i][j]-=1
cnt+=1
ans.append((i+1,j+1,i+1,j+2))
for i in range(h-1):
if a[i][w-1]%2==1:
a[i][w-1]-=1
a[i+1][w-1]+=1
cnt+=1
ans.append((i+1,w,i+2,w))
print(cnt)
for i,j,k,l in ans:
print(i,j,k,l)
``` | instruction | 0 | 12,341 | 15 | 24,682 |
Yes | output | 1 | 12,341 | 15 | 24,683 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
H,W = map(int,input().split())
A = [list(map(int,input().split())) for _ in range(H)]
#print(A)
ans = []
for i in range(H):
for j in range(W-1):
if A[i][j] % 2 == 1:
A[i][j] -= 1
A[i][j+1] += 1
ans.append([i+1,j+1,i+1,j+2])
for i in range(H-1):
if A[i][W-1] % 2 == 1:
A[i][W-1] -= 1
A[i+1][W-1] += 1
ans.append([i+1,W,i+2,W])
print(len(ans))
for a in ans:
print(*a)
``` | instruction | 0 | 12,342 | 15 | 24,684 |
Yes | output | 1 | 12,342 | 15 | 24,685 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
H,W=[int(s) for s in input().split()]
ls=[[int(s) for s in input().split()] for i in range(H)]
ans=[]
#まず各列ごとに右に寄せる
for i in range(H):
for j in range(W-1):
if ls[i][j]%2==1:
ans.append([i+1,j+1,i+1,j+2])
ls[i][j+1]+=1
#一番右の列を下に寄せる
for i in range(H-1):
if ls[i][W-1]%2==1:
ans.append([i+1, W, i+2, W])
ls[i+1][W-1]+=1
print(len(ans))
for e in ans:
print(*e)
``` | instruction | 0 | 12,343 | 15 | 24,686 |
Yes | output | 1 | 12,343 | 15 | 24,687 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
def solve():
t,*a=open(0)
h,w=map(int,t.split())
a=[[int(x)%2 for x in y.split()] for y in a]
ret=[]
for i in range(h):
for j in range(w-1):
if a[i][j]:
a[i][j+1]^=1
ret+=[" ".join(map(str,[i+1,j+1,i+1,j+2]))]
for i in range(h-1):
if a[i][-1]:
a[i+1][-1]^=1
ret+=[" ".join(map(str,[i+1,w,i+2,w]))]
print(len(ret),*ret,sep="\n")
if __name__=="__main__":
solve()
``` | instruction | 0 | 12,344 | 15 | 24,688 |
Yes | output | 1 | 12,344 | 15 | 24,689 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
def solve(string):
ins = string.split("\n")
h, w = map(int, ins[0].split(" "))
a = [list(map(lambda x: int(x) % 2, _i.split(" "))) for _i in ins[1:]]
move = []
for j in range(h):
for i in range(w):
a[j][i] -= 1
if i < w - 1:
a[j][i + 1] += 1
move.append("{} {} {} {}".format(j + 1, i + 1, j + 1, i + 2))
elif j < h - 1:
a[j + 1][i] += 1
move.append("{} {} {} {}".format(j + 1, i + 1, j + 2, i + 1))
return "{}\n{}".format(len(move), "\n".join(move))
if __name__ == '__main__':
line = input()
tmp = [line]
for _ in range(int(line[0])):
tmp.append(input())
print(solve('\n'.join(tmp)))
``` | instruction | 0 | 12,345 | 15 | 24,690 |
No | output | 1 | 12,345 | 15 | 24,691 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
h, w = map(int, input().split())
a = [list(map(int, input().split())) for i in range(h)]
c = []
hold = False
for y in range(h):
for x in list(range(w))[::-1+(y % 2 == 0)*2]:
# print((y + 1, x + 1))
if hold:
c.append((*back, y + 1, x + 1))
if a[y][x] % 2 == 1:
hold = False
continue
if not hold and a[y][x] % 2 == 1:
hold = True
back = (y + 1, x + 1)
print(len(c))
for i in range(len(c)):
print(*c[i])
``` | instruction | 0 | 12,346 | 15 | 24,692 |
No | output | 1 | 12,346 | 15 | 24,693 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
import sys, os
f = lambda:list(map(int,input().split()))
if 'local' in os.environ :
sys.stdin = open('./input.txt', 'r')
def solve():
h,w = f()
g = [ f() for i in range(h)]
cnt = 0
ans = []
for i in range(h):
for j in range(w):
if g[i][j]%2 == 0:
continue
else:
if (j+1<w and g[i][j+1]%2 == 1) or i+1 == h:
g[i][j+1] += 1
cnt+=1
ans += [(i+1, j+1, i+1, j+1+1)]
elif i+1<h:
g[i+1][j] += 1
cnt+=1
ans += [(i+1, j+1, i+2, j+1)]
print(cnt)
for i in ans:
print(i[0], i[1], i[2], i[3])
solve()
``` | instruction | 0 | 12,347 | 15 | 24,694 |
No | output | 1 | 12,347 | 15 | 24,695 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a grid of square cells with H horizontal rows and W vertical columns. The cell at the i-th row and the j-th column will be denoted as Cell (i, j).
In Cell (i, j), a_{ij} coins are placed.
You can perform the following operation any number of times:
Operation: Choose a cell that was not chosen before and contains one or more coins, then move one of those coins to a vertically or horizontally adjacent cell.
Maximize the number of cells containing an even number of coins.
Constraints
* All values in input are integers.
* 1 \leq H, W \leq 500
* 0 \leq a_{ij} \leq 9
Input
Input is given from Standard Input in the following format:
H W
a_{11} a_{12} ... a_{1W}
a_{21} a_{22} ... a_{2W}
:
a_{H1} a_{H2} ... a_{HW}
Output
Print a sequence of operations that maximizes the number of cells containing an even number of coins, in the following format:
N
y_1 x_1 y_1' x_1'
y_2 x_2 y_2' x_2'
:
y_N x_N y_N' x_N'
That is, in the first line, print an integer N between 0 and H \times W (inclusive), representing the number of operations.
In the (i+1)-th line (1 \leq i \leq N), print four integers y_i, x_i, y_i' and x_i' (1 \leq y_i, y_i' \leq H and 1 \leq x_i, x_i' \leq W), representing the i-th operation. These four integers represents the operation of moving one of the coins placed in Cell (y_i, x_i) to a vertically or horizontally adjacent cell, (y_i', x_i').
Note that if the specified operation violates the specification in the problem statement or the output format is invalid, it will result in Wrong Answer.
Examples
Input
2 3
1 2 3
0 1 1
Output
3
2 2 2 3
1 1 1 2
1 3 1 2
Input
3 2
1 0
2 1
1 0
Output
3
1 1 1 2
1 2 2 2
3 1 3 2
Input
1 5
9 9 9 9 9
Output
2
1 1 1 2
1 3 1 4
Submitted Solution:
```
H,W=map(int,input().split())
a=[]
place=[]
doubleN=0
for i in range(H):
a.append(list(map(int,input().split())))
for j in range(W):
if a[i][j]%2==1:
doubleN+=1
place.append([i+1,j+1])
count=0
answer=0
anslist=[]
while(count!=(doubleN//2)):
if place[2*count][0]==place[2*count+1][0] and place[2*count][1]==place[2*count+1][1]:
count+=1
continue;
answer+=1
if place[2*count][0]==place[2*count+1][0]:
if place[2*count][1]<place[2*count+1][1]:
anslist.append([place[2*count][0],place[2*count][1],place[2*count][0],place[2*count][1]+1])
place[2*count][1]+=1
continue;
else:
anslist.append([place[2*count][0],place[2*count][1],place[2*count][0],place[2*count][1]-1])
place[2*count][1]-=1
continue;
else:
anslist.append([place[2*count][0],place[2*count][1],place[2*count][0]+1,place[2*count][1]])
place[2*count][0]+=1
continue;
print(answer)
for i in range(len(anslist)):
print(anslist[i][0],anslist[i][1],anslist[i][2],anslist[i][3])
``` | instruction | 0 | 12,348 | 15 | 24,696 |
No | output | 1 | 12,348 | 15 | 24,697 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21 | instruction | 0 | 12,381 | 15 | 24,762 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
INF = 10**12
class Rmin():
def __init__(self, size):
#the number of nodes is 2n-1
self.n = 1 << (size.bit_length())
self.node = [INF] * (2*self.n-1)
def Access(self, x):
return self.node[x+self.n-1]
def Update(self, x, val):
x += self.n-1
self.node[x] = val
while x > 0:
x = (x-1)>>1
self.node[x] = min(self.node[(x<<1)+1], self.node[(x<<1)+2])
return
#[l, r)
def Get(self, l, r):
L, R = l+self.n, r+self.n
s = INF
while L<R:
if R & 1:
R -= 1
s = min(s, self.node[R-1])
if L & 1:
s = min(s, self.node[L-1])
L += 1
L >>= 1
R >>= 1
return s
n, q, a, b, *qs = map(int, read().split())
dp_l, dp_r = Rmin(n+1), Rmin(n+1)
dp_l.Update(b, -b)
dp_r.Update(b, b)
total_diff = 0
x = a
for y in qs:
diff = abs(y - x)
l_min = dp_l.Get(1, y)
r_min = dp_r.Get(y, n+1)
res = min(l_min + y, r_min - y)
dp_l.Update(x, res - diff - x)
dp_r.Update(x, res - diff + x)
total_diff += diff
x = y
N = dp_l.n
print(total_diff + min((l+r)>>1 for l, r in zip(dp_l.node[N:], dp_r.node[N:])))
``` | output | 1 | 12,381 | 15 | 24,763 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21 | instruction | 0 | 12,382 | 15 | 24,764 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,Q,A,B,*X = map(int,read().split())
class MinSegTree():
def __init__(self,N):
self.Nelem = N
self.size = 1<<(N.bit_length()) # 葉の要素数
def build(self,raw_data):
# raw_data は 0-indexed
INF = 10**18
self.data = [INF] * (2*self.size)
for i,x in enumerate(raw_data):
self.data[self.size+i] = x
for i in range(self.size-1,0,-1):
x = self.data[i+i]; y = self.data[i+i+1]
self.data[i] = x if x<y else y
def update(self,i,x):
i += self.size
self.data[i] = x
i >>= 1
while i:
x = self.data[i+i]; y = self.data[i+i+1]
self.data[i] = x if x<y else y
i >>= 1
def get_value(self,L,R):
# [L,R] に対する値を返す
L += self.size
R += self.size + 1
# [L,R) に変更
x = 10**18
while L < R:
if L&1:
y = self.data[L]
if x > y: x = y
L += 1
if R&1:
R -= 1
y = self.data[R]
if x > y: x = y
L >>= 1; R >>= 1
return x
INF = 10**18
dpL = MinSegTree(N+10); dpL.build([INF] * (N+10))
dpR = MinSegTree(N+10); dpR.build([INF] * (N+10))
dpL.update(A,0-A)
dpR.update(A,0+A)
prev_x = B
add = 0
for x in X:
from_left = dpL.get_value(0,x) + x
from_right = dpR.get_value(x,N+10) - x
dist = x-prev_x if x>prev_x else prev_x-x
y = from_left if from_left < from_right else from_right
y -= dist
dpL.update(prev_x,y-prev_x)
dpR.update(prev_x,y+prev_x)
add += dist
prev_x = x
dp = [(x+y)//2 for x,y in zip(dpL.data[dpL.size:],dpR.data[dpR.size:])]
answer = min(dp) + add
print(answer)
``` | output | 1 | 12,382 | 15 | 24,765 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21
Submitted Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N,Q,A,B,*X = map(int,read().split())
class MinSegTree():
def __init__(self,N):
self.Nelem = N
self.size = 1<<(N.bit_length()) # 葉の要素数
def build(self,raw_data):
# raw_data は 0-indexed
INF = 10**18
self.data = [INF] * (2*self.size)
for i,x in enumerate(raw_data):
self.data[self.size+i] = x
for i in range(self.size-1,0,-1):
x = self.data[i+i]; y = self.data[i+i+1]
self.data[i] = x if x<y else y
def update(self,i,x):
i += self.size
self.data[i] = x
i >>= 1
while i:
x = self.data[i+i]; y = self.data[i+i+1]
self.data[i] = x if x<y else y
i >>= 1
def get_value(self,L,R):
# [L,R] に対する値を返す
L += self.size
R += self.size + 1
# [L,R) に変更
x = 10**18
while L < R:
if L&1:
y = self.data[L]
if x > y: x = y
L += 1
if R&1:
R -= 1
y = self.data[R]
if x > y: x = y
L >>= 1; R >>= 1
return x
INF = 10**18
dpL = MinSegTree(N+10); dpL.build([INF] * (N+10))
dpR = MinSegTree(N+10); dpR.build([INF] * (N+10))
dpL.update(A,0-A)
dpR.update(A,0+A)
prev_x = B
add = 0
for x in X:
from_left = dpL.get_value(0,x) + x
from_right = dpR.get_value(x,N+10) - x
dist = x-prev_x if x>prev_x else prev_x-x
y = from_left if from_left < from_right else from_right
y -= dist
dpL.update(prev_x,y-prev_x)
dpR.update(prev_x,y+prev_x)
add += dist
prev_x = x
dp = [(x+y)//2 for x,y in zip(dpL.data[dpL.size:],dpR.data[dpR.size:])]
answer = min(dp) + add
print(answer)
``` | instruction | 0 | 12,383 | 15 | 24,766 |
No | output | 1 | 12,383 | 15 | 24,767 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21
Submitted Solution:
```
INF = 10**15
class Rmin():
def __init__(self, size):
#the number of nodes is 2n-1
self.n = 1
while self.n < size:
self.n *= 2
self.node = [INF] * (2*self.n-1)
def Access(self, x):
return self.node[x+self.n-1]
def Update(self, x, val):
x += self.n-1
self.node[x] = val
while x > 0:
x = (x-1)//2
self.node[x] = min(self.node[2*x+1], self.node[2*x+2])
return
#[l, r)
def Get(self, l, r):
L, R = l+self.n, r+self.n
s = INF
while L<R:
if R & 1:
R -= 1
s = min(s, self.node[R-1])
if L & 1:
s = min(s, self.node[L-1])
L += 1
L >>= 1
R >>= 1
return s
n, q, a, b = map(int, input().split())
qs = [a] + list(map(int, input().split()))
dp_l, dp_r = Rmin(n+1), Rmin(n+1)
dp_l.Update(b, -b)
dp_r.Update(b, b)
total_diff = 0
for i in range(q):
x, y = qs[i], qs[i+1]
diff = abs(y - x)
l_min = dp_l.Get(1, y)
r_min = dp_r.Get(y, n+1)
res = min(l_min + y, r_min - y)
dp_l.Update(x, res - diff - x)
dp_r.Update(x, res - diff + x)
total_diff += diff
ans_l, ans_r = INF, INF
for i in range(1, n+1):
ans_l = min(ans_l, dp_l.Access(i) + i)
ans_r = min(ans_r, dp_r.Access(i) - i)
print(ans_l + total_diff)
``` | instruction | 0 | 12,384 | 15 | 24,768 |
No | output | 1 | 12,384 | 15 | 24,769 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21
Submitted Solution:
```
#####segfunc#####
def segfunc(x, y):
return (min(x[0],y[0]),min(x[1],y[1]))
#################
#####ide_ele#####
ide_ele = (10**20,10**20)
#################
class SegTree:
"""
init(init_val, ide_ele): 配列init_valで初期化 O(N)
update(k, x): k番目の値をxに更新 O(logN)
query(l, r): 区間[l, r)をsegfuncしたものを返す O(logN)
"""
def __init__(self, n,segfunc, ide_ele):
"""
init_val: 配列の初期値
segfunc: 区間にしたい操作
ide_ele: 単位元
n: 要素数
num: n以上の最小の2のべき乗
tree: セグメント木(1-index)
"""
self.segfunc = segfunc
self.ide_ele = ide_ele
self.num = 1 << (n - 1).bit_length()
self.tree = [ide_ele] * 2 * self.num
# 構築していく
for i in range(self.num - 1, 0, -1):
self.tree[i] = self.segfunc(self.tree[2 * i], self.tree[2 * i + 1])
def update(self, k, x):
"""
k番目の値をxに更新
k: index(0-index)
x: update value
"""
k += self.num
self.tree[k] =self.segfunc(self.tree[k],x)
while k > 1:
self.tree[k >> 1] = self.segfunc(self.tree[k], self.tree[k ^ 1])
k >>= 1
def query(self, l, r):
"""
[l, r)のsegfuncしたものを得る
l: index(0-index)
r: index(0-index)
"""
res = self.ide_ele
l += self.num
r += self.num
while l < r:
if l & 1:
res = self.segfunc(res, self.tree[l])
l += 1
if r & 1:
res = self.segfunc(res, self.tree[r - 1])
l >>= 1
r >>= 1
return res
import random
def main():
N,Q,A,B=map(int,input().split())
x=list(map(int,input().split()))
Sx=[abs(x[0]-A)]
Sy=[abs(x[0]-B)]
for i in range(1,Q):
Sx.append(abs(x[i]-x[i-1]))
Sy.append(abs(x[i]-x[i-1]))
for i in range(1,Q):
Sx[i]+=Sx[i-1]
Sy[i]+=Sy[i-1]
rmqx=SegTree(N+1,segfunc,ide_ele)
rmqy=SegTree(N+1,segfunc,ide_ele)
dpx=Sx[0]
dpy=Sy[0]
test1=Sx[Q-1]
test2=Sy[Q-1]
rmqx.update(A,(-A,A))
rmqy.update(B,(-B,B))
for i in range(2,Q+1):
testx1=rmqx.query(0,x[i-1])[0]+x[i-1]+Sy[i-2]
testx2=rmqx.query(x[i-1],N+1)[1]-x[i-1]+Sy[i-2]
dpx=min(testx2,testx1)
testy1=rmqy.query(0,x[i-1])[0]+x[i-1]+Sx[i-2]
testy2=rmqy.query(x[i-1],N+1)[1]-x[i-1]+Sx[i-2]
dpy=min(testy2,testy1)
rmqx.update(x[i-2],(dpy-Sy[i-1]-x[i-2],dpy-Sy[i-1]+x[i-2]))
rmqy.update(x[i-2],(dpx-Sx[i-1]-x[i-2],dpx-Sx[i-1]+x[i-2]))
test1=min(test1,dpx+Sx[Q-1]-Sx[i-1])
test2=min(test2,dpy+Sy[Q-1]-Sy[i-1])
print(min(test1,test2))
if __name__=="__main__":
main()
``` | instruction | 0 | 12,385 | 15 | 24,770 |
No | output | 1 | 12,385 | 15 | 24,771 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares in a row. The squares are numbered 1, 2, ..., N from left to right.
You have two pieces, initially placed on square A and B, respectively. You will be asked to process Q queries of the following kind, in the order received:
* Given an integer x_i, move one of the two pieces of your choice to square x_i.
Here, it takes you one second to move a piece one square. That is, the time it takes to move a piece from square X to Y is |X-Y| seconds.
Your objective is to process all the queries in the shortest possible time.
You may only move the pieces in response to queries, and you may not move both pieces at the same time. Also, it is not allowed to rearrange the order in which queries are given. It is, however, allowed to have both pieces in the same square at the same time.
Constraints
* 1 ≤ N, Q ≤ 200,000
* 1 ≤ A, B ≤ N
* 1 ≤ x_i ≤ N
Input
Input is given from Standard Input in the following format:
N Q A B
x_1 x_2 ... x_Q
Output
Let the shortest possible time to process all the queries be X seconds. Print X.
Examples
Input
8 3 1 8
3 5 1
Output
7
Input
9 2 1 9
5 1
Output
4
Input
9 2 1 9
5 9
Output
4
Input
11 16 8 1
1 1 5 1 11 4 5 2 5 3 3 3 5 5 6 7
Output
21
Submitted Solution:
```
class MinSegTree:
def __init__(self, initial_data):
initial_data = list(initial_data)
self.original_size = len(initial_data)
self.depth = (len(initial_data)-1).bit_length()
self.size = 1 << self.depth
self.data = [0]*self.size + initial_data + [0]*(self.size - len(initial_data))
self.offset = 0
for d in reversed(range(self.depth)):
a = 1 << d
b = a << 1
for i in range(a,b):
self.data[i] = min(self.data[2*i],self.data[2*i+1])
def _min_interval(self, a, b):
def rec(i, na, nb):
if b <= na or nb <= a:
return float('inf')
if a <= na and nb <= b:
return self.data[i]
split = (na+nb)//2
return min(rec(2*i, na, split), rec(2*i+1, split, nb))
return rec(1, 0, self.size)
def _set_val(self, a, val):
def rec(i, na, nb):
if na == a == nb-1:
self.data[i] = val
elif na <= a < nb:
split = (na+nb)//2
self.data[i] = min(rec(2*i, na, split), rec(2*i+1, split, nb))
return self.data[i]
rec(1, 0, self.size)
def add_to_all(self, val):
self.offset += val
def __getitem__(self, i):
if isinstance(i, slice):
return self.offset + self._min_interval(
0 if i.start is None else i.start,
self.original_size if i.stop is None else i.stop)
elif isinstance(i, int):
return self.data[i+self.size]+self.offset
def __setitem__(self, i, x):
self._set_val(i,x-self.offset)
def __iter__(self):
def gen():
for x in self.data[self.size:]:
yield x
return gen
"""
dp[i][b] = dp[i-1][b] + |x-a| for all b
dp[i][a] = min(dp[i-1][b] + |x-b| for all b)
= min(dp[i-1][j] - j + x for j = [0,x]), min(dp[i-1][j]+j-x for j = (x,n])
dp[i][j] - j と dp[i][j] + jをセグ木でもつ
"""
N,Q,A,B = map(int,input().split())
t1 = MinSegTree([float('inf')]*N)
t2 = MinSegTree([float('inf')]*N)
A,B = A-1,B-1
a = A
t1[B] = -B
t2[B] = B
for x in map(int, input().split()):
x -= 1
d = abs(x-a)
m = min(t1[:x] + x, t2[x:] - x, (t1[a]+t2[a])//2+d)
t1.add_to_all(d)
t2.add_to_all(d)
t1[a] = m - a
t2[a] = m + a
a = x
print(min(t1[i]+t2[i] for i in range(N))//2)
``` | instruction | 0 | 12,386 | 15 | 24,772 |
No | output | 1 | 12,386 | 15 | 24,773 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall.
In this problem <image> is a remainder of dividing number a by number b.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1500) — the height and the width of the maze that the boy used to cyclically tile the plane.
Each of the next n lines contains m characters — the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point.
The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.
Output
Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).
Examples
Input
5 4
##.#
##S#
#..#
#.##
#..#
Output
Yes
Input
5 4
##.#
##S#
#..#
..#.
#.##
Output
No
Note
In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.
In the second sample the vertical path is blocked. The path to the left doesn't work, too — the next "copy" of the maze traps the boy.
Submitted Solution:
```
from collections import defaultdict
n,m = map(int, input().split())
mat = [list(input()) for _ in range(n)]
vis = defaultdict()
x,y =0,0
for i in range(n):
for j in range(m):
if 'S' in mat[i][j]:
x,y = i,j
mat[i][j]='.'
def safe(i,j):
return i>=0 and j>=0 and i<n and j<m
def dfs(i,j):
try:
if (i%n,j%m) in vis:
return True
vis[(i,j)] =1
vis[(i%n,j%m)]=1
except:
print('fir')
try:
for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]:
x,y = i+di+n, j+dj+m
u,v = (x)%n, (y)%m
if safe(u,v) and '.' == mat[u][v] and (x,y) not in vis and dfs(x,y):
return True
return False
except:
print(i,j)
print('Yes' if dfs(x,y) else 'No')
``` | instruction | 0 | 12,728 | 15 | 25,456 |
No | output | 1 | 12,728 | 15 | 25,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall.
In this problem <image> is a remainder of dividing number a by number b.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1500) — the height and the width of the maze that the boy used to cyclically tile the plane.
Each of the next n lines contains m characters — the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point.
The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.
Output
Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).
Examples
Input
5 4
##.#
##S#
#..#
#.##
#..#
Output
Yes
Input
5 4
##.#
##S#
#..#
..#.
#.##
Output
No
Note
In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.
In the second sample the vertical path is blocked. The path to the left doesn't work, too — the next "copy" of the maze traps the boy.
Submitted Solution:
```
from collections import defaultdict,deque
n,m = map(int, input().split())
mat = [input() for _ in range(n)]
vis = defaultdict()
def dfs(i,j):
q = deque()
q.append((i,j))
while q:
i,j = q.popleft()
u,v = (i%n+n)%n, (j%n+m)%m
if mat[u][v] == '#' or (i,j) in vis:
continue
if (u,v) in vis:
return True
vis[(i,j)]=1
vis[(u,v)]=1
for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]:
x,y = i+di, j+dj
q.append((x,y))
return False
for i in range(n):
for j in range(m):
if 'S' in mat[i][j]:
print('Yes' if dfs(2*n+i,2*m+j) else 'No')
``` | instruction | 0 | 12,729 | 15 | 25,458 |
No | output | 1 | 12,729 | 15 | 25,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall.
In this problem <image> is a remainder of dividing number a by number b.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1500) — the height and the width of the maze that the boy used to cyclically tile the plane.
Each of the next n lines contains m characters — the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point.
The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.
Output
Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).
Examples
Input
5 4
##.#
##S#
#..#
#.##
#..#
Output
Yes
Input
5 4
##.#
##S#
#..#
..#.
#.##
Output
No
Note
In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.
In the second sample the vertical path is blocked. The path to the left doesn't work, too — the next "copy" of the maze traps the boy.
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
def solve():
xs, ys = [-1, 1, 0, 0], [0, 0, -1, 1]
n, m, = rv()
tab = [list(input()) for _ in range(n)]
visited = [[False] * m for _ in range(n)]
points = list()
for r in range(n):
for c in range(m):
if tab[r][c] == 'S':
dfs(r, c, tab, visited, xs, ys)
for r in range(n):
if visited[r][0] == visited[r][-1] == True: return "Yes"
for c in range(m):
if visited[0][c] == visited[-1][c] == True: return "Yes"
return "No"
def dfs(row, col, tab, visited, xs, ys):
if row < 0 or row >= len(tab) or col < 0 or col >= len(tab[0]) or tab[row][col] == '#' or visited[row][col]: return
visited[row][col] = True
for i in range(4): dfs(row + xs[i], col + ys[i], tab, visited, xs, ys)
def prt(l): return print(''.join(l))
def rv(): return map(int, input().split())
def rl(n): return [list(map(int, input().split())) for _ in range(n)]
if sys.hexversion == 50594544 : sys.stdin = open("test.txt")
print(solve())
``` | instruction | 0 | 12,730 | 15 | 25,460 |
No | output | 1 | 12,730 | 15 | 25,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
We've got a rectangular n × m-cell maze. Each cell is either passable, or is a wall (impassable). A little boy found the maze and cyclically tiled a plane with it so that the plane became an infinite maze. Now on this plane cell (x, y) is a wall if and only if cell <image> is a wall.
In this problem <image> is a remainder of dividing number a by number b.
The little boy stood at some cell on the plane and he wondered whether he can walk infinitely far away from his starting position. From cell (x, y) he can go to one of the following cells: (x, y - 1), (x, y + 1), (x - 1, y) and (x + 1, y), provided that the cell he goes to is not a wall.
Input
The first line contains two space-separated integers n and m (1 ≤ n, m ≤ 1500) — the height and the width of the maze that the boy used to cyclically tile the plane.
Each of the next n lines contains m characters — the description of the labyrinth. Each character is either a "#", that marks a wall, a ".", that marks a passable cell, or an "S", that marks the little boy's starting point.
The starting point is a passable cell. It is guaranteed that character "S" occurs exactly once in the input.
Output
Print "Yes" (without the quotes), if the little boy can walk infinitely far from the starting point. Otherwise, print "No" (without the quotes).
Examples
Input
5 4
##.#
##S#
#..#
#.##
#..#
Output
Yes
Input
5 4
##.#
##S#
#..#
..#.
#.##
Output
No
Note
In the first sample the little boy can go up for infinitely long as there is a "clear path" that goes vertically. He just needs to repeat the following steps infinitely: up, up, left, up, up, right, up.
In the second sample the vertical path is blocked. The path to the left doesn't work, too — the next "copy" of the maze traps the boy.
Submitted Solution:
```
from collections import defaultdict
n,m = map(int, input().split())
mat = [input() for _ in range(n)]
vis = defaultdict()
x,y =0,0
for i in range(n):
for j in range(m):
if 'S' in mat[i][j]:
x,y = i,j
def safe(i,j):
return i>=0 and j>=0 and i<n and j<m
def dfs(i,j):
try:
u,v = (i+n)%n, (j+m)%m
if mat[u][v] == '#':
return False
if (u,v) in vis:
return True
vis[(i,j)]=1
vis[(u,v)]=1
for di,dj in [(0,1), (0,-1), (1,0), (-1,0)]:
x,y = i+di, j+dj
if (x,y) not in vis and dfs(x,y):
return True
return False
except IndexError:
return False
except:
return True
print('Yes' if dfs(2*n+x,2*m+y) else 'No')
``` | instruction | 0 | 12,731 | 15 | 25,462 |
No | output | 1 | 12,731 | 15 | 25,463 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,140 | 15 | 26,280 |
"Correct Solution:
```
n=int(input())
h=list(map(int,input().split()))
res=[]
t=0
for i in range(1,n):
if h[i]<=h[i-1]:
t+=1
else:
res.append(t)
t=0
res.append(t)
print(max(res))
``` | output | 1 | 13,140 | 15 | 26,281 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,141 | 15 | 26,282 |
"Correct Solution:
```
n = int(input())
a = list(map(int,input().split()))
b=[]
x=0
for i in range(n-1):
if a[i]>=a[i+1]:
x+=1
else:
b.append(x)
x=0
b.append(x)
print(max(b))
``` | output | 1 | 13,141 | 15 | 26,283 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,142 | 15 | 26,284 |
"Correct Solution:
```
n=int(input())
h=list(map(int,input().split()))
l=[0]*n
for i in range(1,n):
if h[i]<=h[i-1]:
l[i]=1+l[i-1]
print(max(l))
``` | output | 1 | 13,142 | 15 | 26,285 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,143 | 15 | 26,286 |
"Correct Solution:
```
N = int(input())
H = [int(_) for _ in input().split()]
num = [0] * N
for i in range(N-2, -1, -1):
if H[i] >= H[i+1]:
num[i] = num[i+1]+1
print(max(num))
``` | output | 1 | 13,143 | 15 | 26,287 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,144 | 15 | 26,288 |
"Correct Solution:
```
N = int(input())
H = list(map(int,input().split()))
a =[0]*(N+1)
for i in range(N-1,0,-1):
if H[i]<=H[i-1]:
a[i] = a[i+1]+1
print(max(a))
``` | output | 1 | 13,144 | 15 | 26,289 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,145 | 15 | 26,290 |
"Correct Solution:
```
n,a=input(),list(map(int,input().split()))
ans,now,cnt=0,10**20,0
for i in a:
if i>now:
cnt=0
cnt+=1
now=i
ans=max(ans,cnt)
print(ans-1)
``` | output | 1 | 13,145 | 15 | 26,291 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,146 | 15 | 26,292 |
"Correct Solution:
```
n=int(input())
a=[int(i) for i in input().split()]
m=0
c=0
for i in range(n-1):
if a[i]>=a[i+1]:
c+=1
else:
c=0
if c>m:
m=c
print(m)
``` | output | 1 | 13,146 | 15 | 26,293 |
Provide a correct Python 3 solution for this coding contest problem.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0 | instruction | 0 | 13,147 | 15 | 26,294 |
"Correct Solution:
```
N=int(input())
H=list(map(int,input().split()))
a=b=c=0
for i in range(N):
if H[i]<=a:
a=H[i]
b+=1
if b>=c:
c=b
else:
a=H[i]
b=0
print(c)
``` | output | 1 | 13,147 | 15 | 26,295 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are N squares arranged in a row from left to right.
The height of the i-th square from the left is H_i.
You will land on a square of your choice, then repeat moving to the adjacent square on the right as long as the height of the next square is not greater than that of the current square.
Find the maximum number of times you can move.
Constraints
* All values in input are integers.
* 1 \leq N \leq 10^5
* 1 \leq H_i \leq 10^9
Input
Input is given from Standard Input in the following format:
N
H_1 H_2 ... H_N
Output
Print the maximum number of times you can move.
Examples
Input
5
10 4 8 7 3
Output
2
Input
7
4 4 5 6 6 5 5
Output
3
Input
4
1 2 3 4
Output
0
Submitted Solution:
```
N = int(input())
H= list(map(int, input().split()))
res = [0]
for i in range(N-1):
if H[i+1]<=H[i]:
res[-1]+=1
else:
res.append(0)
print(max(res))
``` | instruction | 0 | 13,148 | 15 | 26,296 |
Yes | output | 1 | 13,148 | 15 | 26,297 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.