message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3 | instruction | 0 | 77,677 | 13 | 155,354 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
"""
NTC here
"""
import sys
# reader = (s.rstrip() for s in sys.stdin)
# input = reader.__next__
inp = sys.stdin.readline
def input(): return inp().strip()
out = []
# flush = sys.stdout.flush
# import threading
# sys.setrecursionlimit(10**7)
# threading.stack_size(2**25)
def iin(): return int(input())
def lin(): return list(map(int, input().split()))
# range = xrange
# input = raw_input
INF = 10**5+7
n = iin()
adj = [[] for i in range(n+1)]
for _ in range(n-1):
i, j = lin()
adj[i].append(j)
adj[j].append(i)
# LCA - lowest common ancestor
def dfs(adj, start=1):
n = len(adj)
visited = [False]*n
first = [-1]*n
euler = []
height = [-1]*n
srt = [start]
height[start] = 1
parent = [-1]*n
while srt:
v = srt.pop()
if visited[v]:
euler.append(v)
continue
first[v] = len(euler)
euler.append(v)
visited[v] = True
if parent[v] != -1:
srt.append(parent[v])
for u in adj[v]:
if not visited[u]:
parent[u] = v
height[u] = height[v]+1
srt.append(u)
return first, euler, height
# segment tree
first, euler, height = dfs(adj)
# print(first, euler, height)
euler = [height[i] for i in euler]
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, begin, end):
end+=1
depth = (end - begin).bit_length() - 1
return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])
sa = RangeQuery(euler)
def check(i, j):
l, r = first[i], first[j]
if l > r:
l, r = r, l
h = sa.query(l, r)
#print("CHK", l, r, h, i, j)
return height[i] + height[j] - 2*h
# print(euler)
q = iin()
while q:
q -= 1
x, y, a, b, k = lin()
ans1 = [check(a, b), check(a, x)+1+check(y, b),
check(a, y)+1+check(x, b)]
for i in ans1:
if ((k-i) >= 0 and (k-i) % 2 == 0):
out.append('YES')
break
else:
out.append('NO')
# print(ans, ans1)
# out.append('YES' if True in ans else 'NO')
print('\n'.join(out))
# main()
# threading.Thread(target=main).start()
``` | output | 1 | 77,677 | 13 | 155,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3 | instruction | 0 | 77,678 | 13 | 155,356 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
import math
import collections
import bisect
import heapq
import time
import random
import itertools
import sys
from typing import List
from functools import lru_cache
"""
created by shhuan at 2020/3/18 19:28
"""
def solve(N, edges, queries):
LIM = 20
parent = [[0 for _ in range(LIM)] for _ in range(N+1)]
depth = [0 for _ in range(N + 1)]
def build(u, p):
# depth[u] = depth[p] + 1
# parent[u][0] = p
# for i in range(1, LIM):
# parent[u][i] = parent[parent[u][i-1]][i-1]
# for v in edges[u]:
# if v != p:
# build(v, u)
q = [(u, p)]
while q:
nq = []
for u, p in q:
depth[u] = depth[p] + 1
parent[u][0] = p
for i in range(1, LIM):
parent[u][i] = parent[parent[u][i-1]][i-1]
for v in edges[u]:
if v != p:
nq.append((v, u))
q = nq
def dist(x, y):
if depth[x] > depth[y]:
x, y = y, x
d = 0
for i in range(LIM-1, -1, -1):
if depth[parent[y][i]] >= depth[x]:
y = parent[y][i]
d += 1 << i
if x == y:
return d
for i in range(LIM-1, -1, -1):
if parent[x][i] != parent[y][i]:
x = parent[x][i]
y = parent[y][i]
d += 1 << (i + 1)
return d + 2
def checkparity(u, v):
return u <= v and u % 2 == v % 2
build(1, 0)
ans = []
for x, y, a, b, k in quries:
dxy = 1 if x != y else 0
d = dist(a, b)
if checkparity(d, k):
ans.append('YES')
continue
d = dist(a, x) + dist(y, b) + dxy
if checkparity(d, k):
ans.append('YES')
continue
d = dist(a, y) + dist(x, b) + dxy
if checkparity(d, k):
ans.append('YES')
continue
ans.append('NO')
return '\n'.join(ans)
N = int(input())
edges = collections.defaultdict(list)
for i in range(N-1):
u, v = map(int, input().split())
edges[u].append(v)
edges[v].append(u)
M = int(input())
quries = []
for i in range(M):
x, y, a, b, k = map(int, input().split())
quries.append((x, y, a, b, k))
print(solve(N, edges, quries))
``` | output | 1 | 77,678 | 13 | 155,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3 | instruction | 0 | 77,679 | 13 | 155,358 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial, log2, floor
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
gp = [[] for _ in range(n+1)]
for _ in range(n-1):
f, t = RL()
gp[f].append(t)
gp[t].append(f)
mxd = floor(log2(n))
marr = [[0]*(mxd+1) for _ in range(n+1)]
par = [1]*(n+1)
deep = [0]*(n+1)
vis = [0]*(n+1)
q = deque()
q.append((1, 0))
vis[1] = 1
while q:
nd, d = q.popleft()
deep[nd] = d
marr[nd][0] = par[nd]
for i in range(1, mxd+1):
if 2**i>d: break
marr[nd][i] = marr[marr[nd][i-1]][i-1]
for nex in gp[nd]:
if vis[nex]==1: continue
vis[nex] = 1
par[nex] = nd
q.append((nex, d+1))
# for i in marr:
# print(i)
def lca(a, b):
ta, tb = a, b
if deep[a]>deep[b]:
a, b = b, a
for i in range(mxd, -1, -1):
if marr[b][i]!=-1 and deep[marr[b][i]]>=deep[a]:
b = marr[b][i]
if a==b: return deep[ta]-deep[a]+deep[tb]-deep[a]
for i in range(mxd, -1, -1):
if marr[b][i] != marr[a][i]:
a = marr[a][i]
b = marr[b][i]
ld = par[a] if a!=b else a
return deep[ta]-deep[ld]+deep[tb]-deep[ld]
qn = N()
for _ in range(qn):
x, y, a, b, k = RL()
lst = k & 1
dis = lca(a, b)
disaxyb = (lca(a, x) + lca(y, b) + 1)
disayxb = (lca(a, y) + lca(x, b) + 1)
if (dis<=k and dis&1==lst) or (disaxyb<=k and disaxyb&1==lst) or (disayxb<=k and disayxb&1==lst):
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
``` | output | 1 | 77,679 | 13 | 155,359 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3 | instruction | 0 | 77,680 | 13 | 155,360 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
N = int(input())
G = [set() for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
G[a].add(b)
G[b].add(a)
S = [None]*(2*N-1)
F = [None]*(N+1)
stack = [1]
visited = set()
depth = [None]*(N+1)
depth[1] = 0
path = []
ii = 0
while stack:
v = stack.pop()
if v > 0:
visited.add(v)
path.append(v)
F[v], S[ii] = ii, v
ii += 1
for u in G[v]:
if u in visited:
continue
stack += [-v, u]
depth[u] = depth[v] + 1
else:
child = path.pop()
S[ii] = -v
ii += 1
INF = (N, None)
M = 2*N
M0 = 2**(M-1).bit_length()
data = [INF]*(2*M0)
for i, v in enumerate(S):
data[M0-1+i] = (depth[v], i)
for i in range(M0-2, -1, -1):
data[i] = min(data[2*i+1], data[2*i+2])
def _query(a, b):
yield INF
a, b = a + M0, b + M0
while a < b:
if b & 1:
b -= 1
yield data[b-1]
if a & 1:
yield data[a-1]
a += 1
a, b = a >> 1, b >> 1
def query(u, v):
fu, fv = F[u], F[v]
if fu > fv:
fu, fv = fv, fu
return S[min(_query(fu, fv+1))[1]]
def dist(x, y):
c = query(x, y)
return depth[x] + depth[y] - 2*depth[c]
Q = int(input())
for _ in range(Q):
x, y, a, b, k = map(int, input().split())
t1 = dist(a, b)
t2 = min(dist(a, x)+dist(y, b), dist(a, y)+dist(x, b)) + 1
if t1 <= k and (t1-k) % 2 == 0:
print("YES")
elif t2 <= k and (t2-k) % 2 == 0:
print("YES")
else:
print("NO")
``` | output | 1 | 77,680 | 13 | 155,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
# by the authority of GOD author: manhar singh sachdev #
import os,sys
from io import BytesIO, IOBase
def euler_path(n,path):
height = [0]*n+[10**10]
euler,st,visi,he = [],[0],[1]+[0]*(n-1),0
first = [-1]*n
while len(st):
x = st[-1]
euler.append(x)
if first[x] == -1:
first[x] = len(euler)-1
while len(path[x]) and visi[path[x][-1]]:
path[x].pop()
if not len(path[x]):
he -= 1
st.pop()
else:
i = path[x].pop()
he += 1
st.append(i)
height[i],visi[i] = he,1
return height,euler,first
def cons(euler,height):
n = len(euler)
xx = n.bit_length()
dp = [[n]*n for _ in range(xx)]
dp[0] = euler
for i in range(1,xx):
for j in range(n-(1<<i)+1):
a,b = dp[i-1][j],dp[i-1][j+(1<<(i-1))]
dp[i][j] = a if height[a] < height[b] else b
return dp
def lca(l,r,dp,height,first):
l,r = first[l],first[r]
if l > r:
l,r = r,l
xx1 = (r-l+1).bit_length()-1
a,b = dp[xx1][l],dp[xx1][r-(1<<xx1)+1]
return a if height[a] < height[b] else b
def dis(a,b,dp,height,first):
return height[a]+height[b]-2*height[lca(a,b,dp,height,first)]
def main():
n = int(input())
path = [[] for _ in range(n)]
for _ in range(n-1):
u1,v1 = map(int,input().split())
path[u1-1].append(v1-1)
path[v1-1].append(u1-1)
height,euler,first = euler_path(n,path)
dp = cons(euler,height)
for _ in range(int(input())):
x,y,a,b,k = map(lambda xx:int(xx)-1,input().split())
k += 1
z = dis(a,b,dp,height,first)
z1 = dis(a,x,dp,height,first)+1+dis(y,b,dp,height,first)
z2 = dis(a,y,dp,height,first)+1+dis(x,b,dp,height,first)
if z <= k and z&1 == k&1:
print('YES')
elif z1 <= k and z1&1 == k&1:
print('YES')
elif z2 <= k and z2&1 == k&1:
print('YES')
else:
print('NO')
# Fast IO Region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
if __name__ == "__main__":
main()
``` | instruction | 0 | 77,681 | 13 | 155,362 |
Yes | output | 1 | 77,681 | 13 | 155,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
import sys
n = int(input())
g = [[] for _ in range(n)]
t_in = [-1 for _ in range(n)]
t_out = [-1 for _ in range(n)]
height = [-1 for _ in range(n)]
time = 0
k = 0
while (2 ** k) <= n:
k += 1
up = [[0 for j in range(k + 1)] for i in range(n)]
def upper(a, b):
return t_in[a] <= t_in[b] and t_out[a] >= t_out[b]
def lca(v, u):
# if (upper(a, b)):
# return a
# if upper(b, a):
# return b
# i = k
# while i >= 0:
# if not upper(up[a][i], b):
# a = up[a][i]
# i -= 1
# #print('lca k = ', k)
# return up[a][i]
if height[v] > height[u]:
u, v = v, u
for i in reversed(range(k + 1)):
if height[up[u][i]] - height[v] >= 0:
u = up[u][i]
if u == v:
return u
for i in reversed(range(k + 1)):
if up[v][i] != up[u][i]:
v = up[v][i]
u = up[u][i]
return up[v][0]
def dist(a, b):
p = lca(a, b)
result = (height[a] - height[p]) + (height[b] - height[p])
#print('dist', a, b, 'lca = ', p, 'res = ', result)
return result
def dfs(v, p, depth):
time = 0
stack = [(v, p, depth)]
while len(stack) > 0:
x = stack.pop()
if len(x) == 1:
t_out[x[0]] = time
time += 1
continue
v, p, depth = x
t_in[v] = time
time += 1
height[v] = depth
up[v][0] = p
for i in range(1, k + 1):
up[v][i] = up[up[v][i-1]][i - 1]
stack.append([v])
for w in g[v]:
if t_in[w] == -1:
stack.append((w, v, depth + 1))
def check(dist, k):
#print('check', dist, k)
return dist <= k and ((dist % 2) == (k % 2))
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a].append(b)
g[b].append(a)
dfs(0, 0, 0)
#print(height)
#print(t_in)
#print(t_out)
#print(upper(8, 5))
m = int(input())
for i in range(m):
x, y, a, b, q = map(lambda x: int(x) - 1, input().split())
#print(x, y, a, b, q)
q = q + 1
dist1 = dist(a, b)
if check(dist1, q):
print("YES")
continue
dist2 = dist(a, x) + 1 + dist(y, b)
if check(dist2, q):
print("YES")
continue
dist3 = dist(a, y) + 1 + dist(b, x)
if check(dist3, q):
print("YES")
else:
print("NO")
``` | instruction | 0 | 77,682 | 13 | 155,364 |
Yes | output | 1 | 77,682 | 13 | 155,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
n = int(input())
g = [[] for _ in range(n)]
for i in range(n - 1):
u, v = map(int, input().split())
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
logn = 19
st = [0] * n
dep = [-1] * n
par = [[0] * n for _ in range(logn + 1)]
st[0], cur = 0, 1
dep[0] = 0
while cur > 0:
x = st[cur - 1]
cur = cur - 1
for i in g[x]:
if dep[i] is -1:
dep[i] = 1 + dep[x]
par[0][i] = x
st[cur] = i
cur = cur + 1
for i in range(1, logn + 1):
for j in range(n):
par[i][j] = par[i - 1][par[i - 1][j]]
def lca(i, j):
if dep[i] > dep[j]:
return lca(j, i)
var = logn
while var >= 0:
if dep[j] - (1 << var) >= dep[i]:
j = par[var][j]
var = var - 1
if i == j: return i
var = logn
while var >= 0:
if par[var][i] is not par[var][j]:
i = par[var][i]
j = par[var][j]
var = var - 1
return par[0][i]
def dist(i, j):
return dep[i] + dep[j] - 2 * dep[lca(i, j)]
def query(a, b, x, y, k):
can = []
can.append(dist(x, y))
can.append(dist(x, a) + 1 + dist(b, y))
can.append(dist(x, b) + 1 + dist(a, y))
for i in can:
if i % 2 == k % 2 and i <= k:
return 'YES'
return 'NO'
q = int(input())
res = []
for i in range(q):
x, y, a, b, k = map(int, input().split())
res.append(query(x - 1, y - 1, a - 1, b - 1, k))
print('\n'.join(res))
``` | instruction | 0 | 77,683 | 13 | 155,366 |
Yes | output | 1 | 77,683 | 13 | 155,367 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
from math import factorial, log2, floor
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
gp = [[] for _ in range(n+1)]
for _ in range(n-1):
f, t = RL()
gp[f].append(t)
gp[t].append(f)
mxd = floor(log2(n))
marr = [[0]*(mxd+1) for _ in range(n+1)]
par = [1]*(n+1)
deep = [0]*(n+1)
vis = [0]*(n+1)
q = deque()
q.append((1, 0))
vis[1] = 1
while q:
nd, d = q.popleft()
deep[nd] = d
marr[nd][0] = par[nd]
for i in range(1, mxd+1):
if 2**i>d: break
marr[nd][i] = marr[marr[nd][i-1]][i-1]
for nex in gp[nd]:
if vis[nex]==1: continue
vis[nex] = 1
par[nex] = nd
q.append((nex, d+1))
# for i in marr:
# print(i)
def lca(a, b):
ta, tb = a, b
if deep[a]>deep[b]:
a, b = b, a
for i in range(mxd, -1, -1):
if marr[b][i]!=-1 and deep[marr[b][i]]>=deep[a]:
b = marr[b][i]
if a==b: return deep[ta]-deep[a]+deep[tb]-deep[a]
for i in range(mxd, -1, -1):
if marr[b][i] != marr[a][i]:
a = marr[a][i]
b = marr[b][i]
ld = par[a] if a!=b else a
return deep[ta]-deep[ld]+deep[tb]-deep[ld]
qn = N()
for _ in range(qn):
x, y, a, b, k = RL()
lst = k & 1
dis = lca(a, b)
disaxyb = (lca(a, x) + lca(y, b) + 1)
disayxb = (lca(a, y) + lca(x, b) + 1)
# print(a, b)
# print(dis, disaxyb, disayxb)
if (dis<=k and dis&1==lst) or (disaxyb<=k and disaxyb&1==lst) or (disayxb<=k and disayxb&1==lst):
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
``` | instruction | 0 | 77,684 | 13 | 155,368 |
Yes | output | 1 | 77,684 | 13 | 155,369 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
import sys, math
import io, os
#data = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
# from itertools import permutations,combinations
def data(): return sys.stdin.readline().strip()
def mdata(): return list(map(int, data().split()))
def outl(var): sys.stdout.write(' '.join(map(str, var)) + '\n')
def out(var): sys.stdout.write(str(var) + '\n')
from decimal import Decimal
# from fractions import Fraction
# sys.setrecursionlimit(100000)
mod = int(1e9) + 7
INF=10**8
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, begin, end):
depth = (end - begin).bit_length() - 1
return self.func(self._data[depth][begin], self._data[depth][end - (1 << depth)])
class LCA:
def __init__(self, root, graph):
self.time = [-1] * len(graph)
self.path = [-1] * len(graph)
self.depth = [0] * len(graph)
P = [-1] * len(graph)
t = -1
dfs = [root]
while dfs:
node = dfs.pop()
self.path[t] = P[node]
self.time[node] = t = t + 1
for nei in graph[node]:
if self.time[nei] == -1:
P[nei] = node
dfs.append(nei)
self.depth[nei]=self.depth[node]+1
self.rmq = RangeQuery(self.time[node] for node in self.path)
def __call__(self, a, b):
if a == b:
return a
a = self.time[a]
b = self.time[b]
if a > b:
a, b = b, a
return self.path[self.rmq.query(a, b)]
def dis(a,b):
return L.depth[a]+L.depth[b]-2*L.depth[L(a,b)]
n=int(data())
graph=[[] for i in range(n)]
for i in range(n-1):
u,v=mdata()
graph[u-1].append(v-1)
graph[v-1].append(u-1)
L=LCA(0,graph)
for i in range(int(data())):
x,y,a,b,k=mdata()
x,y,a,b=x-1,y-1,a-1,x-1
flag=True
for d in [dis(a,b),dis(a,x) + dis(b,y) + 1,dis(a,y) + dis(b,x) + 1]:
if d <= k and d % 2 == k % 2:
out("YES")
flag=False
break
if flag:
out("NO")
``` | instruction | 0 | 77,685 | 13 | 155,370 |
No | output | 1 | 77,685 | 13 | 155,371 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
import math
timer = 0
n = int(input())
tin = [0]*n
tout = [0]*n
l = math.ceil(math.log2(n))
up = [[0]*(l+1) for _ in range(n)]
def dfs(v,p):
global timer
global l
timer+=1
tin[v] = timer
up[v][0] = p
for i in range(1,l+1):
up[v][i] = up[up[v][i-1]][i-1]
for c in adj[v]:
if c!=p:
dfs(c,v)
timer+=1
tout[v] = timer
def is_ancestor(u,v):
return tin[u]<=tin[v] and tout[u]>=tout[v]
def lca(u,v):
if is_ancestor(u,v):
return u
if is_ancestor(v,u):
return v
global l
for i in range(l,-1,-1):
if not is_ancestor(up[u][i],v):
u = up[u][i]
return up[u][0]
adj = [[] for _ in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
u-=1;v-=1
adj[u].append(v)
adj[v].append(u)
dfs(0,0)
q = int(input())
while q:
q-=1
x,y,a,b,k = map(int,input().split())
x-=1;y-=1;a-=1;b-=1
p1 = tin[a]+tin[b]-(2*tin[lca(a,b)])
p2 = tin[a]+tin[x]-(2*tin[lca(a,x)])
p2+=1
p2+= tin[y]+tin[b]-(2*tin[lca(y,b)])
p3 = tin[a]+tin[y]-(2*tin[lca(a,y)])
p3+=1
p3+=tin[x]+tin[b]-(2*tin[lca(x,b)])
ans = []
if p1%2==(k%2):
ans.append(p1)
if p2%2==(k%2):
ans.append(p2)
if p3%2==(k%2):
ans.append(p3)
if len(ans) and min(ans)<=k:
print("YES")
else:
print("NO")
``` | instruction | 0 | 77,686 | 13 | 155,372 |
No | output | 1 | 77,686 | 13 | 155,373 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
def examA():
t = I()
ans = []
for _ in range(t):
x, y, a, b = LI()
if (y-x)%(a+b)!=0:
cur = -1
else:
cur = (y-x)//(a+b)
ans.append(cur)
for v in ans:
print(v)
return
def examB():
N, M = LI()
S = [SI() for _ in range(N)]
d = defaultdict(int)
ok_1 = []
ok_2 = []
for i in range(N):
cur = S[i]
if d[S[i][::-1]]>0:
ok_2.append([d[S[i][::-1]],i+1])
flag = True
for j in range(M//2):
if cur[j]!=cur[M-1-j]:
flag = False
break
if flag:
ok_1.append(i+1)
d[cur] = i+1
#print(ok_1,ok_2)
ans = ""
for i in range(len(ok_2)):
ans += S[ok_2[i][0]-1]
if ok_1:
ans += S[ok_1[0]-1]
for i in range(len(ok_2)-1,-1,-1):
ans += S[ok_2[i][1]-1]
print(len(ans))
print(ans)
return
def examC():
q = I()
for _ in range(q):
flag = True
N, M = LI()
t,l,h = [0]*(N+1),[0]*N,[0]*N
for i in range(N):
t[i+1],l[i],h[i] = LI()
curl = M; curr = M
for i in range(N):
canl = l[i]-(t[i+1]-t[i])
canr = h[i]+(t[i+1]-t[i])
#print(curl,curr)
#print(canl,canr)
if canl>curr or canr<curl:
flag = False
break
curl = max(l[i],curl-(t[i+1]-t[i]))
curr = min(h[i],curr+(t[i+1]-t[i]))
if flag:
print("YES")
else:
print("NO")
return
"""
def examD():
t = I()
for _ in range(t):
N, S = LSI()
N = int(N)
L1 = [False]*N
for i in range(N-1):
if S[i]=="<":
L1[i] = True
#print(L1)
ans1 = [0]*N
ans2 = [0]*N
cur = N
for i in range(N):
if not L1[i]:
ans1[i] = cur
cur -=1
for i in range(N-1,-1,-1):
if L1[i]:
ans1[i] = cur
cur -=1
print(ans1)
cur = N
for i in range(N-1,-1,-1):
if not L1[i]:
ans2[i] = cur
cur -=1
print(ans2)
for i in range(N):
if L1[i]:
ans2[i] = cur
cur -=1
print(ans2)
return
"""
def examE():
class LCA(object):
def __init__(self, G, root=0):
self.G = G
self.root = root
self.n = len(G)
self.logn = (self.n - 1).bit_length()
self.depth = [-1 if i != root else 0 for i in range(self.n)]
self.parent = [[-1] * self.n for _ in range(self.logn)]
self.dfs()
self.doubling()
def dfs(self):
que = [self.root]
while que:
u = que.pop()
for v in self.G[u].keys():
if self.depth[v] == -1:
self.depth[v] = self.depth[u] + 1
self.parent[0][v] = u
que += [v]
def doubling(self):
for i in range(1, self.logn):
for v in range(self.n):
if self.parent[i - 1][v] != -1:
self.parent[i][v] = self.parent[i - 1][self.parent[i - 1][v]]
def get(self, u, v):
if self.depth[v] < self.depth[u]:
u, v = v, u
du = self.depth[u]
dv = self.depth[v]
for i in range(self.logn):
if (dv - du) >> i & 1:
v = self.parent[i][v]
if u == v: return u
for i in range(self.logn - 1, -1, -1):
pu, pv = self.parent[i][u], self.parent[i][v]
if pu != pv:
u, v = pu, pv
return self.parent[0][u]
N = I()
V = [defaultdict(int) for _ in range(N)]
for _ in range(N - 1):
u, v = LI()
V[u - 1][v - 1] = 1
V[v - 1][u - 1] = 1
lca = LCA(V)
q = I()
for _ in range(q):
x, y, a, b, k = LI()
p1 = lca.get(a - 1, b - 1)
cur = lca.depth[a - 1] + lca.depth[b - 1] - lca.depth[p1] * 2
p2 = lca.get(x - 1, y - 1)
loop = lca.depth[x - 1] + lca.depth[y - 1] - lca.depth[p2] * 2 +1
if (k-cur)>=0 and (k-cur)%2==0:
print("YES")
continue
pa = lca.get(p2, a - 1)
pb = lca.get(p2, b - 1)
cost = min(lca.depth[p2] - lca.depth[pa],lca.depth[p2] - lca.depth[pb])*2
if loop%2==1:
if k-cur-loop-cost>=0:
print("YES")
continue
if pa == p2 and pb == p2:
if k - (loop - cur) >= 0 and (k - (loop - cur))%2==0:
print("YES")
continue
print("NO")
return
def examF():
ans = 0
print(ans)
return
import sys,copy,bisect,itertools,heapq,math,random
from heapq import heappop,heappush,heapify
from collections import Counter,defaultdict,deque
def I(): return int(sys.stdin.readline())
def LI(): return list(map(int,sys.stdin.readline().split()))
def LSI(): return list(map(str,sys.stdin.readline().split()))
def LS(): return sys.stdin.readline().split()
def SI(): return sys.stdin.readline().strip()
global mod,mod2,inf,alphabet,_ep
mod = 10**9 + 7
mod2 = 998244353
inf = 10**18
_ep = 10**(-12)
alphabet = [chr(ord('a') + i) for i in range(26)]
if __name__ == '__main__':
examE()
"""
"""
``` | instruction | 0 | 77,687 | 13 | 155,374 |
No | output | 1 | 77,687 | 13 | 155,375 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Gildong was hiking a mountain, walking by millions of trees. Inspired by them, he suddenly came up with an interesting idea for trees in data structures: What if we add another edge in a tree?
Then he found that such tree-like graphs are called 1-trees. Since Gildong was bored of solving too many tree problems, he wanted to see if similar techniques in trees can be used in 1-trees as well. Instead of solving it by himself, he's going to test you by providing queries on 1-trees.
First, he'll provide you a tree (not 1-tree) with n vertices, then he will ask you q queries. Each query contains 5 integers: x, y, a, b, and k. This means you're asked to determine if there exists a path from vertex a to b that contains exactly k edges after adding a bidirectional edge between vertices x and y. A path can contain the same vertices and same edges multiple times. All queries are independent of each other; i.e. the added edge in a query is removed in the next query.
Input
The first line contains an integer n (3 ≤ n ≤ 10^5), the number of vertices of the tree.
Next n-1 lines contain two integers u and v (1 ≤ u,v ≤ n, u ≠ v) each, which means there is an edge between vertex u and v. All edges are bidirectional and distinct.
Next line contains an integer q (1 ≤ q ≤ 10^5), the number of queries Gildong wants to ask.
Next q lines contain five integers x, y, a, b, and k each (1 ≤ x,y,a,b ≤ n, x ≠ y, 1 ≤ k ≤ 10^9) – the integers explained in the description. It is guaranteed that the edge between x and y does not exist in the original tree.
Output
For each query, print "YES" if there exists a path that contains exactly k edges from vertex a to b after adding an edge between vertices x and y. Otherwise, print "NO".
You can print each letter in any case (upper or lower).
Example
Input
5
1 2
2 3
3 4
4 5
5
1 3 1 2 2
1 4 1 3 2
1 4 1 3 3
4 2 3 3 9
5 2 3 3 9
Output
YES
YES
NO
YES
NO
Note
The image below describes the tree (circles and solid lines) and the added edges for each query (dotted lines).
<image>
Possible paths for the queries with "YES" answers are:
* 1-st query: 1 – 3 – 2
* 2-nd query: 1 – 2 – 3
* 4-th query: 3 – 4 – 2 – 3 – 4 – 2 – 3 – 4 – 2 – 3
Submitted Solution:
```
import sys
x = 150000
sys.setrecursionlimit(x)
n = int(input())
e = {i: set() for i in range(n)}
for i in range(n - 1):
a, b = map(lambda s: int(s) - 1, input().split())
e[a].add(b)
e[b].add(a)
parent = [-1 for v in range(n)]
lev = [-1 for v in range(n)]
def dfs(v, level, par):
lev[v] = level
parent[v] = par
for u in e[v]:
if parent[u] == -1:
dfs(u, level + 1, v)
dfs(0, 0, 0)
levmx = max(lev)
bindep = levmx.bit_length() + 2
P = [[-1] * bindep for _ in range(n)]
for i in range(n):
P[i][0] = parent[i]
for j in range(1, bindep):
for i in range(n):
if P[i][j - 1] != -1:
P[i][j] = P[P[i][j - 1]][j - 1]
def lca(u, v):
if lev[u] < lev[v]:
u, v = v, u
dist = lev[u] - lev[v]
while dist:
podn = dist.bit_length() - 1
u = P[u][podn]
dist -= (1 << podn)
if u == v:
return u
j = bindep - 1
while j > 0:
if (P[u][j] != -1) and (P[u][j] != P[v][j]):
u = P[u][j]
v = P[v][j]
j -= 1
return parent[u]
def dist(a, b):
return lev[a] + lev[b] - 2 * lev[lca(a, b)]
Q = int(input())
for _ in range(Q):
x, y, a, b, k = map(int, input().split())
x, y, a, b = map(lambda aa: aa - 1, [x, y, a, b])
if dist(a, b) == k:
print('YES')
else:
dxy = dist(x, y)
if dist(a, x) + 1 + dist(b, y) <= k and \
(dist(a, x) + 1 + dist(b, y) - k) % (dxy + 1) == 0:
print('YES')
elif dist(a, y) + 1 + dist(b, x) <= k and \
(dist(a, y) + 1 + dist(b, x) - k) % (dxy + 1) == 0:
print('YES')
else:
print('NO')
``` | instruction | 0 | 77,688 | 13 | 155,376 |
No | output | 1 | 77,688 | 13 | 155,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4. | instruction | 0 | 77,709 | 13 | 155,418 |
Tags: dp, graphs, greedy, math, trees
Correct Solution:
```
from collections import defaultdict as dd
from collections import deque
import bisect
import heapq
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
cache = [0] * (2 * 10**6 + 1)
cache[3] = 4
cache[4] = 4
def solve(last):
n = ri()
if cache[n] != 0:
print(cache[n])
return last
mod = 10**9 + 7
if n <= 2:
print (0)
return last
elif n <= 4:
print (4)
return last
else:
j, k = last
a, b = cache[j], cache[k]
for i in range(k + 1, n + 1):
a, b = b, (2 * a + b) % mod
if i % 3 == 0:
b = (b + 4) % mod
cache[i] = b
last = [n - 1, n]
print (b)
return last
mode = 'T'
if mode == 'T':
t = ri()
last = [3, 4]
for i in range(t):
last = solve(last)
else:
solve()
``` | output | 1 | 77,709 | 13 | 155,419 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4. | instruction | 0 | 77,710 | 13 | 155,420 |
Tags: dp, graphs, greedy, math, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
mod = 10**9+7
INF = float('inf')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('../input.txt')
# sys.stdin = f
def main():
ans = [0, 0, 0, 1, 1]
up = 2000001
a, b = 1, 1
for i in range(5, up + 1):
a, b = b, (a * 2 + b) % mod
if i % 3 == 0: b += 1
ans.append(b)
for _ in range(N()):
print(ans[N()]*4%mod)
if __name__ == "__main__":
main()
``` | output | 1 | 77,710 | 13 | 155,421 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4. | instruction | 0 | 77,711 | 13 | 155,422 |
Tags: dp, graphs, greedy, math, trees
Correct Solution:
```
dp = [0, 0, 0, 4, 4, 12]
for n in range(2000000 // 6):
dp.append(dp[-1] * 2 % (10**9 + 7))
dp.append(dp[-1] * 2 % (10**9 + 7))
dp.append(dp[-1] * 2 % (10**9 + 7))
dp.append((dp[-1] * 2 + 4) % (10**9 + 7))
dp.append((dp[-1] * 2 - 4) % (10**9 + 7))
dp.append((dp[-1] * 2 + 4) % (10**9 + 7))
T = int(input())
for i in range(T):
n = int(input())
print(dp[n] % (10**9 + 7))
``` | output | 1 | 77,711 | 13 | 155,423 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4. | instruction | 0 | 77,712 | 13 | 155,424 |
Tags: dp, graphs, greedy, math, trees
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 19
MOD = 10 ** 9 + 7
def mat_pow(mat, init, K, MOD):
""" 行列累乗 """
def mat_dot(A, B, MOD):
""" 行列の積 """
# 1次元リストが来たら2次元の行列にする
if not isinstance(A[0], list) and not isinstance(A[0], tuple):
A = [A]
if not isinstance(B[0], list) and not isinstance(A[0], tuple):
B = [[b] for b in B]
n1 = len(A)
n2 = len(A[0])
_ = len(B)
m2 = len(B[0])
res = list2d(n1, m2, 0)
for i in range(n1):
for j in range(m2):
for k in range(n2):
res[i][j] += A[i][k] * B[k][j]
res[i][j] %= MOD
return res
def _mat_pow(mat, k, MOD):
""" 行列matをk乗する """
n = len(mat)
res = list2d(n, n, 0)
for i in range(n):
res[i][i] = 1
# 繰り返し二乗法
while k > 0:
if k & 1:
res = mat_dot(res, mat, MOD)
mat = mat_dot(mat, mat, MOD)
k >>= 1
return res
# 行列累乗でK項先へ
res = _mat_pow(mat, K, MOD)
# 最後に初期値と掛ける
res = mat_dot(res, init, MOD)
return [a[0] for a in res]
for _ in range(INT()):
N = INT()
mat = [
[5, 6, 0, 4],
[3, 2, 0, 0],
[1, 2, 0, 0],
[0, 0, 0, 1],
]
init = [4, 0, 0, 1]
if N % 3 == 0:
res = mat_pow(mat, init, N//3-1, MOD)
ans = res[0]
print(ans)
else:
res = mat_pow(mat, init, N//3, MOD)
ans = res[3-N%3]
print(ans)
``` | output | 1 | 77,712 | 13 | 155,425 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4. | instruction | 0 | 77,713 | 13 | 155,426 |
Tags: dp, graphs, greedy, math, trees
Correct Solution:
```
def draw(n):
MOD = 10 ** 9 + 7
INV = 47619048
ADD = [6, -30, -18]
def fpow(x, n):
r = 1
while n > 1:
if n & 1:
r = r * x % MOD
x = x * x % MOD
n >>= 1
return x * r % MOD
return ((fpow(2, n+3)+14*(2*(n&1)-1)+ADD[n%3]) * INV) % MOD
t = int(input())
for i in range(t):
n = int(input())
print(draw(n))
``` | output | 1 | 77,713 | 13 | 155,427 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4.
Submitted Solution:
```
def solution(n):
m = 1000000007
arr = [0]*(n+1)
for i in range(3,n+1):
val = 0
if i % 3 == 0 :
val = 1
arr[i] = (2*arr[i-2] + arr[i-1] + val) % m
return arr[-1]
for _ in range(int(input())):
n = int(input())
print(solution(n))
``` | instruction | 0 | 77,714 | 13 | 155,428 |
No | output | 1 | 77,714 | 13 | 155,429 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4.
Submitted Solution:
```
n = 2000001
mod = 10**9+7
ls = [0 for i in range(n)]
ls[1] = 1
for i in range(2,n):
ls[i] = (ls[i-1]+(2*ls[i-2])%mod)%mod
for lo in range(int(input())):
n = int(input())
if n<=2:
print(0)
continue
print((ls[n-2]*4)%mod)
``` | instruction | 0 | 77,715 | 13 | 155,430 |
No | output | 1 | 77,715 | 13 | 155,431 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4.
Submitted Solution:
```
''' Read input from STDIN. Print your output to STDOUT '''
#import sys
#RI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
#from collections import defaultdict as df
#import copy
#import math
mod = 1e9+7
dp = [[0]*2 for i in range(2*1000005)]
dp[1][0]=0
dp[1][1]=0
dp[2][0]=0
dp[2][1]=0
dp[3][0]=0
dp[3][1]=1
for i in range(4,2*1000005):
dp[i][0]=(max(dp[i-1][1],dp[i-1][0])+2*max(dp[i-2][0],dp[i-2][1])%mod)%mod
dp[i][1]=(1+dp[i-1][0]+2*dp[i-2][0])%mod
t = int(input().strip())
for _ in range(t):
n = int(input().strip())
print(int(max(dp[n][0],dp[n][1])*4)%mod)
#print(0)
``` | instruction | 0 | 77,716 | 13 | 155,432 |
No | output | 1 | 77,716 | 13 | 155,433 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Lee tried so hard to make a good div.2 D problem to balance his recent contest, but it still doesn't feel good at all. Lee invented it so tediously slow that he managed to develop a phobia about div.2 D problem setting instead. And now he is hiding behind the bushes...
Let's define a Rooted Dead Bush (RDB) of level n as a rooted tree constructed as described below.
A rooted dead bush of level 1 is a single vertex. To construct an RDB of level i we, at first, construct an RDB of level i-1, then for each vertex u:
* if u has no children then we will add a single child to it;
* if u has one child then we will add two children to it;
* if u has more than one child, then we will skip it.
<image> Rooted Dead Bushes of level 1, 2 and 3.
Let's define a claw as a rooted tree with four vertices: one root vertex (called also as center) with three children. It looks like a claw:
<image> The center of the claw is the vertex with label 1.
Lee has a Rooted Dead Bush of level n. Initially, all vertices of his RDB are green.
In one move, he can choose a claw in his RDB, if all vertices in the claw are green and all vertices of the claw are children of its center, then he colors the claw's vertices in yellow.
He'd like to know the maximum number of yellow vertices he can achieve. Since the answer might be very large, print it modulo 10^9+7.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) — the number of test cases.
Next t lines contain test cases — one per line.
The first line of each test case contains one integer n (1 ≤ n ≤ 2 ⋅ 10^6) — the level of Lee's RDB.
Output
For each test case, print a single integer — the maximum number of yellow vertices Lee can make modulo 10^9 + 7.
Example
Input
7
1
2
3
4
5
100
2000000
Output
0
0
4
4
12
990998587
804665184
Note
It's easy to see that the answer for RDB of level 1 or 2 is 0.
The answer for RDB of level 3 is 4 since there is only one claw we can choose: \{1, 2, 3, 4\}.
The answer for RDB of level 4 is 4 since we can choose either single claw \{1, 3, 2, 4\} or single claw \{2, 7, 5, 6\}. There are no other claws in the RDB of level 4 (for example, we can't choose \{2, 1, 7, 6\}, since 1 is not a child of center vertex 2).
<image> Rooted Dead Bush of level 4.
Submitted Solution:
```
import copy
count = int(input())
save = [[2, [[0, 0], [0, 0], [0, 0]]]]
step = 100
for _ in range(count):
level = int(input())
start, stats = copy.deepcopy(save[min(len(save) - 1, level // step)].copy())
for i in range(start, level):
if (i - 2) % step == 0 and i > len(save) * step:
save.append([i, stats[:]])
stats[0] = stats[1]
stats[1] = stats[2]
stats[2] = [(4 + stats[0][1] * 2 + stats[1][1]) % (10 ** 9 + 7), (max(stats[1]) + max(stats[0]) * 2) % (10 ** 9 + 7)]
print(max(stats[-1]))
``` | instruction | 0 | 77,717 | 13 | 155,434 |
No | output | 1 | 77,717 | 13 | 155,435 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,737 | 13 | 155,474 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
for _ in range(int(input())):
n = int(input())
p = [(1,1)] + sorted(list(zip(map(int,input().split()), map(int,input().split()))))
cost = 0
for i in range(n):
back = p[i+1][0] - p[i][0] - (p[i+1][1] - p[i][1])
if back == 0:
cost += (1-sum(p[i])%2)*(p[i+1][0] - p[i][0])
else:
back -= (1-sum(p[i])%2)
cost += (back+1)//2
print(cost)
``` | output | 1 | 77,737 | 13 | 155,475 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,738 | 13 | 155,476 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
t = int(input().strip())
for __ in range(t):
n = int(input().strip())
rarr = [int(val) for val in input().strip().split(' ')]
carr = [int(val) for val in input().strip().split(' ')]
arr = [(0,1,1)]+[(r-c,r,c) for r, c in zip(rarr,carr)]
arr.sort()
res = 0
for i in range(n):
delta = arr[i+1][0] - arr[i][0]
if delta % 2:
if arr[i][0] % 2:
res += delta // 2+1
else:
res += delta // 2
elif delta == 0 and arr[i][0] % 2 == 0:
res += arr[i+1][1]-arr[i][1]
else:
res += delta // 2
print(res)
``` | output | 1 | 77,738 | 13 | 155,477 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,739 | 13 | 155,478 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
from sys import stdin, stdout
def triangular_paths(n, r_a, c_a):
rc_a = [[1, 1]]
for i in range(n):
rc_a.append([r_a[i], c_a[i]])
rc_a.sort(key=lambda x: x[0])
res = 0
for i in range(1, n+1):
r1 = rc_a[i-1][0]
c1 = rc_a[i-1][1]
r2 = rc_a[i][0]
c2 = rc_a[i][1]
if (r1+c1)%2 == 1 and (r2+c2)%2 == 1:
res += cal_1(r1, c1, r2, c2)
elif (r1+c1)%2 == 1 and (r2+c2)%2 == 0:
res += cal_2(r1, c1, r2, c2)
elif (r1+c1)%2 == 0 and (r2+c2)%2 == 1:
res += cal_3(r1, c1, r2, c2)
elif (r1+c1)%2 == 0 and (r2+c2)%2 == 0:
res += cal_4(r1, c1, r2, c2)
# print(str(r1) + ' ' + str(c1) + ' , ' + str(r2) + ' ' + str(c2))
# print(res)
# print('-------------')
return res
# odd, odd
def cal_1(r1, c1, r2, c2):
return (r2 - (c2 - c1) - r1) // 2
# odd, even
def cal_2(r1, c1, r2, c2):
return cal_1(r1, c1, r2 - 1, c2) + 1
# even, odd
def cal_3(r1, c1, r2, c2):
return cal_1(r1 + 1, c1, r2, c2)
# even, even
def cal_4(r1, c1, r2, c2):
if r1 - c1 == r2 - c2:
return c2 - c1
else:
return cal_2(r1 + 1, c1, r2, c2)
t = int(stdin.readline())
for _ in range(t):
n = int(stdin.readline())
r_a = list(map(int, stdin.readline().split()))
c_a = list(map(int, stdin.readline().split()))
r = triangular_paths(n, r_a, c_a)
stdout.write(str(r) + '\n')
``` | output | 1 | 77,739 | 13 | 155,479 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,740 | 13 | 155,480 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
from os import path;import sys,time
mod = int(1e9 + 7)
from math import ceil, floor,gcd,log,log2 ,factorial,sqrt
from collections import defaultdict ,Counter , OrderedDict , deque;from itertools import combinations,permutations
# from string import ascii_lowercase ,ascii_uppercase
from bisect import *;from functools import reduce;from operator import mul;maxx = float('inf')
I = lambda :int(sys.stdin.buffer.readline())
lint = lambda :[int(x) for x in sys.stdin.buffer.readline().split()]
S = lambda: sys.stdin.readline().strip('\n')
grid = lambda r :[lint() for i in range(r)]
localsys = 0
start_time = time.time()
#left shift --- num*(2**k) --(k - shift)
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
def ceill(n,x):
return (n+x -1 )//x
T =1
def make_set(v):
parent[v] = v
def find_set(v):
if v== parent[v]:
return v
return find_set(parent[v])
def union_sets(a , b):
a = find_set(a)
b = find_set(b)
if a!= b:
parent[b] = a
def lcs(x , y ):
m , n = len(x) , len(y)
dp = [[None]*(n+1) for _ in range(m+1)]
for i in range(m+1):
for j in range(n+1):
if i == 0 or j == 0 :
dp[i][j] = 0
elif y[j-1] == x[i-1]:
dp[i][j] = dp[i-1][j-1]+ 1
else:
dp[i][j] = max(dp[i-1][j], dp[i][j-1])
return dp[m][n]
def solve():
n = I()
arr , ans = [(1,1)] + sorted((i,j) for i ,j in zip(lint() , lint())) , 0
for i in range(n):
c = (arr[i+1][0] - arr[i][0]) - (arr[i+1][1] - arr[i][1])
if not c:
ans+=(1 - sum(arr[i]) % 2) *(arr[i+1][0] - arr[i][0])
continue
ans+=((c - (1 - sum(arr[i])%2))+1)//2
print(ans)
def run():
if (path.exists('input.txt')):
sys.stdin=open('input.txt','r')
sys.stdout=open('output.txt','w')
run()
T = I() if T else 1
for _ in range(T):
solve()
if localsys:
print("\n\nTime Elased :",time.time() - start_time,"seconds")
``` | output | 1 | 77,740 | 13 | 155,481 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,741 | 13 | 155,482 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
import sys
sys.setrecursionlimit(10**5)
int1 = lambda x: int(x)-1
p2D = lambda x: print(*x, sep="\n")
def II(): return int(sys.stdin.buffer.readline())
def LI(): return list(map(int, sys.stdin.buffer.readline().split()))
def LI1(): return list(map(int1, sys.stdin.buffer.readline().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def LLI1(rows_number): return [LI1() for _ in range(rows_number)]
def BI(): return sys.stdin.buffer.readline().rstrip()
def SI(): return sys.stdin.buffer.readline().rstrip().decode()
# dij = [(0, 1), (-1, 0), (0, -1), (1, 0)]
dij = [(0, 1), (-1, 0), (0, -1), (1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
inf = 10**16
# md = 998244353
md = 10**9+7
for _ in range(II()):
n = II()
rr = LI()
cc = LI()
rc = [(r, c) for r, c in zip(rr, cc)]
rc.sort()
ans = 0
now = 0
pr = 1
for r, c in rc:
nxt = r-c
if now < nxt:
if now & 1:
ans += (nxt-now+1)//2
else:
ans += (nxt-now)//2
elif now > nxt:
if now & 1:
ans += (nxt-now)//2
else:
ans += (nxt-now+1)//2
elif now & 1 == 0:
ans += r-pr
now = nxt
pr = r
print(ans)
``` | output | 1 | 77,741 | 13 | 155,483 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,742 | 13 | 155,484 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
def helper(a, b):
if a == b: return 0
x0, y0 = a; x1, y1 = b
if (x0+y0) % 2 == 0: x0 += 1
y0 += x1-x0
if y1 > y0: return x1-x0+1
elif y1 == y0: return 0
else: return (y0-y1+1) // 2
for i in range(int(input())):n = int(input());r = list(map(int,input().split()));c = list(map(int,input().split()));pool = sorted([[1,1]] + [[r[i],c[i]] for i in range(n)]);print(sum([helper(pool[i-1],pool[i]) for i in range(1,n+1)]))
``` | output | 1 | 77,742 | 13 | 155,485 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,743 | 13 | 155,486 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
import heapq
import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
n = int(input())
r = list(map(int, input().split()))
c = list(map(int, input().split()))
h = []
for i in range(n):
heapq.heappush(h, (r[i], c[i]))
nowx, nowy = 1, 1
ans = 0
while h:
x, y = heapq.heappop(h)
if nowx - nowy == x - y:
if not (x - y) % 2:
ans += x - nowx
elif nowx - nowy < x - y:
ans += (x - y) // 2 - (nowx - nowy) // 2
nowx, nowy = x, y
print(ans)
``` | output | 1 | 77,743 | 13 | 155,487 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Consider an infinite triangle made up of layers. Let's number the layers, starting from one, from the top of the triangle (from top to bottom). The k-th layer of the triangle contains k points, numbered from left to right. Each point of an infinite triangle is described by a pair of numbers (r, c) (1 ≤ c ≤ r), where r is the number of the layer, and c is the number of the point in the layer. From each point (r, c) there are two directed edges to the points (r+1, c) and (r+1, c+1), but only one of the edges is activated. If r + c is even, then the edge to the point (r+1, c) is activated, otherwise the edge to the point (r+1, c+1) is activated. Look at the picture for a better understanding.
<image> Activated edges are colored in black. Non-activated edges are colored in gray.
From the point (r_1, c_1) it is possible to reach the point (r_2, c_2), if there is a path between them only from activated edges. For example, in the picture above, there is a path from (1, 1) to (3, 2), but there is no path from (2, 1) to (1, 1).
Initially, you are at the point (1, 1). For each turn, you can:
* Replace activated edge for point (r, c). That is if the edge to the point (r+1, c) is activated, then instead of it, the edge to the point (r+1, c+1) becomes activated, otherwise if the edge to the point (r+1, c+1), then instead if it, the edge to the point (r+1, c) becomes activated. This action increases the cost of the path by 1;
* Move from the current point to another by following the activated edge. This action does not increase the cost of the path.
You are given a sequence of n points of an infinite triangle (r_1, c_1), (r_2, c_2), …, (r_n, c_n). Find the minimum cost path from (1, 1), passing through all n points in arbitrary order.
Input
The first line contains one integer t (1 ≤ t ≤ 10^4) is the number of test cases. Then t test cases follow.
Each test case begins with a line containing one integer n (1 ≤ n ≤ 2 ⋅ 10^5) is the number of points to visit.
The second line contains n numbers r_1, r_2, …, r_n (1 ≤ r_i ≤ 10^9), where r_i is the number of the layer in which i-th point is located.
The third line contains n numbers c_1, c_2, …, c_n (1 ≤ c_i ≤ r_i), where c_i is the number of the i-th point in the r_i layer.
It is guaranteed that all n points are distinct.
It is guaranteed that there is always at least one way to traverse all n points.
It is guaranteed that the sum of n over all test cases does not exceed 2 ⋅ 10^5.
Output
For each test case, output the minimum cost of a path passing through all points in the corresponding test case.
Example
Input
4
3
1 4 2
1 3 1
2
2 4
2 3
2
1 1000000000
1 1000000000
4
3 10 5 8
2 5 2 4
Output
0
1
999999999
2 | instruction | 0 | 77,744 | 13 | 155,488 |
Tags: constructive algorithms, graphs, math, shortest paths, sortings
Correct Solution:
```
import math
for _ in range(int(input())):
n = int(input())
a = list(map(int, input().split()))
b = list(map(int, input().split()))
c = []
for i in range(n):
c.append((a[i], b[i]))
c.sort()
if c[0] != (1, 1):
c.insert(0, (1, 1))
n += 1
cost = 0
for u in range(n - 1):
p, q = c[u][0], c[u][1]
r, s = c[u + 1][0], c[u + 1][1]
if abs(p - q) == abs(r - s):
if abs(p - q) % 2:
continue
else:
cost += abs(p - r)
else:
x = abs(p - q)
y = abs(r - s)
if y % 2:
cost += abs(x - y) // 2
else:
cost += int(math.ceil(abs(x - y) / 2))
print(cost)
``` | output | 1 | 77,744 | 13 | 155,489 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,905 | 13 | 155,810 |
Tags: *special
Correct Solution:
```
rof = "f" + "o" + "r" #0
fi = "i" + "f" #1
code = """
def floyd(n, c):
{0} k in range(n):
{0} j in range(n):
{0} i in range(n):
c[i][j] = min(c[i][j], c[i][k] + c[k][j])
def array(s, v = 0, i = 0):
{1} i >= len(s) - 1:
return [v] * s[i]
r = array(s, v, i + 1)
return [r.copy() {0} i in range(s[i])]
n = int(input())
c = array([n, n])
{0} i in range(n):
v = input().split()
{0} j in range(n):
c[i][j] = int(v[j])
floyd(n, c)
m = -1
{0} i in range(n):
{0} j in range(n):
m = max(m, c[i][j])
print(m)
""".format(rof, fi)
exec(code)
``` | output | 1 | 77,905 | 13 | 155,811 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,906 | 13 | 155,812 |
Tags: *special
Correct Solution:
```
asd=''
asd+=chr(102)
asd+=chr(114)
asd+=chr(111)
asd+=chr(109)
asd+=chr(32)
asd+=chr(113)
asd+=chr(117)
asd+=chr(101)
asd+=chr(117)
asd+=chr(101)
asd+=chr(32)
asd+=chr(105)
asd+=chr(109)
asd+=chr(112)
asd+=chr(111)
asd+=chr(114)
asd+=chr(116)
asd+=chr(32)
asd+=chr(80)
asd+=chr(114)
asd+=chr(105)
asd+=chr(111)
asd+=chr(114)
asd+=chr(105)
asd+=chr(116)
asd+=chr(121)
asd+=chr(81)
asd+=chr(117)
asd+=chr(101)
asd+=chr(117)
asd+=chr(101)
asd+=chr(10)
asd+=chr(110)
asd+=chr(61)
asd+=chr(105)
asd+=chr(110)
asd+=chr(116)
asd+=chr(40)
asd+=chr(105)
asd+=chr(110)
asd+=chr(112)
asd+=chr(117)
asd+=chr(116)
asd+=chr(40)
asd+=chr(41)
asd+=chr(41)
asd+=chr(10)
asd+=chr(120)
asd+=chr(61)
asd+=chr(91)
asd+=chr(93)
asd+=chr(10)
asd+=chr(102)
asd+=chr(111)
asd+=chr(114)
asd+=chr(32)
asd+=chr(97)
asd+=chr(32)
asd+=chr(105)
asd+=chr(110)
asd+=chr(32)
asd+=chr(114)
asd+=chr(97)
asd+=chr(110)
asd+=chr(103)
asd+=chr(101)
asd+=chr(40)
asd+=chr(110)
asd+=chr(41)
asd+=chr(58)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(120)
asd+=chr(46)
asd+=chr(97)
asd+=chr(112)
asd+=chr(112)
asd+=chr(101)
asd+=chr(110)
asd+=chr(100)
asd+=chr(40)
asd+=chr(108)
asd+=chr(105)
asd+=chr(115)
asd+=chr(116)
asd+=chr(40)
asd+=chr(109)
asd+=chr(97)
asd+=chr(112)
asd+=chr(40)
asd+=chr(105)
asd+=chr(110)
asd+=chr(116)
asd+=chr(44)
asd+=chr(105)
asd+=chr(110)
asd+=chr(112)
asd+=chr(117)
asd+=chr(116)
asd+=chr(40)
asd+=chr(41)
asd+=chr(46)
asd+=chr(115)
asd+=chr(112)
asd+=chr(108)
asd+=chr(105)
asd+=chr(116)
asd+=chr(40)
asd+=chr(41)
asd+=chr(41)
asd+=chr(41)
asd+=chr(41)
asd+=chr(10)
asd+=chr(114)
asd+=chr(101)
asd+=chr(116)
asd+=chr(61)
asd+=chr(48)
asd+=chr(10)
asd+=chr(102)
asd+=chr(111)
asd+=chr(114)
asd+=chr(32)
asd+=chr(97)
asd+=chr(32)
asd+=chr(105)
asd+=chr(110)
asd+=chr(32)
asd+=chr(114)
asd+=chr(97)
asd+=chr(110)
asd+=chr(103)
asd+=chr(101)
asd+=chr(40)
asd+=chr(110)
asd+=chr(41)
asd+=chr(58)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(81)
asd+=chr(61)
asd+=chr(80)
asd+=chr(114)
asd+=chr(105)
asd+=chr(111)
asd+=chr(114)
asd+=chr(105)
asd+=chr(116)
asd+=chr(121)
asd+=chr(81)
asd+=chr(117)
asd+=chr(101)
asd+=chr(117)
asd+=chr(101)
asd+=chr(40)
asd+=chr(41)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(81)
asd+=chr(46)
asd+=chr(112)
asd+=chr(117)
asd+=chr(116)
asd+=chr(40)
asd+=chr(40)
asd+=chr(48)
asd+=chr(44)
asd+=chr(97)
asd+=chr(41)
asd+=chr(41)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(68)
asd+=chr(61)
asd+=chr(91)
asd+=chr(45)
asd+=chr(49)
asd+=chr(93)
asd+=chr(42)
asd+=chr(110)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(119)
asd+=chr(104)
asd+=chr(105)
asd+=chr(108)
asd+=chr(101)
asd+=chr(32)
asd+=chr(110)
asd+=chr(111)
asd+=chr(116)
asd+=chr(32)
asd+=chr(81)
asd+=chr(46)
asd+=chr(101)
asd+=chr(109)
asd+=chr(112)
asd+=chr(116)
asd+=chr(121)
asd+=chr(40)
asd+=chr(41)
asd+=chr(58)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(100)
asd+=chr(44)
asd+=chr(112)
asd+=chr(61)
asd+=chr(81)
asd+=chr(46)
asd+=chr(103)
asd+=chr(101)
asd+=chr(116)
asd+=chr(40)
asd+=chr(41)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(105)
asd+=chr(102)
asd+=chr(32)
asd+=chr(68)
asd+=chr(91)
asd+=chr(112)
asd+=chr(93)
asd+=chr(33)
asd+=chr(61)
asd+=chr(45)
asd+=chr(49)
asd+=chr(58)
asd+=chr(32)
asd+=chr(99)
asd+=chr(111)
asd+=chr(110)
asd+=chr(116)
asd+=chr(105)
asd+=chr(110)
asd+=chr(117)
asd+=chr(101)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(68)
asd+=chr(91)
asd+=chr(112)
asd+=chr(93)
asd+=chr(61)
asd+=chr(100)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(114)
asd+=chr(101)
asd+=chr(116)
asd+=chr(61)
asd+=chr(109)
asd+=chr(97)
asd+=chr(120)
asd+=chr(40)
asd+=chr(114)
asd+=chr(101)
asd+=chr(116)
asd+=chr(44)
asd+=chr(100)
asd+=chr(41)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(102)
asd+=chr(111)
asd+=chr(114)
asd+=chr(32)
asd+=chr(98)
asd+=chr(32)
asd+=chr(105)
asd+=chr(110)
asd+=chr(32)
asd+=chr(114)
asd+=chr(97)
asd+=chr(110)
asd+=chr(103)
asd+=chr(101)
asd+=chr(40)
asd+=chr(110)
asd+=chr(41)
asd+=chr(58)
asd+=chr(10)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(32)
asd+=chr(81)
asd+=chr(46)
asd+=chr(112)
asd+=chr(117)
asd+=chr(116)
asd+=chr(40)
asd+=chr(40)
asd+=chr(100)
asd+=chr(43)
asd+=chr(120)
asd+=chr(91)
asd+=chr(112)
asd+=chr(93)
asd+=chr(91)
asd+=chr(98)
asd+=chr(93)
asd+=chr(44)
asd+=chr(98)
asd+=chr(41)
asd+=chr(41)
asd+=chr(10)
asd+=chr(112)
asd+=chr(114)
asd+=chr(105)
asd+=chr(110)
asd+=chr(116)
asd+=chr(40)
asd+=chr(114)
asd+=chr(101)
asd+=chr(116)
asd+=chr(41)
asd+=chr(10)
exec(asd)
``` | output | 1 | 77,906 | 13 | 155,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,907 | 13 | 155,814 |
Tags: *special
Correct Solution:
```
exec("""
from queue import PriorityQueue
INF = 1000000
n = int(input())
g = [[int(x) fo"""+"""r x in input().split()] fo"""+"""r _ in range(n)]
diam = 0
fo"""+"""r start in range(n):
d = [INF fo"""+"""r i in range(n)]
q = PriorityQueue()
q.put((0, start))
whi"""+"""le not q.empty():
dist, i = q.get()
i"""+"""f d[i] != INF:
continue
# print("get", dist, i)
d[i] = dist
fo"""+"""r j in range(n):
# print("put", d[i] + g[i][j], j)
q.put((d[i] + g[i][j], j))
diam = max(diam, max(d))
# print(d)
print(diam)
""")
``` | output | 1 | 77,907 | 13 | 155,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,908 | 13 | 155,816 |
Tags: *special
Correct Solution:
```
exec("""
n = i@nt(in@put())
a = [li@st(m@ap(in@t, in@put().s@plit())) f@or i i@n ra@nge(n)]
f@or k i@n r@ange(n):
f@or i i@n ra@nge(n):
fo@r j i@n ra@nge(n):
a[i][j] = m@in(a[i][j], a[i][k] + a[k][j])
an@s = 0
fo@r i i@n ra@nge(n):
f@or j i@n ra@nge(n):
a@ns = ma@x(an@s, a[i][j])
pr@int(a@ns)
""".replace("@", ""))
``` | output | 1 | 77,908 | 13 | 155,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,909 | 13 | 155,818 |
Tags: *special
Correct Solution:
```
n = int(input())
a = []
exec("f"+"or i in range(n): a.append(list(map(int, input().split())))")
exec("""
f"""+"""or k in range(n):
f"""+"""or i in range(n):
f"""+"""or j in range(n):
a[i][j] = min(a[i][j], a[i][k] + a[k][j])
print(max([max(x) f"""+"""or x in a]))""")
``` | output | 1 | 77,909 | 13 | 155,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,910 | 13 | 155,820 |
Tags: *special
Correct Solution:
```
from itertools import product
def relax(D, t):
k, i, j = t
D[i][j] = min(D[i][j], D[i][k] + D[k][j])
N = int(input())
D = list(map(lambda i:list(map(int, input().split())), range(N)))
list(map(lambda t: relax(D, t), product(range(N), range(N), range(N))))
print(max(map(max, D)))
``` | output | 1 | 77,910 | 13 | 155,821 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,911 | 13 | 155,822 |
Tags: *special
Correct Solution:
```
n, g = int(input()), []
exec('g.append(list(map(int, input().split())));'*n)
def boom(_k, _g):
pass
def go(k, g):
i = 0
exec("j = 0;exec('g[i][j] = min(g[i][j], g[i][k] + g[k][j]);j+=1;'*n);i+=1;"*n)
(go, boom)[k + 1 >= n](k + 1, g)
go(0, g)
ans, i = 0, 0
exec('ans = max(ans, max(g[i]));i+=1;'*n)
print(ans)
``` | output | 1 | 77,911 | 13 | 155,823 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
| instruction | 0 | 77,912 | 13 | 155,824 |
Tags: *special
Correct Solution:
```
#!/usr/bin/python3
import sys
sys.setrecursionlimit(10000)
n = int(input())
a = []
def read(i):
try:
1 / (n - i)
a.append(list(map(int, input().split())))
read(i + 1);
except:
pass
def f(i, j, k):
try:
1 / (n - i)
1 / (n - j)
1 / (n - k)
a[j][k] = min(a[j][k], a[j][i] + a[i][k])
f(i, j, k + 1)
except:
try:
1 / (n - i)
1 / (n - j)
f(i, j + 1, 0)
except:
try:
1 / (n - i)
f(i + 1, 0, 0)
except:
pass
def m(i):
try:
1 / (n - i)
return max(max(a[i]), m(i + 1))
except:
return 0
read(0)
f(0, 0, 0)
print(m(0))
``` | output | 1 | 77,912 | 13 | 155,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
n = int(input())
S = list(map(lambda i: list(map(int, input().split())), range(n)))
def shortest_path(target, queue, visited):
dist, element = min(queue)
queue.remove((dist, element))
try:
1 // (1 - int(element in visited))
except ZeroDivisionError:
return shortest_path(target, queue, visited)
visited.add(element)
try:
1 // (element - target)
except ZeroDivisionError:
return dist
list(map(lambda i: queue.add((dist + S[element][i], i)), range(n)))
return shortest_path(target, queue, visited)
#print(shortest_path(2, {(0, 0)}, set()))
print(max(map(lambda x: shortest_path(x % n, { (0, x // n) }, set()), range(n * n))))
``` | instruction | 0 | 77,913 | 13 | 155,826 |
Yes | output | 1 | 77,913 | 13 | 155,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
import sys, itertools, collections
n = int(input())
d = list(map(lambda s: list(map(int, s.split())), sys.stdin.readlines()))
def assign(t):
k,i,j = t
d[i][j] = min(d[i][j], d[i][k] + d[k][j])
collections.deque(maxlen=0).extend(map(assign, itertools.product(range(n), **{'taeper'[::-1]:3})))
print(max(map(max, d)))
``` | instruction | 0 | 77,914 | 13 | 155,828 |
Yes | output | 1 | 77,914 | 13 | 155,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
import binascii
x = binascii.unhexlify(b'6e203d20696e7428696e7075742829290a64203d205b205b5d20666f72206920696e2072616e6765286e29205d0a666f72206920696e2072616e6765286e293a0a20202020645b695d203d206c697374286d617028696e742c20696e70757428292e73706c6974282929290a666f72206b20696e2072616e6765286e293a0a20202020666f72206920696e2072616e6765286e293a0a2020202020202020666f72206a20696e2072616e6765286e293a0a202020202020202020202020645b695d5b6a5d203d206d696e28645b695d5b6a5d2c20645b695d5b6b5d202b20645b6b5d5b6a5d290a616e73203d20300a666f72206920696e20643a0a20202020666f72206a20696e20693a0a20202020202020616e73203d206d617828616e732c206a290a7072696e7428616e7329')
exec(x)
``` | instruction | 0 | 77,915 | 13 | 155,830 |
Yes | output | 1 | 77,915 | 13 | 155,831 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
from functools import reduce
from itertools import chain
n = int(input())
print(max(map(
max,
reduce(
lambda a, k: reduce(
lambda a, i: reduce(
lambda a, j: list(chain(
a[:i],
[list(chain(
a[i][:j],
[min(a[i][j], a[i][k] + a[k][j])],
a[i][j+1:],
))],
a[i+1:],
)),
range(n),
a,
),
range(n),
a,
),
range(n),
list(map(
lambda i: list(map(int, input().split())),
range(n)))))))
``` | instruction | 0 | 77,916 | 13 | 155,832 |
Yes | output | 1 | 77,916 | 13 | 155,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
from queue import PriorityQueue as prioq
n=int(input())
code='''
DIST=[[] FOR A IN RANGE(N)]
FOR I IN RANGE(N):
FOR D IN [INT(A) FOR A IN INPUT().SPLIT() IF A!='']:
DIST[I]+=[D]
DEF SHORTHEST(A,B):
DI=[7 FOR I IN RANGE(N)]
VISITED=[0 FOR I IN RANGE(N)]
QU=PRIOQ()
QU.PUT((0,A))
while(NOT QU.EMPTY()):
POPPED=QU.GET()
IF VISITED[POPPED[1]]:
CONTINUE
VISITED[POPPED[1]]=1
DI[POPPED[1]]=POPPED[0]
FOR A IN RANGE(N):
IF NOT VISITED[A]:
QU.PUT((POPPED[0] + DIST[A][POPPED[1]],A))
RETURN DI[A]
RET=-1
FOR A IN RANGE(N):
FOR B IN RANGE(N):
RET=MAX(RET,SHORTHEST(A,B))
PRINT(RET)
'''
#print(code.lower())
exec(code.lower())
``` | instruction | 0 | 77,917 | 13 | 155,834 |
No | output | 1 | 77,917 | 13 | 155,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
sum = 0
for i in range(int(input())):
a = list(map(int , input().split()))
sum = sum + a[0]
print(sum)
``` | instruction | 0 | 77,918 | 13 | 155,836 |
No | output | 1 | 77,918 | 13 | 155,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
import sys
code = """
n = int(input())
mtr = []
for i in range(n):
mtr.append([int(i) for i in input().split()])
for k in range(n):
for i in range(n):
for j in range(n):
mtr[i][j] = min(mtr[i][j], mtr[i][k] + mtr[k][j])
mx = 0
for i in range(n):
for j in range(n):
mx = max(mx, mtr[i][j])
print(mx)
"""
exec(code)
``` | instruction | 0 | 77,919 | 13 | 155,838 |
No | output | 1 | 77,919 | 13 | 155,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a complete undirected graph. For each pair of vertices you are given the length of the edge that connects them. Find the shortest paths between each pair of vertices in the graph and return the length of the longest of them.
Input
The first line of the input contains a single integer N (3 ≤ N ≤ 10).
The following N lines each contain N space-separated integers. jth integer in ith line aij is the length of the edge that connects vertices i and j. aij = aji, aii = 0, 1 ≤ aij ≤ 100 for i ≠ j.
Output
Output the maximum length of the shortest path between any pair of vertices in the graph.
Examples
Input
3
0 1 1
1 0 4
1 4 0
Output
2
Input
4
0 1 2 3
1 0 4 5
2 4 0 6
3 5 6 0
Output
5
Note
You're running short of keywords, so you can't use some of them:
define
do
for
foreach
while
repeat
until
if
then
else
elif
elsif
elseif
case
switch
Submitted Solution:
```
n=int(input())
if n%2==0 :
print(n+1)
else
print(n-1)
``` | instruction | 0 | 77,920 | 13 | 155,840 |
No | output | 1 | 77,920 | 13 | 155,841 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.
<image> The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:
* si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;
* mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
Input
The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108).
Output
Print n lines, the pair of integers si, mi in each line.
Examples
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1 | instruction | 0 | 77,922 | 13 | 155,844 |
Tags: data structures, graphs
Correct Solution:
```
import sys
n, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
b = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
logk = len(bin(k)) - 2
sum_w, sum_w_p = b[:], b[:]
min_w, min_w_p = b[:], b[:]
dest, dest_p = a[:], a[:]
ans_sum, ans_min, pos = [0]*n, b[:], list(range(n))
if k & 1:
ans_sum = b[:]
pos = [a[i] for i in range(n)]
k >>= 1
for j in range(1, logk):
for i in range(n):
d = dest[i]
p = 0 if d > i else 1
dest_p[i] = d
dest[i] = (dest_p if p else dest)[d]
sum_w_p[i] = sum_w[i]
sum_w[i] += (sum_w_p if p else sum_w)[d]
min_w_p[i] = min_w[i]
if min_w[i] > (min_w_p if p else min_w)[d]:
min_w[i] = (min_w_p if p else min_w)[d]
if k & 1:
for i in range(n):
ans_sum[i] += sum_w[pos[i]]
if ans_min[i] > min_w[pos[i]]:
ans_min[i] = min_w[pos[i]]
pos[i] = dest[pos[i]]
k >>= 1
sys.stdout.buffer.write('\n'.join(
(str(ans_sum[i]) + ' ' + str(ans_min[i]) for i in range(n))).encode('utf-8'))
``` | output | 1 | 77,922 | 13 | 155,845 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.
<image> The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:
* si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;
* mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
Input
The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108).
Output
Print n lines, the pair of integers si, mi in each line.
Examples
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1 | instruction | 0 | 77,923 | 13 | 155,846 |
Tags: data structures, graphs
Correct Solution:
```
g = {}
def push(u, v, w):
g[u] = [v, w]
n, pos = map(int, input().split())
V = list(map(int, input().split()))
W = list(map(int, input().split()))
for _ in range(n):
push(_, V[_], W[_])
max_log = 35
next_n = [[-1] * n for _ in range(max_log)]
next_m = [[float('inf')] * n for _ in range(max_log)]
next_s = [[0] * n for _ in range(max_log)]
for u in range(n):
v, w = g[u]
next_n[0][u] = v
next_m[0][u] = w
next_s[0][u] = w
for k in range(1, max_log):
for u in range(n):
v = next_n[k-1][u]
m = next_m[k-1][u]
s = next_s[k-1][u]
next_n[k][u] = next_n[k-1][v]
next_m[k][u] = min(next_m[k-1][v], m)
next_s[k][u] = next_s[k-1][v] + s
m_arr = [float('inf')] * n
s_arr = [0] * n
for _ in range(n):
s, m = 0, float('inf')
v = _
cur = 1<<max_log
i = max_log
while cur > 0:
if cur & pos:
m = min(m, next_m[i][v])
s = s + next_s[i][v]
v = next_n[i][v]
cur >>= 1
i -= 1
m_arr[_] = m
s_arr[_] = s
arr = [str(x) + ' ' + str(y) for x, y in zip(s_arr, m_arr)]
print('\n'.join([x for x in arr]))
``` | output | 1 | 77,923 | 13 | 155,847 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.
<image> The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:
* si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;
* mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
Input
The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108).
Output
Print n lines, the pair of integers si, mi in each line.
Examples
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1
Submitted Solution:
```
import sys
n, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
b = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
logk = len(bin(k)) - 2
sum_w = [[b[i]]*2 for i in range(n)]
min_w = [[b[i]]*2 for i in range(n)]
dest = [[a[i]]*2 for i in range(n)]
ans_sum, ans_min, pos = [0]*n, b[:], list(range(n))
if k & 1:
ans_sum = b[:]
pos = [a[i] for i in range(n)]
k >>= 1
for j in range(1, logk):
for i in range(n):
d = dest[i][0]
dest[i][0] = dest[i][1]
dest[i][1] = dest[d][1 if d > i else 0]
sum_w[i][0] = sum_w[i][1]
sum_w[i][1] = sum_w[i][0] + sum_w[d][1 if d > i else 0]
min_w[i][0] = min_w[i][1]
if min_w[i][1] > min_w[d][1 if d > i else 0]:
min_w[i][1] = min_w[d][1 if d > i else 0]
if k & 1:
for i in range(n):
ans_sum[i] += sum_w[pos[i]][1]
ans_min[i] = min(ans_min[i], min_w[pos[i]][1])
pos[i] = dest[pos[i]][1]
k >>= 1
sys.stdout.buffer.write('\n'.join(
(str(ans_sum[i]) + ' ' + str(ans_min[i]) for i in range(n))).encode('utf-8'))
``` | instruction | 0 | 77,924 | 13 | 155,848 |
No | output | 1 | 77,924 | 13 | 155,849 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.
<image> The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:
* si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;
* mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
Input
The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108).
Output
Print n lines, the pair of integers si, mi in each line.
Examples
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1
Submitted Solution:
```
import sys
n, k = map(int, sys.stdin.buffer.readline().decode('utf-8').split())
a = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
b = list(map(int, sys.stdin.buffer.readline().decode('utf-8').split()))
logk = len(bin(k)) - 2
sum_w = [[b[i]]*logk for i in range(n)]
min_w = [[b[i]]*logk for i in range(n)]
dest = [[a[i]]*logk for i in range(n)]
ans_sum, ans_min, pos = [0]*n, b[:], list(range(n))
if k & 1:
ans_sum = b[:]
pos = [a[i] for i in range(n)]
k >>= 1
for j in range(1, logk):
for i in range(n):
dest[i][j] = dest[dest[i][j-1]][j-1]
sum_w[i][j] = sum_w[i][j-1] + sum_w[dest[i][j-1]][j-1]
if min_w[i][j] > min_w[dest[i][j-1]][j-1]:
min_w[i][j] = min_w[dest[i][j-1]][j-1]
if k & 1:
for i in range(n):
ans_sum[i] += sum_w[pos[i]][j]
if ans_min[i] > min_w[pos[i]][j]:
ans_min[i] = min_w[pos[i]][j]
pos[i] = dest[pos[i]][j]
k >>= 1
sys.stdout.buffer.write('\n'.join(
(str(ans_sum[i]) + ' ' + str(ans_min[i]) for i in range(n))).encode('utf-8'))
``` | instruction | 0 | 77,925 | 13 | 155,850 |
No | output | 1 | 77,925 | 13 | 155,851 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1.
Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi.
<image> The graph from the first sample test.
Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where:
* si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i;
* mi — the minimal weight from all arcs on the path with length k which starts from the vertex i.
The length of the path is the number of arcs on this path.
Input
The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108).
Output
Print n lines, the pair of integers si, mi in each line.
Examples
Input
7 3
1 2 3 4 3 2 6
6 3 1 4 2 2 3
Output
10 1
8 1
7 1
10 2
8 2
7 1
9 3
Input
4 4
0 1 2 3
0 1 2 3
Output
0 0
4 1
8 2
12 3
Input
5 3
1 2 3 4 0
4 1 2 14 3
Output
7 1
17 1
19 2
21 3
8 1
Submitted Solution:
```
def weight(k,dir,cost):
s = [-1]*len(dir)
sum = [0]*len(dir)
m = [0]*len(dir)
for x in range(len(dir)):
if s[x] == -1:
s[x] = 0
m[x] = int(cost[x])
curr = x
for y in range(int(k)):
sum[x]+=int(cost[curr])
curr = int(dir[curr])
if int(cost[curr]) < m[x]:
m[x] = int(cost[curr])
print(str(sum[x])+' '+str(m[x]))
k = input().split()[1]
dir = input().split()
cost = input().split()
weight(k,dir,cost)
``` | instruction | 0 | 77,926 | 13 | 155,852 |
No | output | 1 | 77,926 | 13 | 155,853 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.