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 |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672
Submitted Solution:
```
mod = 10**9+7 #出力の制限
N = 2*10**5
g1 = [1, 1] # 元テーブル
g2 = [1, 1] #逆元テーブル
inverse = [0, 1] #逆元テーブル計算用テーブル
for i in range( 2, N + 1 ):
g1.append( ( g1[-1] * i ) % mod )
inverse.append( ( -inverse[mod % i] * (mod//i) ) % mod )
g2.append( (g2[-1] * inverse[-1]) % mod )
def func(n):
if n%2==0:
return (-g1[n]*g2[n//2]*pow(inverse[2],n//2,mod))%mod
else:
return 0
import sys
sys.setrecursionlimit(10**5)
N=int(input())
edge=[[] for i in range(N)]
parent=[0]*N
deg=[1]*N
deg[0]=0
for i in range(N-1):
x,y=map(int,input().split())
edge[x-1].append(y-1)
edge[y-1].append(x-1)
def prv(v,pv):
for nv in edge[v]:
if nv!=pv:
parent[nv]=v
prv(nv,v)
prv(0,-1)
for i in range(N):
new=[]
for v in edge[i]:
if v!=parent[i]:
new.append(v)
edge[i]=new
from collections import deque
ans = list(v for v in range(N) if deg[v]==0)
deq = deque(ans)
used = [0]*N
while deq:
v = deq.popleft()
for t in edge[v]:
deg[t] -= 1
if deg[t]==0:
deq.append(t)
ans.append(t)
dp=[[] for i in range(N)]
sz=[0 for i in range(N)]
for v in ans[::-1]:
sz[v]=1
dp[v]=[0]*(sz[v]+1)
dp[v][1]=1
for nv in edge[v]:
merged=[0]*(sz[v]+sz[nv]+1)
for i in range(sz[v]+1):
for j in range(sz[nv]+1):
merged[i+j] +=dp[v][i]*dp[nv][j]
merged[i+j]%=mod
sz[v]+=sz[nv]
dp[v] =merged
dp[v][0]=(sum(func(k)*dp[v][k] for k in range(1,sz[v]+1)))%mod
print((-dp[0][0])%mod)
``` | instruction | 0 | 76,540 | 13 | 153,080 |
No | output | 1 | 76,540 | 13 | 153,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672
Submitted Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)
import numpy as np
MOD = 10 ** 9 + 7
N = int(input())
graph = [[] for _ in range(N+1)]
for _ in range(N-1):
x,y = map(int,input().split())
graph[x].append(y)
graph[y].append(x)
"""
包除の原理。各頂点を根として
・偶数個を選ぶ、そこが反例となっている、他は何でもよい、
・奇数個を選ぶ、そこが反例となっている、他は何でもよい
・根を含む成分は保留してある。保留している頂点の数を持っておく。
・偶数個の場合と奇数の場合の差分だけ持っておく
"""
def dp_merge(data1,data2):
N1 = len(data1) - 1
N2 = len(data2) - 1
data = np.zeros(N1+N2, dtype = np.int64)
for n in range(1,N1+1):
data[n:n+N2] += data1[n] * data2[1:] % MOD
data %= MOD
return data
fact_2 = [1,0,1]
for n in range(3,N+10):
fact_2.append(fact_2[n-2] * (n-1) % MOD)
fact_2 = np.array(fact_2, dtype = np.int64)
def dp_add_edge(data):
N = len(data) - 1
data1 = np.zeros(N+2, dtype=np.int64)
# 辺を反例に加えない
data1[1:] = data
# 辺を反例に加える
data1[1] = - (data * fact_2[:N+1] % MOD).sum() % MOD
return data1
def dfs(v, parent = None):
data = None
for y in graph[v]:
if y == parent:
continue
data1 = dfs(y, v)
# mergeする前に、最後の辺をひとつ加える
data1 = dp_add_edge(data1)
if data is None:
data = data1
else:
data = dp_merge(data, data1)
if data is None:
return np.array([0,1],dtype=np.int64)
return data
data = dfs(1)
answer = (data * fact_2[:N+1] % MOD).sum() % MOD
print(answer)
``` | instruction | 0 | 76,541 | 13 | 153,082 |
No | output | 1 | 76,541 | 13 | 153,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let N be an even number.
There is a tree with N vertices. The vertices are numbered 1, 2, ..., N. For each i (1 \leq i \leq N - 1), the i-th edge connects Vertex x_i and y_i.
Snuke would like to decorate the tree with ribbons, as follows.
First, he will divide the N vertices into N / 2 pairs. Here, each vertex must belong to exactly one pair. Then, for each pair (u, v), put a ribbon through all the edges contained in the shortest path between u and v.
Snuke is trying to divide the vertices into pairs so that the following condition is satisfied: "for every edge, there is at least one ribbon going through it." How many ways are there to divide the vertices into pairs, satisfying this condition? Find the count modulo 10^9 + 7. Here, two ways to divide the vertices into pairs are considered different when there is a pair that is contained in one of the two ways but not in the other.
Constraints
* N is an even number.
* 2 \leq N \leq 5000
* 1 \leq x_i, y_i \leq N
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
x_1 y_1
x_2 y_2
:
x_{N - 1} y_{N - 1}
Output
Print the number of the ways to divide the vertices into pairs, satisfying the condition, modulo 10^9 + 7.
Examples
Input
4
1 2
2 3
3 4
Output
2
Input
4
1 2
1 3
1 4
Output
3
Input
6
1 2
1 3
3 4
1 5
5 6
Output
10
Input
10
8 5
10 8
6 5
1 5
4 8
2 10
3 6
9 2
1 7
Output
672
Submitted Solution:
```
import sys
sys.setrecursionlimit(5001)
MOD = 10 ** 9 + 7
n = int(input())
links = [set() for _ in range(n)]
for line in sys.stdin.readlines():
x, y = map(int, line.split())
x -= 1
y -= 1
links[x].add(y)
links[y].add(x)
double_factorial_odd = [0] * (n // 2)
prev = 1
for i in range(n // 2):
prev = double_factorial_odd[i] = (2 * i + 1) * prev % MOD
def dfs(v, p):
ret = [0, 1]
for u in links[v]:
if u == p:
continue
res = dfs(u, v)
lt, ls = len(ret), len(res)
mrg = [0] * (lt + ls - 1)
for i in range(1 - lt % 2, lt, 2):
c = ret[i]
for j in range(1 - ls % 2, ls, 2):
mrg[i + j] = (mrg[i + j] + c * res[j]) % MOD
ret = mrg
if len(ret) % 2 == 1:
ret[0] = -sum(pattern * df % MOD for pattern, df in zip(ret[2::2], double_factorial_odd)) % MOD
return ret
print(MOD - dfs(0, -1)[0])
``` | instruction | 0 | 76,542 | 13 | 153,084 |
No | output | 1 | 76,542 | 13 | 153,085 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree that has n nodes and n-1 edges. There are military bases on t out of the n nodes. We want to disconnect the bases as much as possible by destroying k edges. The tree will be split into k+1 regions when we destroy k edges. Given the purpose to disconnect the bases, we only consider to split in a way that each of these k+1 regions has at least one base. When we destroy an edge, we must pay destroying cost. Find the minimum destroying cost to split the tree.
Input
The input consists of multiple data sets. Each data set has the following format. The first line consists of three integers n, t, and k (1 \leq n \leq 10,000, 1 \leq t \leq n, 0 \leq k \leq t-1). Each of the next n-1 lines consists of three integers representing an edge. The first two integers represent node numbers connected by the edge. A node number is a positive integer less than or equal to n. The last one integer represents destroying cost. Destroying cost is a non-negative integer less than or equal to 10,000. The next t lines contain a distinct list of integers one in each line, and represent the list of nodes with bases. The input ends with a line containing three zeros, which should not be processed.
Output
For each test case, print its case number and the minimum destroying cost to split the tree with the case number.
Example
Input
2 2 1
1 2 1
1
2
4 3 2
1 2 1
1 3 2
1 4 3
2
3
4
0 0 0
Output
Case 1: 1
Case 2: 3 | instruction | 0 | 76,647 | 13 | 153,294 |
"Correct Solution:
```
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve(t):
N, T, K = map(int, readline().split())
if N == T == K == 0:
return False
G = [[] for i in range(N)]
E = []
res = 0
for i in range(N-1):
a, b, c = map(int, readline().split())
res += c
E.append((c, a-1, b-1))
E.sort(reverse=1)
sz = [0]*N
for i in range(T):
v = int(readline())-1
sz[v] = 1
*prt, = range(N)
def root(x):
if x == prt[x]:
return x
prt[x] = y = root(prt[x])
return y
def unite(x, y):
px = root(x); py = root(y)
if px < py:
prt[py] = px
sz[px] += sz[py]
else:
prt[px] = py
sz[py] += sz[px]
d = T - K - 1
for c, a, b in E:
pa = root(a); pb = root(b)
if sz[pa] == 0 or sz[pb] == 0:
unite(a, b)
res -= c
continue
if d > 0:
d -= 1
unite(a, b)
res -= c
write("Case %d: %d\n" % (t, res))
return True
i = 1
while solve(i):
i += 1
``` | output | 1 | 76,647 | 13 | 153,295 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree that has n nodes and n-1 edges. There are military bases on t out of the n nodes. We want to disconnect the bases as much as possible by destroying k edges. The tree will be split into k+1 regions when we destroy k edges. Given the purpose to disconnect the bases, we only consider to split in a way that each of these k+1 regions has at least one base. When we destroy an edge, we must pay destroying cost. Find the minimum destroying cost to split the tree.
Input
The input consists of multiple data sets. Each data set has the following format. The first line consists of three integers n, t, and k (1 \leq n \leq 10,000, 1 \leq t \leq n, 0 \leq k \leq t-1). Each of the next n-1 lines consists of three integers representing an edge. The first two integers represent node numbers connected by the edge. A node number is a positive integer less than or equal to n. The last one integer represents destroying cost. Destroying cost is a non-negative integer less than or equal to 10,000. The next t lines contain a distinct list of integers one in each line, and represent the list of nodes with bases. The input ends with a line containing three zeros, which should not be processed.
Output
For each test case, print its case number and the minimum destroying cost to split the tree with the case number.
Example
Input
2 2 1
1 2 1
1
2
4 3 2
1 2 1
1 3 2
1 4 3
2
3
4
0 0 0
Output
Case 1: 1
Case 2: 3 | instruction | 0 | 76,648 | 13 | 153,296 |
"Correct Solution:
```
from collections import defaultdict
import heapq
case = 1
while True:
n, t, k = map(int, input().split())
if n == t == k == 0:
break
costs = [0] * 10001
# 全ての辺をまず壊して考える
E = defaultdict(list)
for i in range(n-1):
fr, to, c = map(int, input().split())
E[fr - 1].append((c, to - 1))
E[to - 1].append((c, fr - 1))
costs[c] += 1
bases = [None]*t
# isUnitedが負の点がなくなるようにしなければいけない
isUnited = [False] * n
for i in range(t):
b = int(input()) - 1
bases[i] = b
isUnited[b] = True
q = []
for b in bases:
for c, y in E[b]:
if not isUnited[y]:
# heapqで降順にするためにコストに負を掛ける
heapq.heappush(q, (-c, y))
while q:
c_minus, y = heapq.heappop(q)
if isUnited[y]:
continue
isUnited[y] = True
# -c_minus == c
# 壊してはいけない辺を復活させる
costs[-c_minus] -= 1
for nc, ny in E[y]:
if not isUnited[ny]:
heapq.heappush(q, (-nc, ny))
p = 0
ans = 0
# 壊せる辺の中でコストの低い順からk個だけとる
while k > 0:
while k > 0 and costs[p] > 0:
costs[p] -= 1
k -= 1
ans += p
p += 1
print("Case {}: {}".format(case, ans))
case += 1
``` | output | 1 | 76,648 | 13 | 153,297 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,652 | 13 | 153,304 |
"Correct Solution:
```
from collections import deque
q = deque([])
n = int(input())
G = []
for i in range(n):
u, k, *vvv = list(map(int, input().split()))
G.append([v-1 for v in vvv])
visited = [False for _ in range(n)]
q.append(0)
dist = [-1 for _ in range(n)]
dist[0] = 0
while q:
u = q.popleft()
visited[u] = True
for v in G[u]:
if visited[v] == True:
continue
else:
q.append(v)
visited[v] = True
dist[v] = dist[u] + 1
for i in range(n):
print(i+1, dist[i])
``` | output | 1 | 76,652 | 13 | 153,305 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,653 | 13 | 153,306 |
"Correct Solution:
```
from collections import deque
V = int(input())
edge = [[] for _ in range(V)]
for _ in range(V):
u, _, *v = map(lambda x: int(x)-1, input().split())
edge[u] = sorted(v)
dist = [-1] * V
dist[0] = 0
que = deque([0])
while len(que):
v = que.popleft()
for c in edge[v]:
if dist[c] == -1:
dist[c] = dist[v] + 1
que.append(c)
for i, d in enumerate(dist):
print(i+1, d)
``` | output | 1 | 76,653 | 13 | 153,307 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,654 | 13 | 153,308 |
"Correct Solution:
```
import collections
n=int(input())
l=[]
for i in range(n):
l1=list(map(int,input().split()))
l2=[]
if l1[1]==0:
l2=["0" for j in range(n)]
else:
for j in range(n):
if j+1 in l1[2:]:
l2.append("1")
else:
l2.append("0")
l.append(l2)
D=[-1 for i in range(n)]
D[0]=0
q=collections.deque()
q.append(0)
while len(q)!=0:
cur=q.popleft()
for d in range(n):
if l[cur][d]=="1" and D[d]==-1:
D[d]=D[cur]+1
q.append(d)
for i in range(n):
print(i+1,D[i])
``` | output | 1 | 76,654 | 13 | 153,309 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,655 | 13 | 153,310 |
"Correct Solution:
```
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]
d = [-1] * n
s = 1
q = []
d[s - 1] = 0
q.append(s)
while len(q):
u = q.pop()
v = adj[u - 1]
for vi in v:
if d[vi - 1] == -1:
d[vi - 1] = d[u - 1] + 1
q.append(vi)
elif d[vi - 1] > d[u - 1] + 1:
d[vi - 1] = d[u - 1] + 1
q.append(vi)
for i, di in enumerate(d):
print(i + 1, di)
``` | output | 1 | 76,655 | 13 | 153,311 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,656 | 13 | 153,312 |
"Correct Solution:
```
import sys
from collections import deque
input = sys.stdin.readline
sys.setrecursionlimit(2 * 10**6)
def inpl():
return list(map(int, input().split()))
N = int(input())
edge = {}
for _ in range(N):
tmp = inpl()
u, k = tmp[:2]
edge[u] = tmp[2:]
d = {i: -1 for i in range(1, N + 1)}
d[1] = 0
Q = deque()
Q.append(1)
while Q:
v = Q.popleft()
for nv in edge[v]:
if d[nv] != -1:
continue
d[nv] = d[v] + 1
Q.append(nv)
for i in range(1, N + 1):
print(i, d[i])
``` | output | 1 | 76,656 | 13 | 153,313 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,657 | 13 | 153,314 |
"Correct Solution:
```
from collections import deque
def main():
inf = 1000000007
n = int(input())
e = [[] for _ in range(n)]
d = [inf]*n
for i in range(n):
m = list(map(int,input().split()))
for j in range(2,len(m)):
e[m[0]-1].append(m[j]-1)
d[0] = 0
dq = deque([])
dq.append([0,0])
while dq:
c,v = dq.popleft()
for u in e[v]:
if d[u]==inf:
d[u] = c+1
dq.append([c+1,u])
for i in range(n):
if d[i]==inf:print (i+1,-1)
else :print (i+1,d[i])
if __name__ == '__main__':
main()
``` | output | 1 | 76,657 | 13 | 153,315 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,658 | 13 | 153,316 |
"Correct Solution:
```
from collections import deque
n = int(input())
adj = [0]*n # adjacent list
d = [-1]*n # distance from the source vertex
c = ['w']*n # the 'color' of each vertex
# receiving input (the structure of the graph)
for i in range(n):
tmp = list(map( int, input().split() ) )
adj[tmp[0]-1] = list(map(lambda x : x - 1, tmp[2:]))
# set the source vertex
s = 0
d[s] = 0
c[s] = 'g'
Q = deque()
Q.append(s)
while Q:
u = Q.popleft()
for v in adj[u]:
if c[v] == 'w':
c[v] = 'g'
d[v] = d[u] + 1
Q.append(v)
c[u] = 'b'
for i in range(n):
print(f'{i+1} {d[i]}')
``` | output | 1 | 76,658 | 13 | 153,317 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1 | instruction | 0 | 76,659 | 13 | 153,318 |
"Correct Solution:
```
from collections import deque
n = int(input())
vdata = [list(map(int,input().split())) for _ in range(n)]
d = [-1]*n
q = deque()
q.append(vdata[0])
d[0] = 0
while len(q) > 0:
node = q.popleft()
c = d[node[0]-1]
a = node[1]
for i in range(a):
b = node[i+2]-1
if d[b] == -1:
d[b] = c+1
q.append(vdata[b])
for i in range(n):
print(i+1, d[i])
``` | output | 1 | 76,659 | 13 | 153,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
from collections import deque
N = int(input())
edge = [[] for _ in range(N+1)]
for i in range(N):
A = list(map(int, input().split()))
edge[A[0]] = A[2:]
ans = [-1]*N
ans[0] = 0
d = deque([[1,0]])
while len(d)>0:
v,dist = d.popleft()
for w in edge[v]:
if ans[w-1]==-1:
ans[w-1]=dist+1
d.append([w,dist+1])
for i in range(N):
print(i+1,ans[i])
``` | instruction | 0 | 76,660 | 13 | 153,320 |
Yes | output | 1 | 76,660 | 13 | 153,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
from collections import deque
n = int(input())
G = [[] for _ in range(n)]
for i in range(n):
u, k, *vs = map(int, input().split())
u -= 1
vs = list(map(lambda x: x - 1, vs))
for v in vs:
G[u].append(v)
dist = [-1] * n
dist[0] = 0
que = deque([0])
while len(que) > 0:
now_v = que.popleft()
now_dist = dist[now_v]
next_vs = G[now_v]
for next_v in next_vs:
if dist[next_v] == -1:
dist[next_v] = now_dist + 1
que.append(next_v)
for i, x in enumerate(dist):
print(i + 1, x)
``` | instruction | 0 | 76,661 | 13 | 153,322 |
Yes | output | 1 | 76,661 | 13 | 153,323 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
from collections import deque
def main():
n = int(input())
_next = [[] for _ in range(n)]
for _ in range(n):
u, k, *v = map(lambda s: int(s) - 1, input().split())
_next[u] = v
queue = deque()
queue.append(0)
d = [-1] * n
d[0] = 0
while queue:
u = queue.popleft()
for v in _next[u]:
if d[v] == -1:
d[v] = d[u] + 1
queue.append(v)
for i, v in enumerate(d, start=1):
print(i, v)
if __name__ == '__main__':
main()
``` | instruction | 0 | 76,662 | 13 | 153,324 |
Yes | output | 1 | 76,662 | 13 | 153,325 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
from collections import deque
n = int(input())
graph = [list(map(int,input().split()))[2:] for _ in range(n)]
dist = [-1]*(n+1)
dist[0] = 0
dist[1] = 0
d = deque()
d.append(1)
while d:
v = d.popleft()-1
if len(graph[v]) >= 1:
for i in graph[v]:
if dist[i] == -1:
dist[i] = dist[v+1]+1
d.append(i)
for i in range(1,n+1):
print(i,dist[i])
``` | instruction | 0 | 76,663 | 13 | 153,326 |
Yes | output | 1 | 76,663 | 13 | 153,327 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
from queue import Queue
n = int(input())
A = [[0 for i in range(n)] for j in range(n)]
d = [-1 for i in range(n)]
for i in range(n):
u, k, *v = list(map(int, input().split()))
for j in v:
A[int(u)-1][int(j)-1] = 1
q = Queue()
q.put(0)
d[0] = 0
while not q.empty():
u = q.get()
# print('visited:', u)
for v in range(n):
# print(u, v)
if A[u][v] == 1 and d[v] == -1:
q.put(v)
d[v] = d[u] + 1
# print('-========')
for i in range(n):
print(i, d[i])
``` | instruction | 0 | 76,664 | 13 | 153,328 |
No | output | 1 | 76,664 | 13 | 153,329 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
def srch(i, l, Lng, Dst):
if Lng[i] > l:
Lng[i] = l
if Dst[i] is not None and len(Dst[i]) > 0:
for c in Dst[i]:
srch(c,l+1, Lng, Dst)
def main():
num = int(input())
Dst = [None for i in range(num + 1)]
Lng = [999] * (num + 1)
for n in range(1, num+1):
a = list(map(int,input().split()))
u = a[0]
if a[1] > 0:
Dst[u] = a[2:]
srch(1, 0, Lng, Dst)
for n in range(1, num+1):
l = Lng[n]
if l > num:
l = -1
print("{} {}".format(n,l))
if __name__ == '__main__':
main()
``` | instruction | 0 | 76,665 | 13 | 153,330 |
No | output | 1 | 76,665 | 13 | 153,331 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
n = int(input())
adj = [list(map(int, input().split()))[2:] for _ in range(n)]
d = [-1] * n
s = 1
q = []
d[s - 1] = 0
q.append(s)
while len(q):
u = q.pop()
v = adj[u - 1]
for vi in v:
if d[vi - 1] == -1:
d[vi - 1] = d[u - 1] + 1
q.append(vi)
for i, di in enumerate(d):
print(i + 1, di)
``` | instruction | 0 | 76,666 | 13 | 153,332 |
No | output | 1 | 76,666 | 13 | 153,333 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which reads an directed graph $G = (V, E)$, and finds the shortest distance from vertex $1$ to each vertex (the number of edges in the shortest path). Vertices are identified by IDs $1, 2, ... n$.
Constraints
* $1 \leq n \leq 100$
Input
In the first line, an integer $n$ denoting the number of vertices, is given. In the next $n$ lines, adjacent lists of vertex $u$ are given in the following format:
$u$ $k$ $v_1$ $v_2$ ... $v_k$
$u$ is ID of the vertex and $k$ denotes its degree.$v_i$ are IDs of vertices adjacent to $u$.
Output
For each vertex $u$, print $id$ and $d$ in a line. $id$ is ID of vertex $u$ and $d$ is the distance from vertex $1$ to vertex $u$. If there are no path from vertex $1$ to vertex $u$, print -1 as the shortest distance. Print in order of IDs.
Example
Input
4
1 2 2 4
2 1 4
3 0
4 1 3
Output
1 0
2 1
3 2
4 1
Submitted Solution:
```
n = int(input())
graph = [[0 for i in range(n)] for j in range(n)]
d = [0] * n
f = [0] * n
queue = [0]
for i in range(n):
a = list(map(int, input().split()))
for j in range(0, a[1], 1):
graph[a[0] - 1][a[2 + j] - 1] = 1
while len(queue) != 0:
i = queue.pop(0)
for j in range(n):
if (graph[i][j] == 1) & (f[j] == 0):
queue.append(j)
f[j] = 1
d[j] = d[i] + 1
[print(i+1, d[i]) for i in range(n)]
``` | instruction | 0 | 76,667 | 13 | 153,334 |
No | output | 1 | 76,667 | 13 | 153,335 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,816 | 13 | 153,632 |
Tags: bitmasks, math, number theory
Correct Solution:
```
N = int(input())
*B, = map(int, input().split())
C = [0]*64
L = [[] for i in range(64)]
for b in B:
l = (b & -b).bit_length()
C[l] += 1
L[l].append(b)
i = C.index(max(C))
R = [b for b in B if (b & -b).bit_length() != i]
print(len(R))
if R:
print(*R)
``` | output | 1 | 76,816 | 13 | 153,633 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,817 | 13 | 153,634 |
Tags: bitmasks, math, number theory
Correct Solution:
```
n=int(input())
l=list(map(int,input().split()))
ans=[0]*65
bans=[0]*n
for i in range(n):
b=l[i]
score=0
while b%2==0:
b//=2
score+=1
ans[score]+=1
bans[i]=score
k=max(ans)
ind=ans.index(k)
print(n-k)
ta=[l[i] for i in range(n) if bans[i]!=ind]
print(*ta)
``` | output | 1 | 76,817 | 13 | 153,635 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,818 | 13 | 153,636 |
Tags: bitmasks, math, number theory
Correct Solution:
```
from collections import Counter
n=int(input())
b=list(map(int,input().split()))
a=[0]*n
def divide_count(n, p):
cnt = 0
val = p
while n % p == 0:
n //= p
cnt += 1
return cnt
for i in range(n):
a[i]=divide_count(b[i],2)
A=Counter(a).most_common()
k=A[0][0]
print(n-A[0][1])
ans=[]
if not n-A[0][1]==0:
for i in range(n):
if a[i]!=k:
ans.append(b[i])
print(*ans)
``` | output | 1 | 76,818 | 13 | 153,637 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,819 | 13 | 153,638 |
Tags: bitmasks, math, number theory
Correct Solution:
```
import sys
input=sys.stdin.readline
n=int(input())
b=list(map(int,input().split()))
p=[[] for i in range(61)]
for i in range(n):
c=b[i]
cnt=0
while c%2==0:
cnt+=1
c//=2
p[cnt].append(b[i])
max_l=0
ans=[]
for i in range(61):
if max_l<len(p[i]):
max_l=len(p[i])
ans=p[i]
arr=list(set(b)-set(ans))
print(len(arr))
print(*arr)
``` | output | 1 | 76,819 | 13 | 153,639 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,820 | 13 | 153,640 |
Tags: bitmasks, math, number theory
Correct Solution:
```
n = int(input())
a = list(map(int, input().split()))
count = [0] * 100
b = [0] * 200005
for i, v in enumerate(a):
tot = 0
while v % 2 == 0:
v //= 2
tot += 1
count[tot] += 1
b[i] = tot
m = max(count)
idx = count.index(m)
print(n-m)
for i in range(n):
if b[i] != idx:
print(a[i], end=' ')
``` | output | 1 | 76,820 | 13 | 153,641 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,821 | 13 | 153,642 |
Tags: bitmasks, math, number theory
Correct Solution:
```
n = int(input())
b = list(map(int, input().split()))
pwr2 = [0] * n
cnt = [0] * 64
for i in range(n):
x = b[i]
while x & 1 == 0:
x >>= 1
pwr2[i] += 1
cnt[pwr2[i]] += 1
ind = 0
for i in range(64):
if cnt[ind] < cnt[i]:
ind = i
print(n - cnt[ind])
print(*(b[i] for i in range(n) if pwr2[i] != ind))
``` | output | 1 | 76,821 | 13 | 153,643 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,822 | 13 | 153,644 |
Tags: bitmasks, math, number theory
Correct Solution:
```
import sys
input = sys.stdin.readline
n=int(input())
B=list(map(int,input().split()))
ANS=[0]*65
BANS=[0]*n
for i in range(n):
b=B[i]
score=0
while b%2==0:
b//=2
score+=1
ANS[score]+=1
BANS[i]=score
k=max(ANS)
ind=ANS.index(k)
print(n-k)
T=[B[i] for i in range(n) if BANS[i]!=ind]
print(*T)
``` | output | 1 | 76,822 | 13 | 153,645 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0 | instruction | 0 | 76,823 | 13 | 153,646 |
Tags: bitmasks, math, number theory
Correct Solution:
```
n = int(input())
a = {}
b = list(map(int,input().split()))
c = []
for d in b:
m = 0
while not d%2:
d //= 2
m += 1
a[m] = a.get(m,0)+1
c.append(m)
m = max(a.values())
print(n-m)
for i in a.keys():
if a[i] == m:
x = i
for i,d in enumerate(c):
if d != x:
print(b[i],end=' ')
``` | output | 1 | 76,823 | 13 | 153,647 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
data = [[] for i in range(70)]
n = int(input())
d = [int(i) for i in input().split()]
for k in d:
j = k
cnt = 0
while not j&1:
cnt += 1
j >>= 1
data[cnt].append(k)
ind = max(range(70), key=lambda a: len(data[a]))
print(n - len(data[ind]))
for i in range(70):
if i != ind:
for v in data[i]:
print(v, end=' ')
``` | instruction | 0 | 76,824 | 13 | 153,648 |
Yes | output | 1 | 76,824 | 13 | 153,649 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
from collections import defaultdict
n = int(input())
b = list(map(int, input().split()))
a = defaultdict(list)
for x in b:
y=x
c = 0
while y%2==0:
y//=2
c+=1
a[c].append(x)
largest = max(a.keys(), key=lambda k: len(a[k]))
out = []
for key, l in a.items():
if key==largest:
continue
out += l
print(len(out))
print(*out)
``` | instruction | 0 | 76,825 | 13 | 153,650 |
Yes | output | 1 | 76,825 | 13 | 153,651 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
from sys import stdin
n = int(stdin.readline())
nums = [int(x) for x in stdin.readline().split()]
most = 0
most2 = []
nums2 = nums[:]
d = 2
while nums2:
evens = []
odds = []
for x in nums2:
if x%d == 0:
evens.append(x)
else:
odds.append(x)
if len(odds) > most:
most = len(odds)
most2 = odds
nums2 = evens
d *= 2
print(n-most)
most2 = set(most2)
outL = []
for x in nums:
if not x in most2:
outL.append(x)
print(' '.join([str(x) for x in outL]))
``` | instruction | 0 | 76,826 | 13 | 153,652 |
Yes | output | 1 | 76,826 | 13 | 153,653 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
import sys
input=sys.stdin.readline
import copy
from math import *
n=int(input())
a=[int(x) for x in input().split()]
d=[0 for i in range(70)]
for i in range(n):
l=bin(a[i])[2:]
d[l[::-1].index('1')]+=1
print(n-max(d))
r=d.index(max(d))
for i in range(n):
l=bin(a[i])[2:]
if l[::-1].index('1')!=r:
print(a[i],end=" ")
``` | instruction | 0 | 76,827 | 13 | 153,654 |
Yes | output | 1 | 76,827 | 13 | 153,655 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
n = int(input())
B = list(map(int, input().split()))
even = []
even2 = []
odd = []
for i in B:
if i % 2:
odd.append(i)
elif i % 4 == 2:
even.append(i)
else:
even2.append(i)
mlen = max(len(even), len(even2), len(odd))
if len(odd) == mlen:
print(len(even) + len(even2))
print(' '.join(list(map(str, even))) + ' ' + ' '.join(list(map(str, even2))))
elif len(even) == mlen:
print(len(odd) + len(even2))
print(' '.join(list(map(str, odd))) + ' ' + ' '.join(list(map(str, even2))))
else:
print(len(odd) + len(even))
print(' '.join(list(map(str, odd))) + ' ' + ' '.join(list(map(str, even))))
``` | instruction | 0 | 76,828 | 13 | 153,656 |
No | output | 1 | 76,828 | 13 | 153,657 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
a = int(input())
b = sorted([int(s) for s in input().split()])
c = [b[i] for i in range(len(b))]
d1 = {}
d2 = {}
for i in range(len(b)):
if c[i] == b[i]:
d1[b[i]] = 1
d2[b[i]] = [b[i]]
for j in range(i + 1, len(b)):
if (b[j] / b[i]) % 2 == 1:
c[j] = b[i]
d1[b[i]] += 1
d2[b[i]].append(b[j])
# print(d1, d2, len(d1.keys()))
if len(d1.keys()) == 1: print(0)
else:
print(min(d1.values()))
for i in d2:
if len(d2[i]) == min(d1.values()):
for j in d2[i]: print(j, end = " ")
break
``` | instruction | 0 | 76,829 | 13 | 153,658 |
No | output | 1 | 76,829 | 13 | 153,659 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
"""
NTC here
"""
from sys import setcheckinterval, stdin, setrecursionlimit
setcheckinterval(1000)
setrecursionlimit(10**7)
# print("Case #{}: {} {}".format(i, n + m, n * m))
def iin(): return int(stdin.readline())
def lin(): return list(map(int, stdin.readline().split()))
n=iin()
a=lin()
sa=set(a)
s1={a[0]}
s2=set()
rm=[]
for i in range(1,n):
x=abs(a[0]-a[i])
if x in sa:
if x not in s2:
s2.add(a[i])
else:
rm.append(x)
sa.remove(x)
print(len(rm))
print(*rm, sep='\n')
``` | instruction | 0 | 76,830 | 13 | 153,660 |
No | output | 1 | 76,830 | 13 | 153,661 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Boy Dima gave Julian a birthday present — set B consisting of positive integers. However, he didn't know, that Julian hates sets, but enjoys bipartite graphs more than anything else!
Julian was almost upset, but her friend Alex said, that he can build an undirected graph using this set in such a way: let all integer numbers be vertices, then connect any two i and j with an edge if |i - j| belongs to B.
Unfortunately, Julian doesn't like the graph, that was built using B. Alex decided to rectify the situation, so he wants to erase some numbers from B, so that graph built using the new set is bipartite. The difficulty of this task is that the graph, Alex has to work with, has an infinite number of vertices and edges! It is impossible to solve this task alone, so Alex asks you for help. Write a program that erases a subset of minimum size from B so that graph constructed on the new set is bipartite.
Recall, that graph is bipartite if all its vertices can be divided into two disjoint sets such that every edge connects a vertex from different sets.
Input
First line contains an integer n ~ (1 ⩽ n ⩽ 200 000) — size of B
Second line contains n integers b_1, b_2, …, b_n ~ (1 ⩽ b_i ⩽ 10^{18}) — numbers of B, all b_i are unique
Output
In the first line print single integer k – the number of erased elements. In the second line print k integers — values of erased elements.
If there are multiple answers, print any of them.
Examples
Input
3
1 2 3
Output
1
2
Input
2
2 6
Output
0
Submitted Solution:
```
n=int(input())
b=list(map(int,input().split()))
b2=[]
for i in b:
i/=2
c=0
while i%1==0:
c+=1
i/=2
b2.append(c)
b2s=set(b2)
cv,cvr=0,-1
for i in b2s:
cvc=b2.count(i)
if cvc>cvr:
cv=i
cvr=cvc
pr=False
for i in range(n):
if b2[i]!=cv:
print(b[i],end=" ")
pr=True
if not pr:
print(0+" ")
``` | instruction | 0 | 76,831 | 13 | 153,662 |
No | output | 1 | 76,831 | 13 | 153,663 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero.
Constraints
* All the inputs are given in integers
* $ 2 \leq n \leq 100000 $
* $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$
* $ 2 \leq q \leq 200000 $
* $ 1 \leq u,v \leq n-1 $
* $ 1 \leq w \leq 10000 $
Input
The input is given in the following format.
$n$
$node_0$
$node_1$
$node_2$
$:$
$node_{n-1}$
$q$
$query_1$
$query_2$
$:$
$query_{q}$
The first line of the input includes an integer $n$, the number of nodes in the tree.
In the next $n$ lines,the information of node $i$ is given in the following format:
ki c1 c2 ... ck
$k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$.
In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format:
0 v w
or
1 u
The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$.
Output
For each $getSum$ query, print the sum in a line.
Examples
Input
6
2 1 2
2 3 5
0
0
0
1 4
7
1 1
0 3 10
1 2
0 4 20
1 3
0 5 40
1 4
Output
0
0
40
150
Input
4
1 1
1 2
1 3
0
6
0 3 1000
0 2 1000
0 1 1000
1 1
1 2
1 3
Output
3000
5000
6000 | instruction | 0 | 77,547 | 13 | 155,094 |
"Correct Solution:
```
from collections import deque
import sys
from typing import List
sys.setrecursionlimit(200000)
N = int(input())
G: List[List[int]] = [[0]] * N
for i in range(N):
k, *c = map(lambda x: int(x), input().split())
G[i] = c
H = [0] * N
prv = [None] * N
def dfs(v):
s = 1
heavy = None
m = 0
for w in G[v]:
prv[w] = v
c = dfs(w)
if m < c:
heavy = w
m = c
s += c
H[v] = heavy
return s
dfs(0)
SS: List[List[int]] = []
D: List[int] = []
L = [0] * N
I = [0] * N # noqa: E741
que = deque([(0, 0)])
while que:
v, d = que.popleft()
S: List[int] = []
k = len(SS)
while v is not None:
I[v] = len(S)
S.append(v)
L[v] = k
h = H[v]
for w in G[v]:
if h == w:
continue
que.append((w, d + 1))
v = h
SS.append(S)
D.append(d)
C = list(map(len, SS))
DS0 = [[0] * (c + 1) for c in C]
DS1 = [[0] * (c + 1) for c in C]
def add(K, data, k, x):
while k <= K:
data[k] += x
k += k & -k
def get(K, data, k):
s = 0
while k:
s += data[k]
k -= k & -k
return s
def query_add(v, x):
while v is not None:
l = L[v] # noqa: E741
i = I[v]
add(C[l], DS1[l], i + 1, -x)
add(C[l], DS1[l], 1, x)
add(C[l], DS0[l], i + 1, x * (i + 1))
v = prv[SS[l][0]]
def query_sum(v):
s = - get(C[0], DS1[L[0]], 1) - get(C[0], DS0[L[0]], 1)
while v is not None:
l = L[v] # noqa: E741
i = I[v]
s += get(C[l], DS1[l], i + 1) * (i + 1) + get(C[l], DS0[l], i + 1)
v = prv[SS[l][0]]
return s
Q = int(input())
ans = []
for q in range(Q):
t, *cmd = map(lambda x: int(x), input().split())
if t:
ans.append(str(query_sum(cmd[0])))
else:
v, w = cmd
query_add(v, w)
print("\n".join(ans))
``` | output | 1 | 77,547 | 13 | 155,095 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero.
Constraints
* All the inputs are given in integers
* $ 2 \leq n \leq 100000 $
* $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$
* $ 2 \leq q \leq 200000 $
* $ 1 \leq u,v \leq n-1 $
* $ 1 \leq w \leq 10000 $
Input
The input is given in the following format.
$n$
$node_0$
$node_1$
$node_2$
$:$
$node_{n-1}$
$q$
$query_1$
$query_2$
$:$
$query_{q}$
The first line of the input includes an integer $n$, the number of nodes in the tree.
In the next $n$ lines,the information of node $i$ is given in the following format:
ki c1 c2 ... ck
$k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$.
In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format:
0 v w
or
1 u
The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$.
Output
For each $getSum$ query, print the sum in a line.
Examples
Input
6
2 1 2
2 3 5
0
0
0
1 4
7
1 1
0 3 10
1 2
0 4 20
1 3
0 5 40
1 4
Output
0
0
40
150
Input
4
1 1
1 2
1 3
0
6
0 3 1000
0 2 1000
0 1 1000
1 1
1 2
1 3
Output
3000
5000
6000 | instruction | 0 | 77,548 | 13 | 155,096 |
"Correct Solution:
```
from collections import deque
import sys
sys.setrecursionlimit(10**6)
readline = sys.stdin.readline
write = sys.stdout.write
N = int(readline())
G = [None]*N
for i in range(N):
k, *c = map(int, readline().split())
G[i] = c
H = [0]*N
prv = [None]*N
def dfs(v):
s = 1; heavy = None; m = 0
for w in G[v]:
prv[w] = v
c = dfs(w)
if m < c:
heavy = w
m = c
s += c
H[v] = heavy
return s
dfs(0)
SS = []
D = []
L = [0]*N
I = [0]*N
que = deque([(0, 0)])
while que:
v, d = que.popleft()
S = []
k = len(SS)
while v is not None:
I[v] = len(S)
S.append(v)
L[v] = k
h = H[v]
for w in G[v]:
if h == w:
continue
que.append((w, d+1))
v = h
SS.append(S)
D.append(d)
C = list(map(len, SS))
DS0 = [[0]*(c+1) for c in C]
DS1 = [[0]*(c+1) for c in C]
def add(K, data, k, x):
while k <= K:
data[k] += x
k += k & -k
def get(K, data, k):
s = 0
while k:
s += data[k]
k -= k & -k
return s
def query_add(v, x):
while v is not None:
l = L[v]; i = I[v]
add(C[l], DS1[l], i+1, -x)
add(C[l], DS1[l], 1, x)
add(C[l], DS0[l], i+1, x*(i+1))
v = prv[SS[l][0]]
def query_sum(v):
s = - get(C[0], DS1[L[0]], 1) - get(C[0], DS0[L[0]], 1)
while v is not None:
l = L[v]; i = I[v]
s += get(C[l], DS1[l], i+1)*(i+1) + get(C[l], DS0[l], i+1)
v = prv[SS[l][0]]
return s
Q = int(readline())
ans = []
for q in range(Q):
t, *cmd = map(int, readline().split())
if t:
ans.append(str(query_sum(cmd[0])))
else:
v, w = cmd
query_add(v, w)
write("\n".join(ans))
write("\n")
``` | output | 1 | 77,548 | 13 | 155,097 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero.
Constraints
* All the inputs are given in integers
* $ 2 \leq n \leq 100000 $
* $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$
* $ 2 \leq q \leq 200000 $
* $ 1 \leq u,v \leq n-1 $
* $ 1 \leq w \leq 10000 $
Input
The input is given in the following format.
$n$
$node_0$
$node_1$
$node_2$
$:$
$node_{n-1}$
$q$
$query_1$
$query_2$
$:$
$query_{q}$
The first line of the input includes an integer $n$, the number of nodes in the tree.
In the next $n$ lines,the information of node $i$ is given in the following format:
ki c1 c2 ... ck
$k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$.
In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format:
0 v w
or
1 u
The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$.
Output
For each $getSum$ query, print the sum in a line.
Examples
Input
6
2 1 2
2 3 5
0
0
0
1 4
7
1 1
0 3 10
1 2
0 4 20
1 3
0 5 40
1 4
Output
0
0
40
150
Input
4
1 1
1 2
1 3
0
6
0 3 1000
0 2 1000
0 1 1000
1 1
1 2
1 3
Output
3000
5000
6000 | instruction | 0 | 77,549 | 13 | 155,098 |
"Correct Solution:
```
#!/usr/bin/env python3
# GRL_5_E: Tree - Range Query on Tree 2
# Undirected Graph
class Edge:
__slots__ = ('v', 'w')
def __init__(self, v, w):
self.v = v
self.w = w
def either(self):
return self.v
def other(self, v):
if v == self.v:
return self.w
else:
return self.v
class Graph:
def __init__(self, v):
self.v = v
self._edges = [[] for _ in range(v)]
def add(self, e):
self._edges[e.v].append(e)
self._edges[e.w].append(e)
def adj(self, v):
return self._edges[v]
def edges(self):
for es in self._edges:
for e in es:
yield e
class HeavyLightDecomposition:
class _Path:
__slots__ = ('nodes', '_index')
def __init__(self):
self.nodes = []
self._index = None
@property
def head(self):
return self.nodes[0]
@property
def size(self):
return len(self.nodes)
def append(self, v):
self.nodes.append(v)
def index(self, v):
if self._index is None:
self._index = {v: i for i, v in enumerate(self.nodes)}
return self._index[v]
def next(self, v):
return self.nodes[self.index(v)+1]
def __init__(self, graph, root):
self._paths = {}
self._parent = [root] * graph.v
self._head = [-1] * graph.v
self._find_paths(graph, root)
def _find_paths(self, graph, root):
def create_path(v):
path = self._Path()
u = v
while u != -1:
path.append(u)
self._head[u] = v
u = heavy[u]
return path
size = [1] * graph.v
maxsize = [0] * graph.v
heavy = [-1] * graph.v
visited = [False] * graph.v
stack = [root]
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
stack.append(v)
for e in graph.adj(v):
w = e.other(v)
if not visited[w]:
self._parent[w] = v
stack.append(w)
else:
if v != root:
p = self._parent[v]
if size[v] > maxsize[p]:
maxsize[p] = size[v]
heavy[p] = v
size[p] += size[v]
for e in graph.adj(v):
w = e.other(v)
if w != self._parent[v] and w != heavy[v]:
self._paths[w] = create_path(w)
self._paths[root] = create_path(root)
def parent(self, v):
return self._parent[v]
def paths(self):
return self._paths.values()
def get_path(self, v):
return self._paths[self._head[v]]
class PathSum2:
"""PathSum with range update.
"""
def __init__(self, graph, root):
self.root = root
self.hld = HeavyLightDecomposition(graph, root)
self.rq = {p.head: RangeQuery(p.size) for p in self.hld.paths()}
def add(self, v, val):
u = v
while u != self.root:
path = self.hld.get_path(u)
head = path.head
if head != self.root:
i = path.index(head)
else:
i = path.index(path.next(head))
j = path.index(u)
self.rq[head].add(i+1, j+1, val)
u = self.hld.parent(head)
def get(self, v):
weight = 0
u = v
while u != self.root:
path = self.hld.get_path(u)
head = path.head
i = path.index(head)
j = path.index(u)
weight += self.rq[head].sum(i+1, j+1)
u = self.hld.parent(head)
return weight
# Binary Indexed Tree
class BinaryIndexedTree:
def __init__(self, n):
self.size = n
self.bit = [0] * (self.size+1)
def add(self, i, v):
while i <= self.size:
self.bit[i] += v
i += (i & -i)
def sum(self, i):
s = 0
while i > 0:
s += self.bit[i]
i -= (i & -i)
return s
class RangeQuery:
def __init__(self, n):
self.size = n
self.bit1 = BinaryIndexedTree(n+1)
self.bit2 = BinaryIndexedTree(n+1)
def add(self, i, j, v):
self.bit1.add(i, v * -i)
self.bit1.add(j+1, v * (j+1))
self.bit2.add(i, v)
self.bit2.add(j+1, -v)
def sum(self, i, j):
s = self.bit1.sum(j+1) + (j+1)*self.bit2.sum(j+1)
s -= self.bit1.sum(i) + i*self.bit2.sum(i)
return s
def run():
n = int(input())
g = Graph(n)
for i in range(n):
k, *cs = [int(i) for i in input().split()]
if k > 0:
for j in cs:
g.add(Edge(i, j))
ps = PathSum2(g, 0)
q = int(input())
for _ in range(q):
com, *args = [int(i) for i in input().split()]
if com == 0:
u, val = args
ps.add(u, val)
elif com == 1:
u, = args
print(ps.get(u))
else:
raise ValueError('invalid command')
if __name__ == '__main__':
run()
``` | output | 1 | 77,549 | 13 | 155,099 |
Provide a correct Python 3 solution for this coding contest problem.
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero.
Constraints
* All the inputs are given in integers
* $ 2 \leq n \leq 100000 $
* $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$
* $ 2 \leq q \leq 200000 $
* $ 1 \leq u,v \leq n-1 $
* $ 1 \leq w \leq 10000 $
Input
The input is given in the following format.
$n$
$node_0$
$node_1$
$node_2$
$:$
$node_{n-1}$
$q$
$query_1$
$query_2$
$:$
$query_{q}$
The first line of the input includes an integer $n$, the number of nodes in the tree.
In the next $n$ lines,the information of node $i$ is given in the following format:
ki c1 c2 ... ck
$k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$.
In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format:
0 v w
or
1 u
The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$.
Output
For each $getSum$ query, print the sum in a line.
Examples
Input
6
2 1 2
2 3 5
0
0
0
1 4
7
1 1
0 3 10
1 2
0 4 20
1 3
0 5 40
1 4
Output
0
0
40
150
Input
4
1 1
1 2
1 3
0
6
0 3 1000
0 2 1000
0 1 1000
1 1
1 2
1 3
Output
3000
5000
6000 | instruction | 0 | 77,550 | 13 | 155,100 |
"Correct Solution:
```
class Tree():
def __init__(self, n, edge):
self.n = n
self.tree = [[] for _ in range(n)]
for e in edge:
self.tree[e[0] - 1].append(e[1] - 1)
self.tree[e[1] - 1].append(e[0] - 1)
def setroot(self, root):
self.root = root
self.parent = [None for _ in range(self.n)]
self.parent[root] = -1
self.depth = [None for _ in range(self.n)]
self.depth[root] = 0
self.order = []
self.order.append(root)
self.size = [1 for _ in range(self.n)]
stack = [root]
while stack:
node = stack.pop()
for adj in self.tree[node]:
if self.parent[adj] is None:
self.parent[adj] = node
self.depth[adj] = self.depth[node] + 1
self.order.append(adj)
stack.append(adj)
for node in self.order[::-1]:
for adj in self.tree[node]:
if self.parent[node] == adj:
continue
self.size[node] += self.size[adj]
def heavylight_decomposition(self):
self.order = [None for _ in range(self.n)]
self.head = [None for _ in range(self.n)]
self.head[self.root] = self.root
self.next = [None for _ in range(self.n)]
stack = [self.root]
order = 0
while stack:
node = stack.pop()
self.order[node] = order
order += 1
maxsize = 0
for adj in self.tree[node]:
if self.parent[node] == adj:
continue
if maxsize < self.size[adj]:
maxsize = self.size[adj]
self.next[node] = adj
for adj in self.tree[node]:
if self.parent[node] == adj or self.next[node] == adj:
continue
self.head[adj] = adj
stack.append(adj)
if self.next[node] is not None:
self.head[self.next[node]] = self.head[node]
stack.append(self.next[node])
def range_hld(self, u, v, edge=False):
res = []
while True:
if self.order[u] > self.order[v]: u, v = v, u
if self.head[u] != self.head[v]:
res.append((self.order[self.head[v]], self.order[v] + 1))
v = self.parent[self.head[v]]
else:
res.append((self.order[u] + edge, self.order[v] + 1))
return res
def subtree_hld(self, u):
return self.order[u], self.order[u] + self.size[u]
def lca_hld(self, u, v):
while True:
if self.order[u] > self.order[v]: u, v = v, u
if self.head[u] != self.head[v]:
v = self.parent[self.head[v]]
else:
return u
class BinaryIndexedTree(): #1-indexed
def __init__(self, n):
self.n = n
self.tree = [0 for _ in range(n + 1)]
def sum(self, idx):
res = 0
while idx:
res += self.tree[idx]
idx -= idx & -idx
return res
def add(self, idx, x):
while idx <= self.n:
self.tree[idx] += x
idx += idx & -idx
def bisect_left(self, x):
if x <= 0: return 0
res, tmp = 0, 2**((self.n).bit_length() - 1)
while tmp:
if res + tmp <= self.n and self.tree[res + tmp] < x:
x -= self.tree[res + tmp]
res += tmp
tmp >>= 1
return res + 1
class RAQandRSQ():
def __init__(self, n):
self.bit1 = BinaryIndexedTree(n)
self.bit2 = BinaryIndexedTree(n)
def add(self, lt, rt, x):
self.bit1.add(lt, -x * (lt - 1))
self.bit1.add(rt, x * (rt - 1))
self.bit2.add(lt, x)
self.bit2.add(rt, -x)
def sum(self, lt, rt):
rsum = self.bit2.sum(rt - 1) * (rt - 1) + self.bit1.sum(rt - 1)
lsum = self.bit2.sum(lt - 1) * (lt - 1) + self.bit1.sum(lt - 1)
return rsum - lsum
import sys
input = sys.stdin.readline
from operator import add
N = int(input())
E = []
for i in range(N):
k, *c = map(int, input().split())
for j in range(k):
E.append((i + 1, c[j] + 1))
t = Tree(N, E)
t.setroot(0)
t.heavylight_decomposition()
r = RAQandRSQ(N)
res = []
Q = int(input())
for _ in range(Q):
q, *p = map(int, input().split())
if q == 0:
v, w = p
for lt, rt in t.range_hld(0, v, edge=True):
r.add(lt, rt, w)
else:
s = 0
u, = p
for lt, rt in t.range_hld(0, u, edge=True):
s += r.sum(lt, rt)
res.append(s)
print('\n'.join(map(str, res)))
``` | output | 1 | 77,550 | 13 | 155,101 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Write a program which manipulates a weighted rooted tree $T$ with the following operations:
* $add(v,w)$: add $w$ to all edges from the root to node $u$
* $getSum(u)$: report the sum of weights of all edges from the root to node $u$
The given tree $T$ consists of $n$ nodes and every node has a unique ID from $0$ to $n-1$ respectively where ID of the root is $0$. Note that all weights are initialized to zero.
Constraints
* All the inputs are given in integers
* $ 2 \leq n \leq 100000 $
* $ c_j < c_{j+1} $ $( 1 \leq j \leq k-1 )$
* $ 2 \leq q \leq 200000 $
* $ 1 \leq u,v \leq n-1 $
* $ 1 \leq w \leq 10000 $
Input
The input is given in the following format.
$n$
$node_0$
$node_1$
$node_2$
$:$
$node_{n-1}$
$q$
$query_1$
$query_2$
$:$
$query_{q}$
The first line of the input includes an integer $n$, the number of nodes in the tree.
In the next $n$ lines,the information of node $i$ is given in the following format:
ki c1 c2 ... ck
$k_i$ is the number of children of node $i$, and $c_1$ $c_2$ ... $c_{k_i}$ are node IDs of 1st, ... $k$th child of node $i$.
In the next line, the number of queries $q$ is given. In the next $q$ lines, $i$th query is given in the following format:
0 v w
or
1 u
The first integer represents the type of queries.'0' denotes $add(v, w)$ and '1' denotes $getSum(u)$.
Output
For each $getSum$ query, print the sum in a line.
Examples
Input
6
2 1 2
2 3 5
0
0
0
1 4
7
1 1
0 3 10
1 2
0 4 20
1 3
0 5 40
1 4
Output
0
0
40
150
Input
4
1 1
1 2
1 3
0
6
0 3 1000
0 2 1000
0 1 1000
1 1
1 2
1 3
Output
3000
5000
6000
Submitted Solution:
```
#!/usr/bin/env python3
# GRL_5_E: Tree - Range Query on Tree 2
class RAQ:
def __init__(self, n, initial=0):
size = 1
while size < n:
size *= 2
self.size = 2*size - 1
self.data = [initial] * self.size
def add(self, i, j, v):
def _add(r, lo, hi):
if hi < i or lo > j:
return
elif i <= lo and hi <= j:
self.data[r] += v
else:
mid = lo + (hi - lo)//2
_add(r*2 + 1, lo, mid)
_add(r*2 + 2, mid+1, hi)
return _add(0, 0, self.size//2)
def add_nested(self, ranges, v):
def _add(r, lo, hi, n):
while n >= 0:
i, j = ranges[n]
if hi < i or lo > j:
return
elif (i <= lo and hi <= j):
self.data[r] += v
n -= 1
else:
mid = lo + (hi - lo)//2
_add(r*2 + 1, lo, mid, n)
_add(r*2 + 2, mid+1, hi, n)
return
return _add(0, 0, self.size//2, len(ranges)-1)
def get(self, i):
def _get(r, lo, hi, v):
v += self.data[r]
if lo == hi:
return v
mid = lo + (hi - lo)//2
if mid >= i:
return _get(r*2 + 1, lo, mid, v)
else:
return _get(r*2 + 2, mid+1, hi, v)
return _get(0, 0, self.size//2, 0)
class Edge:
__slots__ = ('v', 'w')
def __init__(self, v, w):
self.v = v
self.w = w
def either(self):
return self.v
def other(self, v):
if v == self.v:
return self.w
else:
return self.v
class Graph:
def __init__(self, v):
self.v = v
self._edges = [[] for _ in range(v)]
def add(self, e):
self._edges[e.v].append(e)
self._edges[e.w].append(e)
def adj(self, v):
return self._edges[v]
def edges(self):
for es in self._edges:
for e in es:
yield e
class PathSum2:
"""PathSum with range update.
"""
def __init__(self, graph, root):
self.root = root
self.seg = RAQ(graph.v)
self._dfs(graph, root)
def _dfs(self, graph, root):
visited = [False] * graph.v
pos = [None] * graph.v
parent = [None] * graph.v
stack = [root]
n = 0
ns = []
while stack:
v = stack.pop()
if not visited[v]:
visited[v] = True
ns.append(n)
n += 1
stack.append(v)
for e in graph.adj(v):
w = e.other(v)
if not visited[w]:
parent[w] = v
stack.append(w)
else:
pos[v] = (ns.pop(), n - 1)
self._pos = pos
self._parent = parent
def add(self, v, val):
ps = []
u = v
while u != self.root:
ps.append(self._pos[u])
u = self._parent[u]
self.seg.add_nested(ps, val)
def get(self, v):
return self.seg.get(self._pos[v][0])
def run():
n = int(input())
g = Graph(n)
for i in range(n):
k, *cs = [int(i) for i in input().split()]
if k > 0:
for j in cs:
g.add(Edge(i, j))
ps = PathSum2(g, 0)
q = int(input())
for _ in range(q):
com, *args = [int(i) for i in input().split()]
if com == 0:
u, val = args
ps.add(u, val)
elif com == 1:
u, = args
print(ps.get(u))
else:
raise ValueError('invalid command')
if __name__ == '__main__':
run()
``` | instruction | 0 | 77,551 | 13 | 155,102 |
No | output | 1 | 77,551 | 13 | 155,103 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.
You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you.
<image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.
You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms:
* A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling.
* B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling.
Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
Interaction
Each test consists of several test cases.
The first line of input contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
For each testcase, your program should interact in the following format.
The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers a_i and b_i (1≤ a_i, b_i≤ n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.
The next line contains a single integer k_1 (1 ≤ k_1 ≤ n) — the number of nodes in your subtree.
The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.
The next line contains a single integer k_2 (1 ≤ k_2 ≤ n) — the number of nodes in Li Chen's subtree.
The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.
Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.
You can ask the Andrew two different types of questions.
* You can print "A x" (1 ≤ x ≤ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling.
* You can print "B y" (1 ≤ y ≤ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling.
You may only ask at most 5 questions per tree.
When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case.
After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hack Format
To hack, use the following format. Note that you can only hack with one test case.
The first line should contain a single integer t (t=1).
The second line should contain a single integer n (1 ≤ n ≤ 1 000).
The third line should contain n integers p_1, p_2, …, p_n (1≤ p_i≤ n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.
Each of the next n-1 lines should contain two integers a_i and b_i (1≤ a_i, b_i≤ n). These edges should form a tree.
The next line should contain a single integer k_1 (1 ≤ k_1 ≤ n).
The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n). These vertices should form a subtree.
The next line should contain a single integer k_2 (1 ≤ k_2 ≤ n).
The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n). These vertices should form a subtree in Li Chen's tree according to the permutation above.
Examples
Input
1
3
1 2
2 3
1
1
1
2
2
1
Output
A 1
B 2
C 1
Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Output
B 2
C 1
A 1
C -1
Note
For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.
In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:
<image>
In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions).
For the second sample, there are two test cases. The first looks is the one from the statement:
<image>
We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.
In the second case in the second sample, the situation looks as follows:
<image>
In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. | instruction | 0 | 77,571 | 13 | 155,142 |
Tags: dfs and similar, interactive, trees
Correct Solution:
```
import sys
from collections import deque
t=int(sys.stdin.readline())
for i in range(t):
n=int(sys.stdin.readline())#node
EDGE=[list(map(int,sys.stdin.readline().split())) for i in range(n-1)]
k1=int(sys.stdin.readline())
X=list(map(int,sys.stdin.readline().split()))
k2=int(sys.stdin.readline())
Y=list(map(int,sys.stdin.readline().split()))
print("B",Y[0],flush=True)
yans=int(input())
if yans in X:
print("C",yans,flush=True)
else:
QUE=deque([yans])
EDGELIST=[[] for i in range(n+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
checked=[0]*(n+1)
XLIST=[0]*(n+1)
for xver in X:
XLIST[xver]=1
while QUE:
now=QUE.pop()
checked[now]=1
for ver in EDGELIST[now]:
if checked[ver]==1:
continue
else:
QUE.append(ver)
if XLIST[now]==1:
break
print("A",now,flush=True)
if int(input()) in Y:
print("C",now,flush=True)
else:
print("C",-1,flush=True)
``` | output | 1 | 77,571 | 13 | 155,143 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.
You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you.
<image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.
You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms:
* A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling.
* B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling.
Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
Interaction
Each test consists of several test cases.
The first line of input contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
For each testcase, your program should interact in the following format.
The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers a_i and b_i (1≤ a_i, b_i≤ n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.
The next line contains a single integer k_1 (1 ≤ k_1 ≤ n) — the number of nodes in your subtree.
The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.
The next line contains a single integer k_2 (1 ≤ k_2 ≤ n) — the number of nodes in Li Chen's subtree.
The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.
Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.
You can ask the Andrew two different types of questions.
* You can print "A x" (1 ≤ x ≤ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling.
* You can print "B y" (1 ≤ y ≤ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling.
You may only ask at most 5 questions per tree.
When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case.
After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hack Format
To hack, use the following format. Note that you can only hack with one test case.
The first line should contain a single integer t (t=1).
The second line should contain a single integer n (1 ≤ n ≤ 1 000).
The third line should contain n integers p_1, p_2, …, p_n (1≤ p_i≤ n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.
Each of the next n-1 lines should contain two integers a_i and b_i (1≤ a_i, b_i≤ n). These edges should form a tree.
The next line should contain a single integer k_1 (1 ≤ k_1 ≤ n).
The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n). These vertices should form a subtree.
The next line should contain a single integer k_2 (1 ≤ k_2 ≤ n).
The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n). These vertices should form a subtree in Li Chen's tree according to the permutation above.
Examples
Input
1
3
1 2
2 3
1
1
1
2
2
1
Output
A 1
B 2
C 1
Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Output
B 2
C 1
A 1
C -1
Note
For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.
In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:
<image>
In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions).
For the second sample, there are two test cases. The first looks is the one from the statement:
<image>
We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.
In the second case in the second sample, the situation looks as follows:
<image>
In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. | instruction | 0 | 77,572 | 13 | 155,144 |
Tags: dfs and similar, interactive, trees
Correct Solution:
```
from collections import deque
import sys
t = int(input())
for i in range(t):
n = int(input())
edge = {}
for j in range(1,n+1):
a = set()
edge[j] = a
for k in range(n-1):
a,b = map(int,input().split())
edge[a].add(b)
edge[b].add(a)
k1 = int(input())
x = input().split()
mysubg = set()
for j in range(len(x)):
mysubg.add(int(x[j]))
k2 = int(input())
y = input().split()
notmysubg = set()
for j in range(len(y)):
notmysubg.add(int(y[j]))
root = int(x[0])
print("B "+y[0])
sys.stdout.flush()
goal = int(input())
d = deque([root])
visit = set()
parent = {}
while len(d) > 0:
cur = d.popleft()
for neigh in edge[cur]:
if neigh not in visit:
visit.add(neigh)
d.append(neigh)
parent[neigh] = cur
while goal != root:
if goal in mysubg:
break
goal = parent[goal]
print("A "+str(goal))
sys.stdout.flush()
goal2 = int(input())
if goal2 in notmysubg:
print("C "+str(goal))
else:
print("C -1")
``` | output | 1 | 77,572 | 13 | 155,145 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.
You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you.
<image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.
You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms:
* A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling.
* B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling.
Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
Interaction
Each test consists of several test cases.
The first line of input contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
For each testcase, your program should interact in the following format.
The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers a_i and b_i (1≤ a_i, b_i≤ n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.
The next line contains a single integer k_1 (1 ≤ k_1 ≤ n) — the number of nodes in your subtree.
The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.
The next line contains a single integer k_2 (1 ≤ k_2 ≤ n) — the number of nodes in Li Chen's subtree.
The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.
Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.
You can ask the Andrew two different types of questions.
* You can print "A x" (1 ≤ x ≤ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling.
* You can print "B y" (1 ≤ y ≤ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling.
You may only ask at most 5 questions per tree.
When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case.
After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hack Format
To hack, use the following format. Note that you can only hack with one test case.
The first line should contain a single integer t (t=1).
The second line should contain a single integer n (1 ≤ n ≤ 1 000).
The third line should contain n integers p_1, p_2, …, p_n (1≤ p_i≤ n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.
Each of the next n-1 lines should contain two integers a_i and b_i (1≤ a_i, b_i≤ n). These edges should form a tree.
The next line should contain a single integer k_1 (1 ≤ k_1 ≤ n).
The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n). These vertices should form a subtree.
The next line should contain a single integer k_2 (1 ≤ k_2 ≤ n).
The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n). These vertices should form a subtree in Li Chen's tree according to the permutation above.
Examples
Input
1
3
1 2
2 3
1
1
1
2
2
1
Output
A 1
B 2
C 1
Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Output
B 2
C 1
A 1
C -1
Note
For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.
In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:
<image>
In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions).
For the second sample, there are two test cases. The first looks is the one from the statement:
<image>
We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.
In the second case in the second sample, the situation looks as follows:
<image>
In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes. | instruction | 0 | 77,573 | 13 | 155,146 |
Tags: dfs and similar, interactive, trees
Correct Solution:
```
import sys
def ask(u, t):
if t == 0:
print('A', u)
else:
print('B', u)
sys.stdout.flush()
return int(input())
def solve():
n = int(input())
e = [[] for _ in range(n + 1)]
p = [0] * (n + 1)
inA = [False] * (n + 1)
for _ in range(n - 1):
u, v = map(int, input().split())
e[u].append(v)
e[v].append(u)
def dfs(v):
for u in e[v]:
if p[u] == 0:
p[u] = v
dfs(u)
a = int(input())
A = list(map(int, input().split()))
for u in A:
inA[u] = True
b = int(input())
B = list(map(int, input().split()))
dfs(A[0])
r = ask(B[0], 1)
while not inA[r]:
r = p[r]
v = ask(r, 0)
print('C', r) if v in B else print('C', -1)
sys.stdout.flush()
t = int(input())
for _ in range(t):
solve()
``` | output | 1 | 77,573 | 13 | 155,147 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are playing a strange game with Li Chen. You have a tree with n nodes drawn on a piece of paper. All nodes are unlabeled and distinguishable. Each of you independently labeled the vertices from 1 to n. Neither of you know the other's labelling of the tree.
You and Li Chen each chose a subtree (i.e., a connected subgraph) in that tree. Your subtree consists of the vertices labeled x_1, x_2, …, x_{k_1} in your labeling, Li Chen's subtree consists of the vertices labeled y_1, y_2, …, y_{k_2} in his labeling. The values of x_1, x_2, …, x_{k_1} and y_1, y_2, …, y_{k_2} are known to both of you.
<image> The picture shows two labelings of a possible tree: yours on the left and Li Chen's on the right. The selected trees are highlighted. There are two common nodes.
You want to determine whether your subtrees have at least one common vertex. Luckily, your friend Andrew knows both labelings of the tree. You can ask Andrew at most 5 questions, each of which is in one of the following two forms:
* A x: Andrew will look at vertex x in your labeling and tell you the number of this vertex in Li Chen's labeling.
* B y: Andrew will look at vertex y in Li Chen's labeling and tell you the number of this vertex in your labeling.
Determine whether the two subtrees have at least one common vertex after asking some questions. If there is at least one common vertex, determine one of your labels for any of the common vertices.
Interaction
Each test consists of several test cases.
The first line of input contains a single integer t (1 ≤ t ≤ 100) — the number of test cases.
For each testcase, your program should interact in the following format.
The first line contains a single integer n (1 ≤ n ≤ 1 000) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers a_i and b_i (1≤ a_i, b_i≤ n) — the edges of the tree, indicating an edge between node a_i and b_i according to your labeling of the nodes.
The next line contains a single integer k_1 (1 ≤ k_1 ≤ n) — the number of nodes in your subtree.
The next line contains k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n) — the indices of the nodes in your subtree, according to your labeling. It is guaranteed that these vertices form a subtree.
The next line contains a single integer k_2 (1 ≤ k_2 ≤ n) — the number of nodes in Li Chen's subtree.
The next line contains k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n) — the indices (according to Li Chen's labeling) of the nodes in Li Chen's subtree. It is guaranteed that these vertices form a subtree according to Li Chen's labelling of the tree's nodes.
Test cases will be provided one by one, so you must complete interacting with the previous test (i.e. by printing out a common node or -1 if there is not such node) to start receiving the next one.
You can ask the Andrew two different types of questions.
* You can print "A x" (1 ≤ x ≤ n). Andrew will look at vertex x in your labeling and respond to you with the number of this vertex in Li Chen's labeling.
* You can print "B y" (1 ≤ y ≤ n). Andrew will look at vertex y in Li Chen's labeling and respond to you with the number of this vertex in your labeling.
You may only ask at most 5 questions per tree.
When you are ready to answer, print "C s", where s is your label of a vertex that is common to both subtrees, or -1, if no such vertex exists. Printing the answer does not count as a question. Remember to flush your answer to start receiving the next test case.
After printing a question do not forget to print end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* see documentation for other languages.
If the judge responds with -1, it means that you asked more queries than allowed, or asked an invalid query. Your program should immediately terminate (for example, by calling exit(0)). You will receive Wrong Answer; it means that you asked more queries than allowed, or asked an invalid query. If you ignore this, you can get other verdicts since your program will continue to read from a closed stream.
Hack Format
To hack, use the following format. Note that you can only hack with one test case.
The first line should contain a single integer t (t=1).
The second line should contain a single integer n (1 ≤ n ≤ 1 000).
The third line should contain n integers p_1, p_2, …, p_n (1≤ p_i≤ n) — a permutation of 1 to n. This encodes the labels that Li Chen chose for his tree. In particular, Li Chen chose label p_i for the node you labeled i.
Each of the next n-1 lines should contain two integers a_i and b_i (1≤ a_i, b_i≤ n). These edges should form a tree.
The next line should contain a single integer k_1 (1 ≤ k_1 ≤ n).
The next line should contain k_1 distinct integers x_1,x_2,…,x_{k_1} (1 ≤ x_i ≤ n). These vertices should form a subtree.
The next line should contain a single integer k_2 (1 ≤ k_2 ≤ n).
The next line should contain k_2 distinct integers y_1, y_2, …, y_{k_2} (1 ≤ y_i ≤ n). These vertices should form a subtree in Li Chen's tree according to the permutation above.
Examples
Input
1
3
1 2
2 3
1
1
1
2
2
1
Output
A 1
B 2
C 1
Input
2
6
1 2
1 3
1 4
4 5
4 6
4
1 3 4 5
3
3 5 2
3
6
1 2
1 3
1 4
4 5
4 6
3
1 2 3
3
4 1 6
5
Output
B 2
C 1
A 1
C -1
Note
For the first sample, Li Chen's hidden permutation is [2, 3, 1], and for the second, his hidden permutation is [5, 3, 2, 4, 1, 6] for both cases.
In the first sample, there is a tree with three nodes in a line. On the top, is how you labeled the tree and the subtree you chose, and the bottom is how Li Chen labeled the tree and the subtree he chose:
<image>
In the first question, you ask Andrew to look at node 1 in your labelling and tell you the label of it in Li Chen's labelling. Andrew responds with 2. At this point, you know that both of your subtrees contain the same node (i.e. node 1 according to your labeling), so you can output "C 1" and finish. However, you can also ask Andrew to look at node 2 in Li Chen's labelling and tell you the label of it in your labelling. Andrew responds with 1 (this step was given with the only reason — to show you how to ask questions).
For the second sample, there are two test cases. The first looks is the one from the statement:
<image>
We first ask "B 2", and Andrew will tell us 3. In this case, we know 3 is a common vertex, and moreover, any subtree with size 3 that contains node 3 must contain node 1 as well, so we can output either "C 1" or "C 3" as our answer.
In the second case in the second sample, the situation looks as follows:
<image>
In this case, you know that the only subtree of size 3 that doesn't contain node 1 is subtree 4,5,6. You ask Andrew for the label of node 1 in Li Chen's labelling and Andrew says 5. In this case, you know that Li Chen's subtree doesn't contain node 1, so his subtree must be consist of the nodes 4,5,6 (in your labelling), thus the two subtrees have no common nodes.
Submitted Solution:
```
import sys
from collections import deque
t=int(sys.stdin.readline())
for i in range(t):
n=int(sys.stdin.readline())#node
EDGE=[list(map(int,sys.stdin.readline().split())) for i in range(n-1)]
k1=int(sys.stdin.readline())
X=list(map(int,sys.stdin.readline().split()))
k2=int(sys.stdin.readline())
Y=list(map(int,sys.stdin.readline().split()))
print("B",Y[0],flush=True)
yans=int(input())
if yans in X:
print("C",yans,flush=True)
else:
QUE=deque([yans])
EDGELIST=[[] for i in range(n+1)]
for i,j in EDGE:
EDGELIST[i].append(j)
EDGELIST[j].append(i)
checked=[0]*(n+1)
XLIST=[0]*(n+1)
for x in X:
XLIST[x]=1
while QUE:
now=QUE.pop()
checked[now]=1
for ver in EDGELIST[now]:
if checked[ver]==1:
continue
else:
QUE.append(ver)
if XLIST[ver]==1:
break
print("A",ver,flush=True)
if int(input()) in Y:
print("C",ver,flush=True)
else:
print("C",-1,flush=True)
``` | instruction | 0 | 77,574 | 13 | 155,148 |
No | output | 1 | 77,574 | 13 | 155,149 |
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,673 | 13 | 155,346 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
from sys import stdin, stdout
import math
graph = []
lca = []
depth = []
lim = 0
def build_lca(cur, p):
global lca
global depth
global lim
global graph
stack = []
stack.append((cur,p))
while stack:
cur,p = stack.pop()
lca[cur][0] = p
depth[cur] = depth[p] + 1
for i in range(1, lim):
lca[cur][i] = lca[lca[cur][i-1]][i-1]
for i in graph[cur]:
if i == p:
continue
stack.append((i,cur))
def get_lca(a,b):
global lim
global graph
global lca
global depth
lg = 0
if depth[a] > depth[b]:
a,b = b,a
for i in range(lim,-1,-1):
if depth[lca[b][i]] >= depth[a]:
b = lca[b][i]
lg += int(pow(2,i))
if b == a:
return lg
for i in range(lim,-1,-1):
if lca[b][i] != lca[a][i]:
b = lca[b][i]
a = lca[a][i]
lg += int(pow(2,i+1))
return lg +2
def main():
global graph
global lca
global depth
global lim
n = int(stdin.readline())
lim =int(math.log(n,2))+1
graph = [set() for _ in range(n+1)]
lca = [[0 for _ in range(lim+1)] for _ in range(n+1)]
depth = [0 for _ in range(n+1)]
for _ in range (n-1):
a,b = list(map(int, stdin.readline().split()))
graph[a].add(b)
graph[b].add(a)
build_lca(1,0)
q = int(stdin.readline())
for _ in range(q):
x,y,a,b,k = list(map(int, stdin.readline().split()))
ans = -1
temp = get_lca(a,b)
if temp % 2 == k % 2 and k >= temp:
stdout.write("YES\n")
continue
temp = min(get_lca(x,a) + get_lca(y,b), get_lca(x,b) + get_lca(y,a)) + 1
if temp % 2 == k % 2 and k >= temp:
stdout.write("YES\n")
continue
stdout.write("NO\n")
main()
``` | output | 1 | 77,673 | 13 | 155,347 |
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,674 | 13 | 155,348 |
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 = [1]+[None]*(2*N-2)
F = [None, 0] + [None]*(N-1)
stack = []
for u in G[1]:
stack += [-1, u]
visited = set([1])
depth = [None]+[0]*(N)
path = [1]
ii = 0
while stack:
v = stack.pop()
ii += 1
if v > 0:
visited.add(v)
parent = path[-1]
path.append(v)
F[v], S[ii] = ii, v
depth[v] = depth[parent] + 1
for u in G[v]:
if u in visited:
continue
stack += [-v, u]
else:
child = path.pop()
S[ii] = -v
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[abs(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 += 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 >>= 1; b >>= 1
def query(u, v):
fu = F[u]; fv = F[v]
if fu > fv:
fu, fv = fv, fu
return abs(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,674 | 13 | 155,349 |
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,675 | 13 | 155,350 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct 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)]
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()
a-=1
b-=1
x-=1
y-=1
if L.depth[a]+L.depth[b]-2*L.depth[L(a,b)]<=k and (L.depth[a]+L.depth[b]-2*L.depth[L(a,b)])%2==k%2:
out("YES")
elif L.depth[a]+L.depth[x]-2*L.depth[L(a,x)] + L.depth[b]+L.depth[y]-2*L.depth[L(b,y)] + 1<=k and (L.depth[a]+L.depth[x]-2*L.depth[L(a,x)] + L.depth[b]+L.depth[y]-2*L.depth[L(b,y)] + 1)%2==k%2:
out("YES")
elif L.depth[a]+L.depth[y]-2*L.depth[L(a,y)] + L.depth[b]+L.depth[x]-2*L.depth[L(b,x)] + 1 <=k and (L.depth[a]+L.depth[y]-2*L.depth[L(a,y)] + L.depth[b]+L.depth[x]-2*L.depth[L(b,x)] + 1)%2==k%2:
out("YES")
else:
out("NO")
``` | output | 1 | 77,675 | 13 | 155,351 |
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,676 | 13 | 155,352 |
Tags: data structures, dfs and similar, shortest paths, trees
Correct Solution:
```
import sys
x = 150000
sys.setrecursionlimit(x)
def go():
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)
stack = [0]
lev[0]=0
parent[0]=0
while stack:
v = stack.pop()
for u in e[v]:
if parent[u] == -1:
lev[u] = lev[v]+1
parent[u] = v
stack.append(u)
# dfs(0, 0, 0)
levmx = max(lev)
bindep = levmx.bit_length()
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)]
ans=[]
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])
dab = dist(a, b)
if dab <= k and (dab - k) % 2 == 0:
ans.append('YES')
else:
# dxy = dist(x, y)
dax = dist(a, x)
dby = dist(b, y)
if dax + 1 + dby <= k and \
(k- (dax + 1 + dby))%2==0:
ans.append ('YES')
else:
day = dist(a, y)
dbx = dist(b, x)
if dbx + 1 + day <= k and \
(k- (dbx + 1 + day))%2==0:
ans.append ('YES')
else:
ans.append('NO')
print('\n'.join(ans))
go()
``` | output | 1 | 77,676 | 13 | 155,353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.