message stringlengths 2 19.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 322 108k | cluster float64 15 15 | __index_level_0__ int64 644 217k |
|---|---|---|---|---|---|
Provide a correct Python 3 solution for this coding contest problem.
There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows:
* `.` : A square without a leaf.
* `o` : A square with a leaf floating on the water.
* `S` : A square with the leaf S.
* `T` : A square with the leaf T.
The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."
Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.
Constraints
* 2 ≤ H, W ≤ 100
* a_{ij} is `.`, `o`, `S` or `T`.
* There is exactly one `S` among a_{ij}.
* There is exactly one `T` among a_{ij}.
Input
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Output
If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead.
Examples
Input
3 3
S.o
.o.
o.T
Output
2
Input
3 4
S...
.oo.
...T
Output
0
Input
4 3
.S.
.o.
.o.
.T.
Output
-1
Input
10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo
Output
5 | instruction | 0 | 9,741 | 15 | 19,482 |
"Correct Solution:
```
"""
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo
グラフを作る
⇛ SからTにたどり着く個数を全探索
⇛ たどり着く直前の座標を保持
⇛ 直前のバリエーション
解説AC
⇛ 行内、列内は自由に動ける
⇛ 行/列のどこかにいる状態でもたせる
⇛ 点の上は行⇔列の切り替えが出来るので、cap==1とする
⇛ 結局MaxCutをしているのと一緒!!
"""
from collections import deque
from collections import defaultdict
import sys
sys.setrecursionlimit(100000)
class Dinic:
def __init__(self):
# self.N = N
self.G = defaultdict(list)
def add_edge(self, fr, to, cap):
"""
:param fr: 始点
:param to: 終点
:param cap: 容量
"""
# forwardの最後には、キャパのうちどれだけ使ったかが入る
forward = [to, cap, None]
backward = [fr, 0, forward]
forward[-1] = backward
self.G[fr].append(forward)
self.G[to].append(backward)
def add_multi_edge(self, v1, v2, cap1, cap2):
"""
:param v1: 始点
:param v2: 終点
:param cap1: 容量1
:param cap2: 容量2
"""
edge1 = [v2, cap1, None]
edge2 = [v1, cap2, edge1]
edge1[-1] = edge2
self.G[v1].append(edge1)
self.G[v2].append(edge2)
def bfs(self, s, t):
"""
:param s: bfsの始点(source)
:param t: bfsの終点(sink)
:return: tに到達したかどうか。(sourceからの距離を保存しながら)
"""
self.level = level = defaultdict(int)
q = deque([s])
level[s] = 1
G = self.G
while len(q) > 0:
v = q.popleft()
lv = level[v] + 1
nexts = G[v]
for w, cap, _ in nexts:
if cap > 0 and level[w] == 0:
level[w] = lv
q.append(w)
is_reach = (level[t] > 0)
return is_reach
def dfs(self, v, t, f):
"""
:param v: 点v
:param t: 終点(sink)
:param f: v時点でのフロー
:return: 終点到達時のフローを返す
"""
if v == t:
return f
level = self.level
nexts = self.G[v]
for edge in nexts:
w, cap, rev = edge
# まだキャパがあるならば
if cap > 0 and level[v] < level[w]:
# キャパが余ってるなら全部流すし
# カツカツならキャパのmaxまで流す
d = self.dfs(w, t, min(f, cap))
# 帰りがけに、更新
if d > 0:
# 順方向のキャパをd下げる
# 逆方向のキャパをd増やす
edge[1] -= d
rev[1] += d
return d
# 次の道が見つからなければ終了
return 0
def flow(self, s, t):
"""
:param s: 始点
:param t: 終点
:return : 最大フロー
"""
flow = 0
INF = 10**10
G = self.G
# ルートが存在する限り、続ける
while self.bfs(s, t):
f = INF
while f > 0:
f = self.dfs(s, t, INF)
flow += f
return flow
ans = set()
H, W = map(int, input().split())
fields = []
for i in range(H):
inp = list(input())
fields.append(inp)
dinic = Dinic()
start = -1
end = -2
INF = 10**10
for i in range(H):
for j in range(W):
if fields[i][j] == "T":
dinic.add_edge(i,end,INF)
dinic.add_edge(j+H,end,INF)
if fields[i][j] == "S":
dinic.add_edge(start,i,INF)
dinic.add_edge(start,j+H,INF)
if fields[i][j] != ".":
dinic.add_edge(i,j+H,1)
dinic.add_edge(j+H,i,1)
ans = dinic.flow(start,end)
if ans > INF:print(-1)
else:print(ans)
``` | output | 1 | 9,741 | 15 | 19,483 |
Provide a correct Python 3 solution for this coding contest problem.
There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows:
* `.` : A square without a leaf.
* `o` : A square with a leaf floating on the water.
* `S` : A square with the leaf S.
* `T` : A square with the leaf T.
The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."
Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.
Constraints
* 2 ≤ H, W ≤ 100
* a_{ij} is `.`, `o`, `S` or `T`.
* There is exactly one `S` among a_{ij}.
* There is exactly one `T` among a_{ij}.
Input
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Output
If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead.
Examples
Input
3 3
S.o
.o.
o.T
Output
2
Input
3 4
S...
.oo.
...T
Output
0
Input
4 3
.S.
.o.
.o.
.T.
Output
-1
Input
10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo
Output
5 | instruction | 0 | 9,742 | 15 | 19,484 |
"Correct Solution:
```
import collections
class Dinic:
def __init__(self, vnum):
self.edge = [[] for i in range(vnum)]
self.n = vnum
self.inf = float('inf')
def addedge(self, st, en, c):
self.edge[st].append([en, c, len(self.edge[en])])
self.edge[en].append([st, 0, len(self.edge[st])-1])
def bfs(self, vst):
dist = [-1]*self.n
dist[vst] = 0
Q = collections.deque([vst])
while Q:
nv = Q.popleft()
for vt, c, r in self.edge[nv]:
if dist[vt] == -1 and c > 0:
dist[vt] = dist[nv] + 1
Q.append(vt)
self.dist = dist
def dfs(self, nv, en, nf):
nextv = self.nextv
if nv == en:
return nf
dist = self.dist
ist = nextv[nv]
for i, (vt, c, r) in enumerate(self.edge[nv][ist:], ist):
if dist[nv] < dist[vt] and c > 0:
df = self.dfs(vt, en, min(nf, c))
if df > 0:
self.edge[nv][i][1] -= df
self.edge[vt][r][1] += df
return df
nextv[nv] += 1
return 0
def getmf(self, st, en):
mf = 0
while True:
self.bfs(st)
if self.dist[en] == -1:
break
self.nextv = [0]*self.n
while True:
fl = self.dfs(st, en, self.inf)
if fl > 0:
mf += fl
else:
break
return mf
H, W = map(int, input().split())
G = [input() for _ in range(H)]
T = Dinic(H+W)
inf = 10**9+7
SS = []
for i in range(H):
for j in range(W):
if G[i][j] == '.':
continue
if G[i][j] == 'o':
T.addedge(i, H+j, 1)
T.addedge(H+j, i, 1)
continue
SS.append(i)
SS.append(H + j)
T.addedge(i, H+j, inf)
T.addedge(H+j, i, inf)
ans = T.getmf(SS[0], SS[-1])
if ans >= 10**9:
print(-1)
else:
print(ans)
``` | output | 1 | 9,742 | 15 | 19,485 |
Provide a correct Python 3 solution for this coding contest problem.
There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows:
* `.` : A square without a leaf.
* `o` : A square with a leaf floating on the water.
* `S` : A square with the leaf S.
* `T` : A square with the leaf T.
The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."
Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.
Constraints
* 2 ≤ H, W ≤ 100
* a_{ij} is `.`, `o`, `S` or `T`.
* There is exactly one `S` among a_{ij}.
* There is exactly one `T` among a_{ij}.
Input
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Output
If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead.
Examples
Input
3 3
S.o
.o.
o.T
Output
2
Input
3 4
S...
.oo.
...T
Output
0
Input
4 3
.S.
.o.
.o.
.T.
Output
-1
Input
10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo
Output
5 | instruction | 0 | 9,743 | 15 | 19,486 |
"Correct Solution:
```
# 最大流
NUMERIC_LIMITS = 10 ** 18
import queue
class maxFlow:
class edge:
def __init__(s, frm, to, cap, flow):
s.frm, s.to = frm, to
s.cap, s.flow = cap, flow
def __init__(s, n):
s._n = n
s.g = [[] for _ in range(n)]
s.pos = []
def add_edge(s, frm, to, cap):
m = len(s.pos)
s.pos.append([frm, len(s.g[frm])])
s.g[frm].append(s._edge(to, len(s.g[to]), cap))
s.g[to].append(s._edge(frm,len(s.g[frm]) - 1, 0))
return m
def get_edge(s, i):
m = len(s.pos)
_e = s.g[s.pos[i][0]][s.pos[i][1]]
_re = s.g[_e.to][_e.rev]
return s.edge(s.pos[i][0], _e.to, _e.cap + _re.cap, _re.cap)
def edges(s):
m = len(s.pos)
result = []
for i in range(m):
result.append(s.get_edge(i))
return result
def change_edge(s, i, new_cap, new_flow):
m = len(s.pos)
_e = s.g[s.pos[i].to][s.pos[i].rev]
_re = s.g[_e.to][_e.rev]
_e.cap = new_cap - new_flow
_re.cap = new_flow
def flow(self, s, t, flow_limit = NUMERIC_LIMITS):
level = [0] * self._n
iter = [0] * self._n
def bfs():
for i in range(self._n):
level[i] = -1
level[s] = 0
que = queue.Queue()
que.put(s)
while not que.empty():
v = que.get()
for e in self.g[v]:
if e.cap == 0 or level[e.to] >= 0: continue
level[e.to] = level[v] + 1
if e.to == t: return
que.put(e.to)
def dfs(this, v, up):
if v == s: return up
res = 0
level_v = level[v]
for i in range(iter[v], len(self.g[v])):
e = self.g[v][i]
if level_v <= level[e.to] or self.g[e.to][e.rev].cap == 0: continue
d = this(this, e.to, min(up - res, self.g[e.to][e.rev].cap))
if d <= 0: continue
self.g[v][i].cap += d
self.g[e.to][e.rev].cap -= d
res += d
if res == up: break
return res
flow = 0
while flow < flow_limit:
bfs()
if level[t] == -1: break
for i in range(self._n): iter[i]
while flow < flow_limit:
f = dfs(dfs, t, flow_limit - flow)
if not f: break
flow += f
return flow
def min_cut(self, s):
visited = [False] * self._n
que = queue.Queue()
que.put(s)
while not que.empty():
p = que.get()
visited[p] = True
for e in self.g[p]:
if e.cap and not visited[e.to]:
visited[e.to] = True
que.put(e.to)
return visited
class _edge:
def __init__(s, to, rev, cap):
s.to, s.rev = to, rev
s.cap = cap
H, W = list(map(int, input().split()))
a = [list(input()) for _ in range(H)]
flow = maxFlow(H + W + 2)
s = H + W
t = H + W + 1
for h in range(H):
for w in range(W):
if a[h][w] == "S":
flow.add_edge(s, h, H + W + 1)
flow.add_edge(s, H + w, H + W + 1)
elif a[h][w] == "T":
flow.add_edge(h, t, H + W + 1)
flow.add_edge(H + w, t, H + W + 1)
if a[h][w] != ".":
flow.add_edge(h, H + w, 1)
flow.add_edge(H + w, h, 1)
ans = flow.flow(s, t)
if ans > H + W:
print(-1)
else:
print(ans)
``` | output | 1 | 9,743 | 15 | 19,487 |
Provide a correct Python 3 solution for this coding contest problem.
There is a pond with a rectangular shape. The pond is divided into a grid with H rows and W columns of squares. We will denote the square at the i-th row from the top and j-th column from the left by (i,\ j).
Some of the squares in the pond contains a lotus leaf floating on the water. On one of those leaves, S, there is a frog trying to get to another leaf T. The state of square (i,\ j) is given to you by a character a_{ij}, as follows:
* `.` : A square without a leaf.
* `o` : A square with a leaf floating on the water.
* `S` : A square with the leaf S.
* `T` : A square with the leaf T.
The frog will repeatedly perform the following action to get to the leaf T: "jump to a leaf that is in the same row or the same column as the leaf where the frog is currently located."
Snuke is trying to remove some of the leaves, other than S and T, so that the frog cannot get to the leaf T. Determine whether this objective is achievable. If it is achievable, find the minimum necessary number of leaves to remove.
Constraints
* 2 ≤ H, W ≤ 100
* a_{ij} is `.`, `o`, `S` or `T`.
* There is exactly one `S` among a_{ij}.
* There is exactly one `T` among a_{ij}.
Input
Input is given from Standard Input in the following format:
H W
a_{11} ... a_{1W}
:
a_{H1} ... a_{HW}
Output
If the objective is achievable, print the minimum necessary number of leaves to remove. Otherwise, print `-1` instead.
Examples
Input
3 3
S.o
.o.
o.T
Output
2
Input
3 4
S...
.oo.
...T
Output
0
Input
4 3
.S.
.o.
.o.
.T.
Output
-1
Input
10 10
.o...o..o.
....o.....
....oo.oo.
..oooo..o.
....oo....
..o..o....
o..o....So
o....T....
....o.....
........oo
Output
5 | instruction | 0 | 9,744 | 15 | 19,488 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
from collections import deque
H,W = map(int,readline().split())
A = [line.rstrip().decode('utf-8') for line in readlines()]
class Dinic:
def __init__(self, N, source, sink):
self.N = N
self.G = [[] for _ in range(N)]
self.source = source
self.sink = sink
def add_edge(self, fr, to, cap):
n1 = len(self.G[fr])
n2 = len(self.G[to])
self.G[fr].append([to, cap, n2])
self.G[to].append([fr, 0, n1]) # 逆辺を cap 0 で追加
def bfs(self):
level = [0] * self.N
G = self.G; source = self.source; sink = self.sink
q = deque([source])
level[source] = 1
pop = q.popleft; append = q.append
while q:
v = pop()
lv = level[v] + 1
for to, cap, rev in G[v]:
if not cap:
continue
if level[to]:
continue
level[to] = lv
if to == sink:
self.level = level
return
append(to)
self.level = level
def dfs(self,v,f):
if v == self.sink:
return f
G = self.G
prog = self.progress
level = self.level
lv = level[v]
E = G[v]
for i in range(prog[v],len(E)):
to, cap, rev = E[i]
prog[v] = i
if not cap:
continue
if level[to] <= lv:
continue
x = f if f < cap else cap
ff = self.dfs(to, x)
if ff:
E[i][1] -= ff
G[to][rev][1] += ff
return ff
return 0
def max_flow(self):
INF = 10**18
flow = 0
while True:
self.bfs()
if not self.level[self.sink]:
return flow
self.progress = [0] * self.N
while True:
f = self.dfs(self.source, INF)
if not f:
break
flow += f
return flow
source = 0
sink = H+W+1
dinic = Dinic(H+W+2, source, sink)
add = dinic.add_edge
INF = 10 ** 18
for h in range(1,H+1):
for w,ox in enumerate(A[h-1],1):
if ox == 'x':
continue
elif ox == 'o':
add(h,H+w,1)
add(H+w,h,1)
elif ox == 'S':
add(source,h,INF)
add(h,source,INF)
add(source,H+w,INF)
add(H+w,source,INF)
elif ox == 'T':
add(sink,h,INF)
add(h,sink,INF)
add(sink,H+w,INF)
add(H+w,sink,INF)
f = dinic.max_flow()
answer = f if f < INF else -1
print(answer)
``` | output | 1 | 9,744 | 15 | 19,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,037 | 15 | 20,074 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
import sys
from collections import deque
a, b, k = map(int,input().split())
obsa = [[] for _ in range(a)]
obsb = [[] for _ in range(b)]
for _ in range(k):
x, y = map(int,input().split())
# x, y = _,7
obsa[x-1].append(y-1)
obsb[y-1].append(x-1)
for l in obsa:l.sort()
for l in obsb:l.sort()
obsa = list (map(deque,obsa))
obsb = list (map(deque,obsb))
totals = a*b-k
bordera=[0,a-1]
borderb=[0,b-1]
state =0
discs=0
discnew=0
broken = False
ff=0
while(discs <a*b-k and not broken):
# print("___")
# print(f"state: {state}")
# print(bordera)
# print(borderb)
if state==0: # go right
ff=-1
while len(obsa[bordera[0]])>0:
f= obsa[bordera[0]].popleft()
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if ff > -1: # obstacle in range
borderb[1] = ff-1
discnew = borderb[1]-borderb[0]+1
bordera[0]+=1
elif state == 1: # go down
ff=-1
while len(obsb[borderb[1]])>0:
f= obsb[borderb[1]].popleft()
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if f>bordera[1]:
break
if ff > -1: # obstacle in range
bordera[1] = ff-1
discnew = bordera[1]-bordera[0]+1
borderb[1] -= 1
elif state == 2: # go left
ff=-1
while len(obsa[bordera[1]])>0:
f = obsa[bordera[1]].pop()
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if ff > -1: # obstacle in range
borderb[0] = ff+1
discnew = borderb[1]-borderb[0]+1
bordera[1]-=1
elif state == 3: # go up
ff=-1
while len(obsb[borderb[0]])>0:
f= obsb[borderb[0]].pop()
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if ff > -1: # obstacle in range
bordera[0] = ff+1
discnew = bordera[1]-bordera[0]+1
borderb[0] += 1
# print(ff)
state = (state+1)%4
if(discnew==0):
broken = True
discs += discnew
# print(f"new discvs: {discnew}")
# print(discs)
if (broken or discs <a*b-k):
print("No")
else:
print("Yes")
``` | output | 1 | 10,037 | 15 | 20,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,038 | 15 | 20,076 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
import sys
def I():
return sys.stdin.readline().rstrip()
n, m, k = map( int, I().split() )
r, c = dict(), dict()
for _ in range( k ):
x, y = map( int, I().split() )
if x not in r:
r[ x ] = []
r[ x ].append( y )
if y not in c:
c[ y ] = []
c[ y ].append( x )
for v in r.values():
v.sort()
for v in c.values():
v.sort()
def bin( a, x ):
i = -1
j = 1
while j <= len( a ):
j *= 2
j //= 2
while j:
if i + j < len( a ) and a[ i + j ] <= x:
i += j
j //= 2
return i
dx = [ m + 1, n + 1, 0, 0 ]
def next( x, y, d ):
if d == 0:
if x in r:
a = r[ x ]
i = bin( a, y ) + 1
if i < len( a ):
dx[ d ] = min( dx[ d ], a[ i ] )
y = dx[ d ] - 1
dx[ d - 1 ] = x
elif d == 1:
if y in c:
a = c[ y ]
i = bin( a, x ) + 1
if i < len( a ):
dx[ d ] = min( dx[ d ], a[ i ] )
x = dx[ d ] - 1
dx[ d - 1 ] = y
elif d == 2:
if x in r:
a = r[ x ]
i = bin( a, y )
if i >= 0:
dx[ d ] = max( dx[ d ], a[ i ] )
y = dx[ d ] + 1
dx[ d - 1 ] = x
else:
if y in c:
a = c[ y ]
i = bin( a, x )
if i >= 0:
dx[ d ] = max( dx[ d ], a[ i ] )
x = dx[ d ] + 1
dx[ d - 1 ] = y
return x, y, ( d + 1 ) % 4
x, y, d = 1, 0, 0
while True:
xx, yy, d = next( x, y, d )
if x == xx and y == yy:
break
k += abs( xx - x ) + abs( yy - y )
x, y = xx, yy
if k == n * m:
print( "Yes" )
else:
print( "No" )
``` | output | 1 | 10,038 | 15 | 20,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,039 | 15 | 20,078 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
import sys
from collections import deque
a, b, k = map(int,sys.stdin.readline().split())
obsa = [[] for _ in range(a)]
obsb = [[] for _ in range(b)]
for _ in range(k):
x, y = map(int,sys.stdin.readline().split())
# x, y = _,7
obsa[x-1].append(y-1)
obsb[y-1].append(x-1)
for l in obsa:l.sort()
for l in obsb:l.sort()
obsa = list (map(deque,obsa))
obsb = list (map(deque,obsb))
totals = a*b-k
bordera=[0,a-1]
borderb=[0,b-1]
state =0
discs=0
discnew=0
broken = False
ff=0
while(discs <a*b-k and not broken):
# print("___")
# print(f"state: {state}")
# print(bordera)
# print(borderb)
if state==0: # go right
ff=-1
while len(obsa[bordera[0]])>0:
f= obsa[bordera[0]].popleft()
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if ff > -1: # obstacle in range
borderb[1] = ff-1
discnew = borderb[1]-borderb[0]+1
bordera[0]+=1
elif state == 1: # go down
ff=-1
while len(obsb[borderb[1]])>0:
f= obsb[borderb[1]].popleft()
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if f>bordera[1]:
break
if ff > -1: # obstacle in range
bordera[1] = ff-1
discnew = bordera[1]-bordera[0]+1
borderb[1] -= 1
elif state == 2: # go left
ff=-1
while len(obsa[bordera[1]])>0:
f = obsa[bordera[1]].pop()
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if ff > -1: # obstacle in range
borderb[0] = ff+1
discnew = borderb[1]-borderb[0]+1
bordera[1]-=1
elif state == 3: # go up
ff=-1
while len(obsb[borderb[0]])>0:
f= obsb[borderb[0]].pop()
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if ff > -1: # obstacle in range
bordera[0] = ff+1
discnew = bordera[1]-bordera[0]+1
borderb[0] += 1
# print(ff)
state = (state+1)%4
if(discnew==0):
broken = True
discs += discnew
# print(f"new discvs: {discnew}")
# print(discs)
if (broken or discs <a*b-k):
print("No")
else:
print("Yes")
``` | output | 1 | 10,039 | 15 | 20,079 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,040 | 15 | 20,080 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
def tr(n, m, inp):
xa = n
xi = yi = 1
ya = m
while True:
while (xi, ya) in inp:
for x in range(xi, xa + 1):
inp.remove((x, ya))
ya -= 1
if ya < yi:
return
xi += 1
if xa < xi:
return
while (xa, ya) in inp:
for y in range(yi, ya + 1):
inp.remove((xa, y))
xa -= 1
if xa < xi:
return
ya -= 1
if ya < yi:
return
while (xa, yi) in inp:
for x in range(xi, xa + 1):
inp.remove((x, yi))
yi += 1
if ya < yi:
return
xa -= 1
if xa < xi:
return
while (xi, yi) in inp:
for y in range(yi, ya + 1):
inp.remove((xi, y))
xi += 1
if xa < xi:
return
yi += 1
if ya < yi:
return
n, m, k = map(int, input().split())
inp = {tuple(map(int, input().split())) for _ in range(k)}
try:
tr(n, m, inp)
assert not inp
print('Yes')
except (AssertionError, KeyError):
print('No')
``` | output | 1 | 10,040 | 15 | 20,081 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,041 | 15 | 20,082 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
"""
Author : thekushalghosh
Team : CodeDiggers
"""
import sys,math
input = sys.stdin.readline
############ ---- USER DEFINED INPUT FUNCTIONS ---- ############
def inp():
return(int(input()))
def inlt():
return(list(map(int,input().split())))
def insr():
s = input()
return(s[:len(s) - 1])
def invr():
return(map(int,input().split()))
################################################################
############ ---- THE ACTUAL CODE STARTS BELOW ---- ############
t = 1
def qw(n,m,inp):
xa = n
xi = yi = 1
ya = m
while True:
while (xi, ya) in inp:
for x in range(xi, xa + 1):
inp.remove((x, ya))
ya = ya - 1
if ya < yi:
return
xi += 1
if xa < xi:
return
while (xa, ya) in inp:
for y in range(yi, ya + 1):
inp.remove((xa, y))
xa -= 1
if xa < xi:
return
ya -= 1
if ya < yi:
return
while (xa, yi) in inp:
for x in range(xi, xa + 1):
inp.remove((x, yi))
yi += 1
if ya < yi:
return
xa -= 1
if xa < xi:
return
while (xi, yi) in inp:
for y in range(yi, ya + 1):
inp.remove((xi, y))
xi += 1
if xa < xi:
return
yi += 1
if ya < yi:
return
for tt in range(t):
n,m,k = invr()
a = {tuple(invr()) for i in range(k)}
try:
qw(n, m, a)
assert not a
if k < 1 and n < 1:
print("No")
else:
print("Yes")
except:
print("No")
``` | output | 1 | 10,041 | 15 | 20,083 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,042 | 15 | 20,084 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
from sys import stdout
printn = lambda x: stdout.write(x)
inn = lambda : int(input())
inl = lambda: list(map(int, input().split()))
inm = lambda: map(int, input().split())
DBG = True and False
BIG = 999999999
R = 10**9 + 7
def ddprint(x):
if DBG:
print(x)
n,m,k = inm()
hx = {}
hy = {}
cnt = 0
for i in range(k):
x,y = inm()
x -= 1
y -= 1
cnt += 1
if x in hx:
hx[x].append(y)
else:
hx[x] = [y]
if y in hy:
hy[y].append(x)
else:
hy[y] = [x]
ddprint(hx)
ddprint(hy)
x,y = 0,0
dir = 1
if m==1 or (m>1 and 0 in hx and 1 in hx[0]):
dir = 2
minx = miny = -1
maxx = n
maxy = m
while True:
#ddprint("x {} y {} dir {} mn {} {} mx {} {}".format(x,y,dir,minx,miny,maxx,maxy))
nx = x
ny = y
if dir==1:
a = [z for z in hx[x] if y<z and z<maxy] if x in hx else []
#ddprint(a)
if len(a)==0:
ny = maxy-1
else:
a.sort()
ny = a[0]-1
if ny==y:
break
cnt += ny-y
y = ny
minx = x
dir = 2
elif dir==2:
a = [z for z in hy[y] if x<z and z<maxx] if y in hy else []
if len(a)==0:
nx = maxx-1
else:
a.sort()
nx = a[0]-1
if nx==x:
break
cnt += nx-x
x = nx
maxy = y
dir = 3
elif dir==3:
a = [z for z in hx[x] if miny<z and z<y] if x in hx else []
if len(a)==0:
ny = miny+1
else:
a.sort(reverse=True)
ny = a[0]+1
if ny==y:
break
cnt += y-ny
y = ny
maxx = x
dir = 4
elif dir==4:
a = [z for z in hy[y] if minx<z and z<x] if y in hy else []
if len(a)==0:
nx = minx+1
else:
a.sort(reverse=True)
nx = a[0]+1
if nx==x:
break
cnt += x-nx
x = nx
miny = y
dir = 1
print('Yes' if cnt==n*m-1 else 'No')
``` | output | 1 | 10,042 | 15 | 20,085 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,043 | 15 | 20,086 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
import sys
from bisect import bisect
input = sys.stdin.readline
def r1():
return int(input())
def rm():
return map(int, input().split())
n, m, k = rm()
rw, cl = {}, {}
for i in range(k):
x, y = rm()
if x not in rw:
rw[x] = []
rw[x].append(y)
if y not in cl:
cl[y] = []
cl[y].append(x)
for v in rw.values():
v.sort()
for v in cl.values():
v.sort()
##print(rw)
##print(cl)
l, r, u, d = 1, m, 1, n
dr = 1
x, y = 1, 1
s = 1
##print('l, r, u, d, x, y, dr, s')
##print(l, r, u, d, x, y, dr, s)
while l <= r and u <= d:
if dr == 1:
if x in rw:
f = bisect(rw[x], y)
if f < len(rw[x]):
r = min(r, rw[x][f]-1)
s += r - y
y = r
u += 1
elif dr == 3:
if x in rw:
f = bisect(rw[x], y)
if f > 0:
l = max(l, rw[x][f-1]+1)
s += y - l
y = l
d -= 1
elif dr == 2:
if y in cl:
f = bisect(cl[y], x)
## print(f)
## print(cl[y])
## print(cl[y][f]-1)
if f < len(cl[y]):
d = min(d, cl[y][f]-1)
## print(d, x)
s += d - x
x = d
r -= 1
elif dr == 0:
if y in cl:
f = bisect(cl[y], x)
if f > 0:
u = max(u, cl[y][f-1]+1)
s += x - u
x = u
l += 1
dr = (dr + 1) % 4
## print(l, r, u, d, x, y, dr, s)
print('YES' if s == n*m - k else 'NO')
``` | output | 1 | 10,043 | 15 | 20,087 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once. | instruction | 0 | 10,044 | 15 | 20,088 |
Tags: brute force, data structures, greedy, implementation
Correct Solution:
```
import sys
#sys.stdin = open('in', 'r')
#n = int(input())
n,m,k = map(int, input().split())
dr = {}
dc = {}
for i in range(n):
dr[i] = []
for i in range(m):
dc[i] = []
for i in range(k):
r,c = map(int, input().split())
dr[r-1].append(c-1)
dc[c-1].append(r-1)
for i in range(n):
dr[i].sort()
for i in range(m):
dc[i].sort()
def findDown(r, c, mx):
global dc
res = mx
lf, rg = 0, len(dc[c])-1
while lf <= rg:
mid = (lf+rg)//2
if dc[c][mid] < r:
lf = mid + 1
else:
res = dc[c][mid]-1
rg = mid - 1
return min(res, mx)
def findUp(r, c, mx):
global dc
res = mx
lf, rg = 0, len(dc[c])-1
while lf <= rg:
mid = (lf+rg)//2
if dc[c][mid] > r:
rg = mid - 1
else:
res = dc[c][mid]+1
lf = mid + 1
return max(res, mx)
def findRight(r, c, mx):
global dr
res = mx
lf, rg = 0, len(dr[r])-1
while lf <= rg:
mid = (lf+rg)//2
if dr[r][mid] < c:
lf = mid + 1
else:
res = dr[r][mid]-1
rg = mid - 1
return min(res, mx)
def findLeft(r, c, mx):
global dr
res = mx
lf, rg = 0, len(dr[r])-1
while lf <= rg:
mid = (lf+rg)//2
if dr[r][mid] > c:
rg = mid - 1
else:
res = dr[r][mid]+1
lf = mid + 1
return max(res, mx)
lb,rb = 0, m-1
ub,db = 1, n-1
direct = 0
visited = 1
r,c = 0,0
while True:
nr, nc = r, c
if direct == 0:
nc = findRight(r,c,rb)
rb = nc - 1
elif direct == 1:
nr = findDown(r,c,db)
db = nr - 1
elif direct == 2:
nc = findLeft(r,c,lb)
lb = nc + 1
elif direct == 3:
nr = findUp(r,c,ub)
ub = nr + 1
steps = abs(r-nr) + abs(c-nc)
#print(steps, lb,rb,ub,db)
#print(r,c,nr,nc)
if steps == 0 and (r != 0 or c != 0 or direct != 0):
break
direct = (direct + 1) % 4
visited += steps
r,c = nr,nc
print('Yes' if (n*m-k == visited) else 'No')
#sys.stdout.write('YES\n')
#sys.stdout.write(f'{res}\n')
#sys.stdout.write(f'{y1} {x1} {y2} {x2}\n')
``` | output | 1 | 10,044 | 15 | 20,089 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
def tr(n, m, inp):
xa = n
xi = yi = 1
ya = m
while True:
while (xi, ya) in inp:
for x in range(xi, xa + 1):
inp.remove((x, ya))
ya -= 1
if ya < yi:
return
xi += 1
if xa < xi:
return
while (xa, ya) in inp:
for y in range(yi, ya + 1):
inp.remove((xa, y))
xa -= 1
if xa < xi:
return
ya -= 1
if ya < yi:
return
while (xa, yi) in inp:
for x in range(xi, xa + 1):
inp.remove((x, yi))
yi += 1
if ya < yi:
return
xa -= 1
if xa < xi:
return
while (xi, yi) in inp:
for y in range(yi, ya + 1):
inp.remove((xi, y))
xi += 1
if xa < xi:
return
yi += 1
if ya < yi:
return
def main():
n, m, k = map(int, input().split())
inp = {tuple(map(int, input().split())) for _ in range(k)}
try:
tr(n, m, inp)
assert not inp
print('Yes')
except (AssertionError, KeyError):
print('No')
main()
``` | instruction | 0 | 10,045 | 15 | 20,090 |
Yes | output | 1 | 10,045 | 15 | 20,091 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
c, r, k = list(map(int, input().split()))
rows = [[] for i in range(r)]
columns = [[] for i in range(c)]
for i in range(k):
x,y = list(map(int, input().split()))
x -= 1
y -= 1
rows[y].append(x)
columns[x].append(y)
for v in rows:
v.sort()
for v in columns:
v.sort()
'''for i in range(r):
for j in range(c):
if j in rows[i]:
print("#", end = "")
else:
print(".", end = "")
print()
'''
def firstGreaterThan(listlist, num, low, high):
if low > high:
return -1
if low == high:
if listlist[low] > num:
return listlist[low]
else:
return -1
mid = (low+high) // 2
if listlist[mid] > num:
high = mid
else:
low = mid+1
return firstGreaterThan(listlist, num, low, high)
def lastLessThan(listlist, num, low, high):
if low > high:
return -1
if low == high:
if listlist[low] < num:
return listlist[low]
else:
return -1
mid = (low+high+1) // 2
if listlist[mid] < num:
low = mid
else:
high = mid-1
return lastLessThan(listlist, num, low, high)
xpos = 0
ypos = 0
cellsCovered = 1
dir = 1
firstStep = True
xmin = 0
xmax = c-1
ymin = 0
ymax = r-1
while xmin <= xmax and ymin <= ymax:
#print((xpos, ypos), (xmin, ymin), (xmax, ymax))
targetSquare = -1
if dir == 1:
targetSquare = firstGreaterThan(columns[xpos], ypos, 0, len(columns[xpos]) - 1)
elif dir == 2:
targetSquare = firstGreaterThan(rows[ypos], xpos, 0, len(rows[ypos]) - 1)
elif dir == 3:
targetSquare = lastLessThan(columns[xpos], ypos, 0, len(columns[xpos]) - 1)
#print(targetSquare, "hello")
else:
targetSquare = lastLessThan(rows[ypos], xpos, 0, len(rows[ypos]) - 1)
if targetSquare == -1:
if dir == 1:
targetSquare = ymax
elif dir == 2:
targetSquare = xmax
elif dir == 3:
targetSquare = ymin
else:
targetSquare = xmin
else:
if dir == 1:
targetSquare -= 1
if targetSquare > ymax:
targetSquare = ymax
elif dir == 2:
targetSquare -= 1
if targetSquare > xmax:
targetSquare = xmax
elif dir == 3:
targetSquare += 1
if targetSquare < ymin:
targetSquare = ymin
else:
targetSquare += 1
if targetSquare < xmin:
targetSquare = xmin
#print(targetSquare)
if dir % 2 == 0 and targetSquare == xpos or dir % 2 == 1 and targetSquare == ypos:
if firstStep:
firstStep = False
dir += 1
if dir == 5:
dir = 1
continue
break
firstStep = False
if dir == 1:
cellsCovered += targetSquare - ypos
ypos = targetSquare
ymax = ypos
xmin += 1
elif dir == 2:
cellsCovered += targetSquare - xpos
xpos = targetSquare
xmax = xpos
ymax -= 1
elif dir == 3:
cellsCovered += ypos - targetSquare
ypos = targetSquare
ymin = ypos
xmax -= 1
else:
cellsCovered += xpos - targetSquare
xpos = targetSquare
xmin = xpos
ymin += 1
dir += 1
if dir == 5:
dir = 1
if cellsCovered == r*c-k:
print("Yes")
else:
print("No")
``` | instruction | 0 | 10,046 | 15 | 20,092 |
Yes | output | 1 | 10,046 | 15 | 20,093 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000000)
def move(x,y):
global length, maxl, cnt
for i in range(4):
x += dx[i]
y += dy[i]
if (x in range(n)) and (y in range(m)) and (maze[x][y] == 0):
maze[x][y] = 1
length += 1
if (length == val):
maxl = max(maxl, length)
print('Yes')
exit
move(x,y)
maze[x][y] = 0
length -= 1
x -= dx[i]
y -= dy[i]
n, m, k = map(int, input().split())
maze = [[0 for i in range(m)] for i in range(n)]
dx = [0, 1, 0, -1]
dy = [1, 0, -1, 0]
for i in range(k):
x, y = map(int, input().split())
maze[x-1][y-1] = 1
length = 1
maxl = 0
val = n*m - k
if (val == 1):
print('Yes')
else:
maze[0][0] = 1
move(0,0)
if (maxl < val):
print('No')
else:
print('Yes')
``` | instruction | 0 | 10,047 | 15 | 20,094 |
No | output | 1 | 10,047 | 15 | 20,095 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
c, r, k = list(map(int, input().split()))
rows = [[] for i in range(r)]
columns = [[] for i in range(c)]
for i in range(k):
x,y = list(map(int, input().split()))
x -= 1
y -= 1
rows[y].append(x)
columns[x].append(y)
for v in rows:
v.sort()
for v in columns:
v.sort()
def firstGreaterThan(listlist, num, low, high):
if low > high:
return -1
if low == high:
if listlist[low] > num:
return listlist[low]
else:
return -1
mid = (low+high) // 2
if listlist[mid] > num:
high = mid
else:
low = mid+1
return firstGreaterThan(listlist, num, low, high)
def lastLessThan(listlist, num, low, high):
if low > high:
return -1
if low == high:
if listlist[low] < num:
return listlist[low]
else:
return -1
mid = (low+high+1) // 2
if listlist[mid] < num:
low = mid
else:
high = mid-1
return lastLessThan(listlist, num, low, high)
xpos = 0
ypos = 0
cellsCovered = 1
dir = 1
xmin = 0
xmax = c-1
ymin = 0
ymax = r-1
while xmin <= xmax and ymin <= ymax:
#print((xpos, ypos), (xmin, ymin), (xmax, ymax))
targetSquare = -1
if dir == 1:
targetSquare = firstGreaterThan(columns[xpos], ypos, 0, len(columns[xpos]) - 1)
elif dir == 2:
targetSquare = firstGreaterThan(rows[ypos], xpos, 0, len(rows[ypos]) - 1)
elif dir == 3:
targetSquare = lastLessThan(columns[xpos], ypos, 0, len(columns[xpos]) - 1)
#print(targetSquare, "hello")
else:
targetSquare = lastLessThan(rows[ypos], xpos, 0, len(rows[ypos]) - 1)
if targetSquare == -1:
if dir == 1:
targetSquare = ymax
elif dir == 2:
targetSquare = xmax
elif dir == 3:
targetSquare = ymin
else:
targetSquare = xmin
else:
if dir == 1:
targetSquare -= 1
if targetSquare > ymax:
targetSquare = ymax
elif dir == 2:
targetSquare -= 1
if targetSquare > xmax:
targetSquare = xmax
elif dir == 3:
targetSquare += 1
if targetSquare < ymin:
targetSquare = ymin
else:
targetSquare += 1
if targetSquare < xmin:
targetSquare = xmin
#print(targetSquare)
if dir % 2 == 0 and targetSquare == xpos or dir % 2 == 1 and targetSquare == ypos:
break
if dir == 1:
cellsCovered += targetSquare - ypos
ypos = targetSquare
ymax = ypos
xmin += 1
elif dir == 2:
cellsCovered += targetSquare - xpos
xpos = targetSquare
xmax = xpos
ymax -= 1
elif dir == 3:
cellsCovered += ypos - targetSquare
ypos = targetSquare
ymin = ypos
xmax -= 1
else:
cellsCovered += xpos - targetSquare
xpos = targetSquare
xmin = xpos
ymin += 1
dir += 1
if dir == 5:
dir = 1
if cellsCovered == r*c-k:
print("Yes")
else:
print("No")
``` | instruction | 0 | 10,048 | 15 | 20,096 |
No | output | 1 | 10,048 | 15 | 20,097 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
from collections import defaultdict
n, m, k = list(map(int, input().split()))
pointsbyx = defaultdict(list)
pointsbyy = defaultdict(list)
pointsx = set()
pointsy = set()
points = set()
for _ in range(k):
point = tuple(map(int, input().split()))
points.add(point)
pointsx.add(point[0])
pointsy.add(point[1])
pointsbyx[point[0]].append(point[1])
pointsbyy[point[1]].append(point[0])
xmin = 1
xmax = n
ymin = 1
ymax = m
while xmin != xmax and ymin != ymax:
if xmin in pointsx:
ycollision = min(pointsbyx[xmin])
for xi in range(xmin, xmax+1):
for yi in range(ycollision, ymax+1):
if (xi,yi) not in points:
print("NO")
exit(0)
ymax = ycollision-1
pointsx.remove(xmin)
elif ymax in pointsy:
xcollision = min(pointsbyy[ymax])
for xi in range(xcollision, xmax+1):
for yi in range(ymin, ymax+1):
if (xi,yi) not in points:
print("No")
exit(0)
xmax = xcollision-1
pointsy.remove(ymax)
elif xmax in pointsx:
ycollision = max(pointsbyx[xmax])
for xi in range(xmin+1, xmax+1):
for yi in range(ymin, ymax):
if xi == xmax and yi == ycollision:
break
if (xi,yi) not in points:
print("No")
exit(0)
print("Yes")
exit(0)
elif ymax in pointsy:
xcollision = max(pointsbyy[ymin])
for yi in reversed(range(ymin, ymax)):
for xi in range(xmin+1, xcollision):
if yi == ymin and xi == xcollision:
break
if (xi,yi) not in points:
print("No")
exit(0)
print("Yes")
exit(0)
else:
xmin+=1
xmax-=1
ymin+=1
ymax-=1
print("Yes")
exit(0)
``` | instruction | 0 | 10,049 | 15 | 20,098 |
No | output | 1 | 10,049 | 15 | 20,099 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Alice got a new doll these days. It can even walk!
Alice has built a maze for the doll and wants to test it. The maze is a grid with n rows and m columns. There are k obstacles, the i-th of them is on the cell (x_i, y_i), which means the cell in the intersection of the x_i-th row and the y_i-th column.
However, the doll is clumsy in some ways. It can only walk straight or turn right at most once in the same cell (including the start cell). It cannot get into a cell with an obstacle or get out of the maze.
More formally, there exist 4 directions, in which the doll can look:
1. The doll looks in the direction along the row from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y + 1);
2. The doll looks in the direction along the column from the first cell to the last. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x + 1, y);
3. The doll looks in the direction along the row from the last cell to first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x, y - 1);
4. The doll looks in the direction along the column from the last cell to the first. While moving looking in this direction the doll will move from the cell (x, y) into the cell (x - 1, y).
.
Standing in some cell the doll can move into the cell in the direction it looks or it can turn right once. Turning right once, the doll switches it's direction by the following rules: 1 → 2, 2 → 3, 3 → 4, 4 → 1. Standing in one cell, the doll can make at most one turn right.
Now Alice is controlling the doll's moves. She puts the doll in of the cell (1, 1) (the upper-left cell of the maze). Initially, the doll looks to the direction 1, so along the row from the first cell to the last. She wants to let the doll walk across all the cells without obstacles exactly once and end in any place. Can it be achieved?
Input
The first line contains three integers n, m and k, separated by spaces (1 ≤ n,m ≤ 10^5, 0 ≤ k ≤ 10^5) — the size of the maze and the number of obstacles.
Next k lines describes the obstacles, the i-th line contains two integer numbers x_i and y_i, separated by spaces (1 ≤ x_i ≤ n,1 ≤ y_i ≤ m), which describes the position of the i-th obstacle.
It is guaranteed that no two obstacles are in the same cell and no obstacle is in cell (1, 1).
Output
Print 'Yes' (without quotes) if the doll can walk across all the cells without obstacles exactly once by the rules, described in the statement.
If it is impossible to walk across the maze by these rules print 'No' (without quotes).
Examples
Input
3 3 2
2 2
2 1
Output
Yes
Input
3 3 2
3 1
2 2
Output
No
Input
3 3 8
1 2
1 3
2 1
2 2
2 3
3 1
3 2
3 3
Output
Yes
Note
Here is the picture of maze described in the first example:
<image>
In the first example, the doll can walk in this way:
* The doll is in the cell (1, 1), looks to the direction 1. Move straight;
* The doll is in the cell (1, 2), looks to the direction 1. Move straight;
* The doll is in the cell (1, 3), looks to the direction 1. Turn right;
* The doll is in the cell (1, 3), looks to the direction 2. Move straight;
* The doll is in the cell (2, 3), looks to the direction 2. Move straight;
* The doll is in the cell (3, 3), looks to the direction 2. Turn right;
* The doll is in the cell (3, 3), looks to the direction 3. Move straight;
* The doll is in the cell (3, 2), looks to the direction 3. Move straight;
* The doll is in the cell (3, 1), looks to the direction 3. The goal is achieved, all cells of the maze without obstacles passed exactly once.
Submitted Solution:
```
a, b, k = map(int,input().split())
obsa = [[] for _ in range(a)]
obsb = [[] for _ in range(b)]
for _ in range(k):
x, y = map(int,input().split())
obsa[x-1].append(y-1)
obsb[y-1].append(x-1)
for l in obsa:l.sort()
for l in obsb:l.sort()
totals = a*b-k
bordera=[0,a-1]
borderb=[0,b-1]
state =0
discs=0
discnew=0
broken = False
while(discs <a*b-k and not broken):
print("___")
print(f"state: {state}")
print(bordera)
print(borderb)
if state==0: # go right
ff=-1
for f in obsa[bordera[0]]:
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if f>borderb[1]:
break
print(ff)
if ff > -1: # obstacle in range
borderb[1] = ff-1
discnew = borderb[1]-borderb[0]+1
bordera[0]+=1
elif state == 1: # go down
ff=-1
for f in obsb[borderb[1]]:
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if f>bordera[1]:
break
print(ff)
if ff > -1: # obstacle in range
bordera[1] = ff-1
discnew = bordera[1]-bordera[0]+1
borderb[1] -= 1
elif state == 2: # go left
ff=-1
for f in obsa[bordera[1]]:
if f>=borderb[0] and f<=borderb[1]:
ff=f
break
if f>borderb[1]:
break
print(ff)
if ff > -1: # obstacle in range
borderb[0] = ff+1
discnew = borderb[1]-borderb[0]+1
bordera[1]-=1
elif state == 3: # go up
ff=-1
for f in obsb[borderb[0]]:
if f>=bordera[0] and f<=bordera[1]:
ff=f
break
if f>bordera[1]:
break
print(ff)
if ff > -1: # obstacle in range
bordera[0] = ff+1
discnew = bordera[1]-bordera[0]+1
borderb[1] -= 1
state = (state+1)%4
if(discnew==0):
broken = True
discs += discnew
print(f"new discvs: {discnew}")
if (broken):
print("No")
else:
print("Yes")
``` | instruction | 0 | 10,050 | 15 | 20,100 |
No | output | 1 | 10,050 | 15 | 20,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Chanek just won the national chess tournament and got a huge chessboard of size N × M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. Chanek defines:
G(X, Y) = ∑_{i=X}^{N} ∑_{j=Y}^{M} F(i, j)
Given X and Y, you are tasked to find G(X, Y).
A knight can move from square (a, b) to square (a', b') if and only if |a - a'| > 0, |b - b'| > 0, and |a - a'| + |b - b'| = 3. Of course, the knight cannot leave the chessboard.
Input
The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases.
Each test case contains a line with four integers X Y N M (3 ≤ X ≤ N ≤ 10^9, 3 ≤ Y ≤ M ≤ 10^9).
Output
For each test case, print a line with the value of G(X, Y) modulo 10^9 + 7.
Example
Input
2
3 4 5 6
5 5 8 8
Output
27
70
Submitted Solution:
```
import itertools
def f(x):
scores = [0, 0]
for i in itertools.cycle([0, 1]):
if x & 1:
scores[i] += 1
x -= 1
elif x == 0:
return scores[0]
elif x & 0b10:
x >>= 1
scores[i] += x
else:
x -= 1
scores[i] += 1
N = int(input())
results = []
import sys
for n in map(f, map(int, sys.stdin.read().split())):
results.append(n)
print('\n'.join(map(str, results)))
``` | instruction | 0 | 10,140 | 15 | 20,280 |
No | output | 1 | 10,140 | 15 | 20,281 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Chanek just won the national chess tournament and got a huge chessboard of size N × M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. Chanek defines:
G(X, Y) = ∑_{i=X}^{N} ∑_{j=Y}^{M} F(i, j)
Given X and Y, you are tasked to find G(X, Y).
A knight can move from square (a, b) to square (a', b') if and only if |a - a'| > 0, |b - b'| > 0, and |a - a'| + |b - b'| = 3. Of course, the knight cannot leave the chessboard.
Input
The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases.
Each test case contains a line with four integers X Y N M (3 ≤ X ≤ N ≤ 10^9, 3 ≤ Y ≤ M ≤ 10^9).
Output
For each test case, print a line with the value of G(X, Y) modulo 10^9 + 7.
Example
Input
2
3 4 5 6
5 5 8 8
Output
27
70
Submitted Solution:
```
def sum_triangle(x,y,len):
if(len==0):
return 0
ans=0
if((x+y)%3==0):
a=len//3
ans+=(a*(a+1)*(2*a+1)*9)/6-(3*a*(a+1))/2
ans+=(3*a*(a+1))/2-a
if(len%3==1):
ans+=(len)*(a+1)
if(len%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len
ans+=((len*(len+1))/2)*((x+y)/3 -1)
return ans
if((x+y)%3==2):
ans+=0
a=(len-1)//3
ans+=(a*(a+1)*(2*a+1)*9)//6
ans+=(3*a*(a+1))//2
if((len-1)%3==1):
ans+=(len)*(a+1)
if((len-1)%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len
ans+=((len*(len+1))//2)*((x+y)//3)
return ans
if((x+y)%3==1):
ans+=0;
a=(len-2)//3
ans+=(a*(a+1)*(2*a+1)*9)//6+(3*a*(a+1))//2
ans+=1
ans+=(3*a*(a+1))//2+a
if((len-2)%3==1):
ans+=(len)*(a+1)
if((len-2)%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len;
ans+=((len*(len+1))//2)*((x+y)//3)
return ans
t=int(input())
for you in range(t):
l=input().split()
x=int(l[0])
y=int(l[1])
n=int(l[2])
m=int(l[3])
a=sum_triangle(x,y,(m-y+1)+(n-x+1))
b=sum_triangle(x,m+1,(n-x+1))
c=sum_triangle(n+1,y,(m-y+1))
if(x==3 and y==3):
a+=2
print(a-b-c)
``` | instruction | 0 | 10,141 | 15 | 20,282 |
No | output | 1 | 10,141 | 15 | 20,283 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Mr. Chanek just won the national chess tournament and got a huge chessboard of size N × M. Bored with playing conventional chess, Mr. Chanek now defines a function F(X, Y), which denotes the minimum number of moves to move a knight from square (1, 1) to square (X, Y). It turns out finding F(X, Y) is too simple, so Mr. Chanek defines:
G(X, Y) = ∑_{i=X}^{N} ∑_{j=Y}^{M} F(i, j)
Given X and Y, you are tasked to find G(X, Y).
A knight can move from square (a, b) to square (a', b') if and only if |a - a'| > 0, |b - b'| > 0, and |a - a'| + |b - b'| = 3. Of course, the knight cannot leave the chessboard.
Input
The first line contains an integer T (1 ≤ T ≤ 100), the number of test cases.
Each test case contains a line with four integers X Y N M (3 ≤ X ≤ N ≤ 10^9, 3 ≤ Y ≤ M ≤ 10^9).
Output
For each test case, print a line with the value of G(X, Y) modulo 10^9 + 7.
Example
Input
2
3 4 5 6
5 5 8 8
Output
27
70
Submitted Solution:
```
def sum_triangle(x,y,len):
if(len==0):
return 0
ans=0
if((x+y)%3==0):
a=len//3
ans+=(a*(a+1)*(2*a+1)*9)/6-(3*a*(a+1))/2
ans+=(3*a*(a+1))/2-a
if(len%3==1):
ans+=(len)*(a+1)
if(len%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len
ans+=((len*(len+1))/2)*((x+y)/3 -1)
return ans
if((x+y)%3==2):
ans+=0
a=(len-1)//3
ans+=(a*(a+1)*(2*a+1)*9)//6
ans+=(3*a*(a+1))//2
if((len-1)%3==1):
ans+=(len)*(a+1)
if((len-1)%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len
ans+=((len*(len+1))//2)*((x+y)//3)
return ans
if((x+y)%3==1):
ans+=0;
a=(len-2)//3
ans+=(a*(a+1)*(2*a+1)*9)//6+(3*a*(a+1))//2
ans+=1
ans+=(3*a*(a+1))//2+a
if((len-2)%3==1):
ans+=(len)*(a+1)
if((len-2)%3==2):
ans+=(len)*(a+1)+(len-1)*(a+1)
ans+=len;
ans+=((len*(len+1))//2)*((x+y)//3)
return ans
t=int(input())
for you in range(t):
l=input().split()
x=int(l[0])
y=int(l[1])
n=int(l[2])
m=int(l[3])
a=sum_triangle(x,y,(m-y+1)+(n-x+1))
b=sum_triangle(x,m+1,(n-x+1))
c=sum_triangle(n+1,y,(m-y+1))
if(x==3 and y==3):
a+=2
print((a-b-c)%1000000007)
``` | instruction | 0 | 10,142 | 15 | 20,284 |
No | output | 1 | 10,142 | 15 | 20,285 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,310 | 15 | 20,620 |
Tags: greedy, math
Correct Solution:
```
MOVS = [(2,-2),(-2,2),(-2,-2),(2,2)]
def check(a):
return 0<=a<8
set1 = set()
set2 = set()
dic1 = dict()
dic2 = dict()
def cango1(matrix,pos,lap):
for dx,dy in MOVS:
nx,ny = dx+pos[0],dy+pos[1]
if not check (nx) or not check(ny):
continue
if (nx,ny) in set1:
continue
dic1[(nx,ny)]=lap%2
set1.add((nx,ny))
cango1(matrix,(nx,ny),lap+1)
def cango2(matrix,pos,lap):
for dx,dy in MOVS:
nx,ny = dx+pos[0],dy+pos[1]
if not check(nx) or not check(ny):
continue
if (nx,ny) in set2:
continue
dic2[(nx,ny)]=lap%2
set2.add((nx,ny))
cango2(matrix,(nx,ny),lap+1)
q = int(input())
for ww in range(q):
matrix = [input().strip() for i in range(8)]
pos = []
for i in range(8):
for j in range(8):
if matrix[i][j] == 'K':
pos.append((i,j))
set1,set2,dic1,dic2=set(),set(),dict(),dict()
cango1(matrix, pos[0],0)
cango2(matrix,pos[1],0)
if ww!=q-1:
input()
sec = set1&set2
for x,y in sec:
if dic1[(x,y)]==dic2[(x,y)]:
print("YES")
break
else:
print("NO")
``` | output | 1 | 10,310 | 15 | 20,621 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,311 | 15 | 20,622 |
Tags: greedy, math
Correct Solution:
```
n = int(input())
for t in range(n):
if t: input()
board = [[c for c in input()] for i in range(8)]
k1, k2 = ((i, j) for i in range(8) for j in range(8) if board[i][j] == 'K')
if (k1[0] - k2[0]) % 4 == 0 and (k1[1] - k2[1]) % 4 == 0:
print('YES')
else:
print('NO')
``` | output | 1 | 10,311 | 15 | 20,623 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,312 | 15 | 20,624 |
Tags: greedy, math
Correct Solution:
```
def check():
board = []
for cont in range(0,8):
board.append(input())
l = True
for cont in range(0,8):
for cont2 in range(0,8):
if board[cont][cont2] == 'K':
if l:
xk1 = cont2
yk1 = cont
l = False
else:
xk2 = cont2
yk2 = cont
break
for cont in range(0,8):
for cont2 in range(0,8):
if cont2 %2 == xk1%2 == xk2%2:
if cont%2 == yk1%2 == yk2%2:
if abs(cont2-xk1)%4 == abs(cont2-xk2)%4:
if abs(cont-yk1)%4 == abs(cont-yk2)%4:
if board[cont][cont2] != '#':
print('YES')
return
print('NO')
return
n = int(input())
check()
for t in range(0,n-1):
a = str(input())
check()
``` | output | 1 | 10,312 | 15 | 20,625 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,313 | 15 | 20,626 |
Tags: greedy, math
Correct Solution:
```
import sys
import collections
class GetOutOfLoop(Exception):
pass
if __name__ == "__main__":
n_cases = int(sys.stdin.readline())
for case in range(n_cases):
board = [list(sys.stdin.readline().rstrip()) for i in range(8)]
knight_init_loc = [None, None]
knight = 0
for current_i in range(8):
for current_j in range(8):
if board[current_i][current_j] == 'K':
knight_init_loc[knight] = (current_i, current_j)
knight += 1
to_explore = collections.deque()
to_explore.append((knight_init_loc[0], 0))
explored = set()
try:
while len(to_explore) > 0:
((current_i, current_j), current_step) = to_explore.popleft()
explored.add((current_i, current_j))
candidates = set()
for inc_i in [-2, 2]:
for inc_j in [-2, 2]:
next_i, next_j = current_i + inc_i, current_j + inc_j
if 0 <= next_i < 8 and 0 <= next_j < 8 and (next_i, next_j) not in explored:
candidates.add(((next_i, next_j), current_step + 1))
for (s, next_step) in candidates:
if s == knight_init_loc[1] and next_step % 2 == 0:
print('YES')
raise GetOutOfLoop
to_explore.append((s, next_step))
current_step += 1
print('NO')
except GetOutOfLoop:
pass
sys.stdin.readline()
``` | output | 1 | 10,313 | 15 | 20,627 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,314 | 15 | 20,628 |
Tags: greedy, math
Correct Solution:
```
for i in range(int(input())):
if i :
input()
ans = []
for i in range(8):
s = input()
for j in range(8):
if s[j] == 'K':
ans.append((i, j))
print(['NO' , 'YES'][abs(ans[0][0] - ans[1][0]) % 4 == 0 and abs(ans[0][1] - ans[1][1]) % 4 == 0])
``` | output | 1 | 10,314 | 15 | 20,629 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,315 | 15 | 20,630 |
Tags: greedy, math
Correct Solution:
```
t = int(input())
for _ in range(t):
if _:
input()
knights = []
for i in range(8):
s = input().strip()
for j in range(8):
if s[j] == 'K':
knights.append((i,j))
n1 = knights[0]
n2 = knights[1]
"""
if n1[0] % 2 == n2[0] % 2 and n1[1] % 2 == n2[1] % 2:
c1 = n1[0]//2 + n1[1]//2
c2 = n2[1]//2 + n2[0]//2
if c1 % 2 == c2 % 2:
print('YES')
else:
print('NO')
"""
if n1[0] % 4 == n2[0] % 4 and n1[1] % 4 == n2[1] % 4:
print('YES')
else:
print('NO')
``` | output | 1 | 10,315 | 15 | 20,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,316 | 15 | 20,632 |
Tags: greedy, math
Correct Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
from collections import deque
def dfs(graph, alpha=0):
"""Breadth first search on a graph!"""
n = len(graph)
q = deque([alpha])
used = [False]*n
used[alpha] = True
dist, parents = [0]*n, [-1]*n
while q:
v = q.popleft()
for u in graph[v]:
if not used[u]:
used[u] = True
q.append(u)
dist[u] = dist[v] + 1
parents[u] = v
return used, dist
for _ in range(int(input()) if True else 1):
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
a = []
def pos(i,j):
return i*8+j+1
for i in range(8):
a += [[k for k in input()]]
graph = [[] for i in range(65)]
ks = []
for i in range(8):
for j in range(8):
if a[i][j] == "K":ks += [pos(i,j)]
if 1:
if i+2 < 8:
if 0<=j+2 <8:
graph[pos(i,j)] += [pos(i+2,j+2)]
graph[pos(i+2, j+2)] += [pos(i,j)]
if 0<=j-2<8:
graph[pos(i,j)] += [pos(i+2,j-2)]
graph[pos(i+2, j-2)] += [pos(i,j)]
if 0<=i-2<8:
if 0<=j+2 <8:
graph[pos(i,j)] += [pos(i-2,j+2)]
graph[pos(i-2, j+2)] += [pos(i,j)]
if 0<=j-2<8:
graph[pos(i,j)] += [pos(i-2,j-2)]
graph[pos(i-2, j-2)] += [pos(i,j)]
d1,dist1 = dfs(graph, ks[0])
d2,dist2 = dfs(graph,ks[1])
found = False
for i in range(1,len(d1)):
if d1[i] and d2[i] and dist1[i] == dist2[i]:
print("YES")
found=True
break
if not found:
print("NO")
x=input()
``` | output | 1 | 10,316 | 15 | 20,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet. | instruction | 0 | 10,317 | 15 | 20,634 |
Tags: greedy, math
Correct Solution:
```
def check(x, y):
return 0 <= x < 8 and 0 <= y < 8
def dfs1(x, y, T=0):
global first, used
if not(check(x, y)) or used[x][y]:
return
used[x][y] = True
first.add((x, y, T))
for pair in (2, 2), (2, -2), (-2, 2), (-2, -2):
dfs1(x + pair[0], y + pair[1], 1 - T)
def dfs2(x, y, T=0):
global second, used
if not(check(x, y)) or used[x][y]:
return
used[x][y] = True
second.add((x, y, T))
for pair in (2, 2), (2, -2), (-2, 2), (-2, -2):
dfs2(x + pair[0], y + pair[1], 1 - T)
t = int(input())
for i in range(t):
if i > 0:
kuzma = input()
board = [input() for i in range(8)]
FoundFirst = False
for i in range(8):
for j in range(8):
if board[i][j] == 'K':
if not(FoundFirst):
First = (i, j)
FoundFirst = True
else:
Second = (i, j)
used = [[0 for i in range(8)] for j in range(8)]
first = set()
dfs1(First[0], First[1])
used = [[0 for i in range(8)] for j in range(8)]
second = set()
dfs2(Second[0], Second[1])
intersection = first & second
IsOk = False
for x, y, t in intersection:
if board[x][y] != '#':
print("YES")
IsOk = True
break
if not(IsOk):
print("NO")
board = []
``` | output | 1 | 10,317 | 15 | 20,635 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
t = int(input())
for k in range(t):
r8 = range(8)
a = [input() for i in r8]
ij = [(i, j) for i in r8 for j in r8]
x, y = ((i, j) for i, j in ij if a[i][j] == "K")
def s(p):
d = [(p[0] - 2, p[1] - 2), (p[0] + 2, p[1] - 2), (p[0] - 2, p[1] + 2), (p[0] + 2, p[1] + 2)]
return set((i, j) for i, j in ij if (i, j) in d)
print("YES" if len(s(x) & s(y)) > 0 else "NO")
if k != t - 1:
input()
``` | instruction | 0 | 10,318 | 15 | 20,636 |
Yes | output | 1 | 10,318 | 15 | 20,637 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
def solve(m, x,y , w,z):
for i in range(8):
for j in range(8):
if m[i][j]:
a, pa = movePossible(x,y , i,j)
b, pb = movePossible(w,z , i,j)
if a and b and pa==pb:
return True
return False
def movePossible(x,y , w,z):
a = x-w
b = y-z
pos=False
ka=a//2
kb=b//2
if a%2==0 and b%2==0 and (ka+kb)%2==0:
pos=True
return pos, ka%2
t = int(input())
for _c in range(t):
m = []
primo = True
for i in range(8):
m.append([])
s = input()
k=0
for c in s:
if c=='#':
m[i].append( False )
else:
m[i].append( True )
if c=='K' and primo:
x=i
y= k
primo = False
if c=='K' and (not primo):
w=i
z= k
k+=1
if solve(m, x,y , w,z):
print("YES")
else:
print("NO")
if _c!=t-1: m=input()
``` | instruction | 0 | 10,319 | 15 | 20,638 |
Yes | output | 1 | 10,319 | 15 | 20,639 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
t = int(input())
for _ in range(t):
s = [input() for i in range(8)]
oh = True
flag = True
for i in range(8):
for j in range(8):
if(s[i][j] == 'K'):
if(flag):
pos1x = i
pos1y = j
flag = False
else:
pos2x = i
pos2y = j
if(pos1x % 4 == pos2x % 4) and (pos1y % 4 == pos2y % 4):
print('YES')
else:
print('NO')
if( _ < t - 1):
k = input()
``` | instruction | 0 | 10,320 | 15 | 20,640 |
Yes | output | 1 | 10,320 | 15 | 20,641 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
T=int(input())
for t in range(T):
L=[]
for i in range(8):
L.append(input())
Moves1=[]
Moves2=[]
K=[]
for i in range(8):
Moves1.append([-1]*8)
Moves2.append([-1]*8)
for j in range(8):
if(L[i][j]=='K'):
K.append((i,j))
Now=K[0]
Explored=[(Now[0],Now[1],0)]
Moves1[Now[0]][Now[1]]=0
while(len(Explored)!=0):
x=Explored[0][0]
y=Explored[0][1]
p=Explored[0][2]
Explored.pop(0)
if(x-2>=0 and y-2>=0):
if(Moves1[x-2][y-2]==-1):
Moves1[x-2][y-2]=1-p
Explored.append((x-2,y-2,1-p))
if(x+2<8 and y-2>=0):
if(Moves1[x+2][y-2]==-1):
Moves1[x+2][y-2]=1-p
Explored.append((x+2,y-2,1-p))
if(x-2>=0 and y+2<8):
if(Moves1[x-2][y+2]==-1):
Moves1[x-2][y+2]=1-p
Explored.append((x-2,y+2,1-p))
if(x+2<8 and y+2<8):
if(Moves1[x+2][y+2]==-1):
Moves1[x+2][y+2]=1-p
Explored.append((x+2,y+2,1-p))
Now=K[1]
Explored=[(Now[0],Now[1],0)]
Moves2[Now[0]][Now[1]]=0
while(len(Explored)!=0):
x=Explored[0][0]
y=Explored[0][1]
p=Explored[0][2]
Explored.pop(0)
if(x-2>=0 and y-2>=0):
if(Moves2[x-2][y-2]==-1):
Moves2[x-2][y-2]=1-p
Explored.append((x-2,y-2,1-p))
if(x+2<8 and y-2>=0):
if(Moves2[x+2][y-2]==-1):
Moves2[x+2][y-2]=1-p
Explored.append((x+2,y-2,1-p))
if(x-2>=0 and y+2<8):
if(Moves2[x-2][y+2]==-1):
Moves2[x-2][y+2]=1-p
Explored.append((x-2,y+2,1-p))
if(x+2<8 and y+2<8):
if(Moves2[x+2][y+2]==-1):
Moves2[x+2][y+2]=1-p
Explored.append((x+2,y+2,1-p))
valid=False
for i in range(8):
for j in range(8):
if(Moves1[i][j]!=-1 and Moves1[i][j]==Moves2[i][j] and L[i][j]!="#"):
valid=True
if(valid):
print("YES")
else:
print("NO")
if(t!=T-1):
s=input()
``` | instruction | 0 | 10,321 | 15 | 20,642 |
Yes | output | 1 | 10,321 | 15 | 20,643 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
t = int(input())
oh = False
v = [[False] * 100 for i in range(100)]
def dfs(i, j, x ,y):
global oh
v[i][j] = True
if(i == x) and (j == y) and (oh == True):
oh = False
print("YES")
else:
if(i > 1) & (j > 1) & (v[i - 2][j - 2] == False):
dfs(i - 2, j - 2, x, y)
if(i + 2 < 8) & (j + 2 < 8) & (v[i + 2][j + 2] == False):
dfs(i + 2, j + 2, x, y)
if(i > 1) & (j + 2 < 8) & (v[i - 2][j + 2] == False):
dfs(i - 2, j + 2, x, y)
if(i + 2 < 8) & (j > 1) & (v[i + 2][j - 2] == False):
dfs(i + 2, j - 2, x, y)
for _ in range(t):
s = [input() for i in range(8)]
oh = True
flag = True
for i in range(8):
for j in range(8):
if(s[i][j] == 'K'):
if(flag):
pos1x = i
pos1y = j
flag = False
else:
pos2x = i
pos2y = j
dfs(pos1x, pos1y, pos2x, pos2y)
if(oh == True):
print("NO")
if ( _ < t - 1):
k = input()
``` | instruction | 0 | 10,322 | 15 | 20,644 |
No | output | 1 | 10,322 | 15 | 20,645 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
def main():
n = int(input())
out = ""
for t in range(n):
knights = [0 for i in range(16)]
valid = [False for i in range(16)]
for i in range(8):
line = input()
#print()
for j in range(8):
#print(get(i, j), end="\t")
if line[j] != '#':
valid[get(i, j)] = True
if line[j] == 'K':
knights[get(i, j)] += 1
for i in range(16):
#print(i, knights[i], valid[i])
if knights[i] == 2 and valid[i]:
out += "YES\n"
break
else:
out += "NO\n"
if t != n-1:
input()
print(out[:-1])
def get(i, j):
x = (i%2)*8 + j
if i % 4 > 1:
x = (i%2)*8 + (j+2)%4 + (j//4)*2
if j > 3:
x += 2
return x
if __name__ == "__main__": main()
``` | instruction | 0 | 10,323 | 15 | 20,646 |
No | output | 1 | 10,323 | 15 | 20,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
import sys
import math
import collections
import heapq
t=int(input())
for w in range(t):
l=[]
for i in range(8):
l1=list(input())
l.append(l1)
t1,t2=(),()
for i in range(8):
for j in range(8):
if(l[i][j]=='K'):
if(t1==()):
t1=(i,j)
else:
t2=(i,j)
break
if(t2!=()):
break
k=max(abs(t1[0]-t2[0])-1,0)+max(abs(t1[1]-t2[1])-1,0)
if(t1[0]!=t2[0] and t1[1]!=t2[1]):
k+=1
if(k%4==3):
print("YES")
else:
print("NO")
if(w<t-1):
input()
``` | instruction | 0 | 10,324 | 15 | 20,648 |
No | output | 1 | 10,324 | 15 | 20,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
A boy Petya loves chess very much. He even came up with a chess piece of his own, a semiknight. The semiknight can move in any of these four directions: 2 squares forward and 2 squares to the right, 2 squares forward and 2 squares to the left, 2 squares backward and 2 to the right and 2 squares backward and 2 to the left. Naturally, the semiknight cannot move beyond the limits of the chessboard.
Petya put two semiknights on a standard chessboard. Petya simultaneously moves with both semiknights. The squares are rather large, so after some move the semiknights can meet, that is, they can end up in the same square. After the meeting the semiknights can move on, so it is possible that they meet again. Petya wonders if there is such sequence of moves when the semiknights meet. Petya considers some squares bad. That is, they do not suit for the meeting. The semiknights can move through these squares but their meetings in these squares don't count.
Petya prepared multiple chess boards. Help Petya find out whether the semiknights can meet on some good square for each board.
Please see the test case analysis.
Input
The first line contains number t (1 ≤ t ≤ 50) — the number of boards. Each board is described by a matrix of characters, consisting of 8 rows and 8 columns. The matrix consists of characters ".", "#", "K", representing an empty good square, a bad square and the semiknight's position, correspondingly. It is guaranteed that matrix contains exactly 2 semiknights. The semiknight's squares are considered good for the meeting. The tests are separated by empty line.
Output
For each test, print on a single line the answer to the problem: "YES", if the semiknights can meet and "NO" otherwise.
Examples
Input
2
........
........
......#.
K..##..#
.......#
...##..#
......#.
K.......
........
........
..#.....
..#..#..
..####..
...##...
........
....K#K#
Output
YES
NO
Note
Consider the first board from the sample. We will assume the rows and columns of the matrix to be numbered 1 through 8 from top to bottom and from left to right, correspondingly. The knights can meet, for example, in square (2, 7). The semiknight from square (4, 1) goes to square (2, 3) and the semiknight goes from square (8, 1) to square (6, 3). Then both semiknights go to (4, 5) but this square is bad, so they move together to square (2, 7).
On the second board the semiknights will never meet.
Submitted Solution:
```
# ------------------- fast io --------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------- fast io --------------------
from math import gcd, ceil
def pre(s):
n = len(s)
pi = [0] * n
for i in range(1, n):
j = pi[i - 1]
while j and s[i] != s[j]:
j = pi[j - 1]
if s[i] == s[j]:
j += 1
pi[i] = j
return pi
def prod(a):
ans = 1
for each in a:
ans = (ans * each)
return ans
def lcm(a, b): return a * b // gcd(a, b)
def binary(x, length=16):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def dfs(graph, alpha):
"""Depth First Search on a graph!"""
n = len(graph)
visited = [False]*n
stack = [alpha]
while stack:
v = stack[-1]
if not visited[v]:
visited[v] = True
for u in graph[v]:
if not visited[u]:
stack.append(u)
else:
stack.pop()
return visited
for _ in range(int(input()) if True else 1):
#n, k = map(int, input().split())
#a, b = map(int, input().split())
#c, d = map(int, input().split())
#a = list(map(int, input().split()))
#b = list(map(int, input().split()))
#s = input()
a = []
def pos(i,j):
return i*8+j+1
for i in range(8):
a += [[k for k in input()]]
graph = [[] for i in range(65)]
ks = []
for i in range(8):
for j in range(8):
if a[i][j] == "K":ks += [pos(i,j)]
if a[i][j] != "#":
if i+2 < 8:
if 0<=j+2 <8:
if a[i+2][j+2] != "#":
graph[pos(i,j)] += [pos(i+2,j+2)]
graph[pos(i+2, j+2)] += [pos(i,j)]
if 0<=j-2<8:
if a[i+2][j-2] != "#":
graph[pos(i,j)] += [pos(i+2,j-2)]
graph[pos(i+2, j-2)] += [pos(i,j)]
if 0<=i-2<8:
if 0<=j+2 <8:
if a[i-2][j+2] != "#":
graph[pos(i,j)] += [pos(i-2,j+2)]
graph[pos(i-2, j+2)] += [pos(i,j)]
if 0<=j-2<8:
if a[i-2][j-2] != "#":
graph[pos(i,j)] += [pos(i-2,j-2)]
graph[pos(i-2, j-2)] += [pos(i,j)]
d1 = dfs(graph, ks[0])
d2 = dfs(graph,ks[1])
found = False
for i in range(len(d1)):
if d1[i] and d2[i]:
print("YES")
found=True
break
if not found:
print("NO")
x=input()
``` | instruction | 0 | 10,325 | 15 | 20,650 |
No | output | 1 | 10,325 | 15 | 20,651 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,798 | 15 | 21,596 |
Tags: geometry
Correct Solution:
```
n, d = map(int, input().split())
count = int(input())
for i in range(count):
x, y = map(int, input().split())
if (y>=x-d) and (y>=-x+d) and (y<=x+d) and (y<=-x+n*2-d):
print('YES')
else:
print('NO')
``` | output | 1 | 10,798 | 15 | 21,597 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,799 | 15 | 21,598 |
Tags: geometry
Correct Solution:
```
n, d = map(int, input().split())
m = int(input())
for _ in range(m) :
x, y = map(int, input().split())
if (x + y) >= d and (x + y) <= n + n - d and (x - y) >= -d and (x - y) <= d :
print("YES")
else :
print("NO")
``` | output | 1 | 10,799 | 15 | 21,599 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,800 | 15 | 21,600 |
Tags: geometry
Correct Solution:
```
n, d = [int(i) for i in input().split()]
m = int(input())
for i in range(m):
x, y = [int(i) for i in input().split()]
if y <= n - abs(x - n + d) and y >= abs(x - d):
print('YES')
else:
print('NO')
``` | output | 1 | 10,800 | 15 | 21,601 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,801 | 15 | 21,602 |
Tags: geometry
Correct Solution:
```
def inF(d,n,x,y):
mg = 0.7071067811865475
x1 = (x-y)*mg
y1 = (x+y)*mg
if x1>=-d*mg and x1<=d*mg:
if y1>=d*mg and y1<=(2*n-d)*mg:
return True
return False
n,d = list(map(int,input().split()))
m=int(input())
x=[]
y=[]
for i in range(m):
x1,y1 = list(map(int,input().split()))
x.append(x1)
y.append(y1)
for i in range(m):
if inF(d,n,x[i],y[i]):
print('YES')
else:
print('NO')
``` | output | 1 | 10,801 | 15 | 21,603 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,802 | 15 | 21,604 |
Tags: geometry
Correct Solution:
```
n, d = map(int, input().split())
q = int(input())
for i in range(q):
x, y = map(int, input().split())
if x >= d - y and y <= 2 * n - d - x and abs(x - y) <= d:
print("YES")
else:
print("NO")
``` | output | 1 | 10,802 | 15 | 21,605 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,803 | 15 | 21,606 |
Tags: geometry
Correct Solution:
```
#------------------------------what is this I don't know....just makes my mess faster--------------------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#----------------------------------Real game starts here--------------------------------------
'''
___________________THIS IS AESTROIX CODE________________________
KARMANYA GUPTA
'''
n , d = list(map(int, input().split()))
for i in range(int(input())):
x , y = list(map(int, input().split()))
a = y-x
b = y+x
if a < d and a > -d and b > d and b < 2*n - d:
print("YES")
elif a == d or a == -d or b == d or b == 2*n - d:
print("YES")
else:
print("NO")
``` | output | 1 | 10,803 | 15 | 21,607 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,804 | 15 | 21,608 |
Tags: geometry
Correct Solution:
```
n, d = list(map(int, input().split()))
m = int(input())
def lfunc(x1, y1, x2, y2, x):
if x2!=x1:
k = (y2 - y1)/(x2-x1)
else:
k = 0
b = y1 - k * x1
return k*x+b
k = 0
for i in range(m):
x, y = list(map(int, input().split()))
if y<=lfunc(0,d,n-d,n,x) and y>=lfunc(d,0,n,n-d,x)\
and y<=lfunc(n,n-d,n-d,n,x) and y>=lfunc(d,0,0,d,x):
print('YES')
else:
print('NO')
``` | output | 1 | 10,804 | 15 | 21,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Vasya owns a cornfield which can be defined with two integers n and d. The cornfield can be represented as rectangle with vertices having Cartesian coordinates (0, d), (d, 0), (n, n - d) and (n - d, n).
<image> An example of a cornfield with n = 7 and d = 2.
Vasya also knows that there are m grasshoppers near the field (maybe even inside it). The i-th grasshopper is at the point (x_i, y_i). Vasya does not like when grasshoppers eat his corn, so for each grasshopper he wants to know whether its position is inside the cornfield (including the border) or outside.
Help Vasya! For each grasshopper determine if it is inside the field (including the border).
Input
The first line contains two integers n and d (1 ≤ d < n ≤ 100).
The second line contains a single integer m (1 ≤ m ≤ 100) — the number of grasshoppers.
The i-th of the next m lines contains two integers x_i and y_i (0 ≤ x_i, y_i ≤ n) — position of the i-th grasshopper.
Output
Print m lines. The i-th line should contain "YES" if the position of the i-th grasshopper lies inside or on the border of the cornfield. Otherwise the i-th line should contain "NO".
You can print each letter in any case (upper or lower).
Examples
Input
7 2
4
2 4
4 1
6 3
4 5
Output
YES
NO
NO
YES
Input
8 7
4
4 4
2 8
8 1
6 1
Output
YES
NO
YES
YES
Note
The cornfield from the first example is pictured above. Grasshoppers with indices 1 (coordinates (2, 4)) and 4 (coordinates (4, 5)) are inside the cornfield.
The cornfield from the second example is pictured below. Grasshoppers with indices 1 (coordinates (4, 4)), 3 (coordinates (8, 1)) and 4 (coordinates (6, 1)) are inside the cornfield.
<image> | instruction | 0 | 10,805 | 15 | 21,610 |
Tags: geometry
Correct Solution:
```
n,d = map(int,input().split())
m = int(input())
ans = []
for i in range(m):
x1,y1 = map(int,input().split())
t1 = x1+y1
t2 = x1-y1
if t1>=d and t1<=(2*n-d) and t2>=(-d) and t2<=d:
ans.append('YES')
else:
ans.append('NO')
for i in ans:
print(i)
``` | output | 1 | 10,805 | 15 | 21,611 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field.
The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | instruction | 0 | 10,815 | 15 | 21,630 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
xy = input().split(" ")
x = int(xy[0])
y = int(xy[1])
wx = 1
wy = 1
bx = n
by = n
if x < y:
white = (x-1) + (y-x)
black = (n-y) + (y-x)
else:
white = (y-1) + (x-y)
black = (n-x) + (x-y)
if white <= black:
print('White')
else:
print('Black')
``` | output | 1 | 10,815 | 15 | 21,631 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field.
The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | instruction | 0 | 10,816 | 15 | 21,632 |
Tags: implementation, math
Correct Solution:
```
def go():
n = int(input())
x, y = [int(i) for i in input().split(' ')]
a = 1 + 1
b = n + n
c = x + y
distance_w = c - a
distance_b = b - c
if distance_w == distance_b:
return 'White'
if distance_w < distance_b:
return 'White'
return 'Black'
print(go())
``` | output | 1 | 10,816 | 15 | 21,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field.
The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | instruction | 0 | 10,817 | 15 | 21,634 |
Tags: implementation, math
Correct Solution:
```
gcd = lambda a, b: gcd(b, a % b) if b else a
def main():
n = int(input())
x, y = map(int, input().split())
if max(n - x, n - y) < max(x - 1, y - 1):
print("Black")
else:
print("White")
main()
``` | output | 1 | 10,817 | 15 | 21,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field.
The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | instruction | 0 | 10,818 | 15 | 21,636 |
Tags: implementation, math
Correct Solution:
```
n = int(input())
[x,y] = [int(x) for x in input().split()]
xw = yw = 1
xb = yb = n
maxi = max(x,y)
mini = min(x,y)
sw = mini-xw + maxi-mini
sb = xb-maxi + maxi-mini
if sw <= sb:
print('White')
else:
print('Black')
``` | output | 1 | 10,818 | 15 | 21,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
On a chessboard with a width of n and a height of n, rows are numbered from bottom to top from 1 to n, columns are numbered from left to right from 1 to n. Therefore, for each cell of the chessboard, you can assign the coordinates (r,c), where r is the number of the row, and c is the number of the column.
The white king has been sitting in a cell with (1,1) coordinates for a thousand years, while the black king has been sitting in a cell with (n,n) coordinates. They would have sat like that further, but suddenly a beautiful coin fell on the cell with coordinates (x,y)...
Each of the monarchs wanted to get it, so they decided to arrange a race according to slightly changed chess rules:
As in chess, the white king makes the first move, the black king makes the second one, the white king makes the third one, and so on. However, in this problem, kings can stand in adjacent cells or even in the same cell at the same time.
The player who reaches the coin first will win, that is to say, the player who reaches the cell with the coordinates (x,y) first will win.
Let's recall that the king is such a chess piece that can move one cell in all directions, that is, if the king is in the (a,b) cell, then in one move he can move from (a,b) to the cells (a + 1,b), (a - 1,b), (a,b + 1), (a,b - 1), (a + 1,b - 1), (a + 1,b + 1), (a - 1,b - 1), or (a - 1,b + 1). Going outside of the field is prohibited.
Determine the color of the king, who will reach the cell with the coordinates (x,y) first, if the white king moves first.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^{18}) — the length of the side of the chess field.
The second line contains two integers x and y (1 ≤ x,y ≤ n) — coordinates of the cell, where the coin fell.
Output
In a single line print the answer "White" (without quotes), if the white king will win, or "Black" (without quotes), if the black king will win.
You can print each letter in any case (upper or lower).
Examples
Input
4
2 3
Output
White
Input
5
3 5
Output
Black
Input
2
2 2
Output
Black
Note
An example of the race from the first sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (4,4) into the cell (3,3).
3. The white king moves from the cell (2,2) into the cell (2,3). This is cell containing the coin, so the white king wins.
<image>
An example of the race from the second sample where both the white king and the black king move optimally:
1. The white king moves from the cell (1,1) into the cell (2,2).
2. The black king moves form the cell (5,5) into the cell (4,4).
3. The white king moves from the cell (2,2) into the cell (3,3).
4. The black king moves from the cell (4,4) into the cell (3,5). This is the cell, where the coin fell, so the black king wins.
<image>
In the third example, the coin fell in the starting cell of the black king, so the black king immediately wins.
<image> | instruction | 0 | 10,819 | 15 | 21,638 |
Tags: implementation, math
Correct Solution:
```
n=int(input())
a,b=map(int,input().split())
a,b=min(a,b),max(a,b)
x=a-1+b-a
y=n-b+b-a
if(x<=y):
print("White")
else:
print("Black")
``` | output | 1 | 10,819 | 15 | 21,639 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.