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.
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.
Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that:
* all b_i are positive;
* the value of the expression ∑ _{i = 1}^{m} w_i b_i is the lowest possible.
It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists.
Input
The first line contains two integers n and m (2 ≤ n ≤ 18; 0 ≤ m ≤ (n(n - 1))/(2)).
Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 ≤ x_i, y_i ≤ n, 1 ≤ w_i ≤ 10^5, x_i ≠ y_i) — the description of the i-th arc.
It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices.
Output
Print n integers a_1, a_2, ..., a_n (0 ≤ a_v ≤ 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression ∑ _{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 ≤ a_v ≤ 10^9.
Examples
Input
3 2
2 1 4
1 3 2
Output
1 2 0
Input
5 4
1 2 1
2 3 1
1 3 6
4 5 8
Output
43 42 41 1337 1336
Input
5 5
1 2 1
2 3 1
3 4 1
1 5 1
5 4 10
Output
4 3 2 1 2
Submitted Solution:
```
n, m = map(int, input().split())
D = [0]*(n+1)
def cD(n):
if type(D[n]) == int:
return D[n]
else:
result = D[n]()
D[n] = result
return result
def cD_(n):
return cD(n)
def wrap(k):
if type(k) == int:
return lambda : k
else:
return k
c = 0
for _ in range(m):
x, y, w = map(int, input().split())
p = D[x]
D[x] = (lambda k, q: (lambda : max(cD_(k) + 1, wrap(q)())))(y, p)
for _ in range(n+1):
cD(_)
print(' '.join(str(x) for x in D[1:]))
``` | instruction | 0 | 15,271 | 13 | 30,542 |
No | output | 1 | 15,271 | 13 | 30,543 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i.
Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that:
* all b_i are positive;
* the value of the expression ∑ _{i = 1}^{m} w_i b_i is the lowest possible.
It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists.
Input
The first line contains two integers n and m (2 ≤ n ≤ 18; 0 ≤ m ≤ (n(n - 1))/(2)).
Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 ≤ x_i, y_i ≤ n, 1 ≤ w_i ≤ 10^5, x_i ≠ y_i) — the description of the i-th arc.
It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices.
Output
Print n integers a_1, a_2, ..., a_n (0 ≤ a_v ≤ 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression ∑ _{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 ≤ a_v ≤ 10^9.
Examples
Input
3 2
2 1 4
1 3 2
Output
1 2 0
Input
5 4
1 2 1
2 3 1
1 3 6
4 5 8
Output
43 42 41 1337 1336
Input
5 5
1 2 1
2 3 1
3 4 1
1 5 1
5 4 10
Output
4 3 2 1 2
Submitted Solution:
```
n, m = map(int, input().split())
adj = [[] for i in range(n)]
radj = [[] for i in range(n)]
out = [0] * n
inc = [0] * n
diff = [0] * n
for _ in range(m):
u, v, w = map(int, input().split())
u-=1;v-=1
adj[u].append((v,w))
out[u] += v
diff[u] += w
diff[v] -= w
inc[v] += 1
radj[v].append((u,w))
found = [0] * n
topo = []
stack = [i for i in range(n) if inc[i] == 0]
while stack:
nex = stack.pop()
topo.append(nex)
for v, _ in adj[nex]:
found[v] += 1
if inc[v] == found[v]:
stack.append(v)
best = [-1] * n
bestV = 10 ** 9
out = [n+1] * n
for v in topo:
tol = n
for u, _ in radj[v]:
tol = min(out[u], tol)
out[v] = tol - 1
import itertools
things = [(0,1)]*n
for tup in itertools.product(*things):
#tup = list(map(int, '111101010011001110'))
copy = out[::]
for v in topo[::-1]:
if tup[v] and len(adj[v]) > 0:
smol = 0
for u, _ in adj[v]:
smol = max(copy[u], smol)
copy[v] = smol + 1
curr = 0
for i in range(n):
curr += copy[i] * diff[i]
#print(copy, curr)
if curr < bestV:
bestV = curr
best = copy
out = [n+1] * n
for v in topo[::-1]:
tol = 0
for u, _ in adj[v]:
tol = max(out[u], tol)
out[v] = tol + 1
import itertools
things = [(0,1)]*n
for tup in itertools.product(*things):
copy = out[::]
for v in topo:
if tup[v] and len(radj[v]) > 0:
smol = n + 5
for u, _ in radj[v]:
smol = min(copy[u], smol)
copy[v] = smol - 1
curr = 0
for i in range(n):
curr += copy[i] * diff[i]
#print(copy, curr)
if curr < bestV:
bestV = curr
best = copy
print(' '.join(map(str,best)))
``` | instruction | 0 | 15,272 | 13 | 30,544 |
No | output | 1 | 15,272 | 13 | 30,545 |
Provide tags and a correct Python 3 solution for this coding contest problem.
A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices.
A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T.
You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation:
1. Select the subtree of the given tree that includes the vertex with number 1.
2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree.
Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero.
Input
The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree.
The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109).
Output
Print the minimum number of operations needed to solve the task.
Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier.
Examples
Input
3
1 2
1 3
1 -1 1
Output
3 | instruction | 0 | 15,373 | 13 | 30,746 |
Tags: dfs and similar, dp, greedy, trees
Correct Solution:
```
import sys
def minp():
return sys.stdin.readline().strip()
n = int(minp())
e = [0]
p = [None]*(n+1)
for i in range(n):
e.append([])
for i in range(n-1):
a, b = map(int,minp().split())
e[a].append(b)
e[b].append(a)
v = list(map(int,minp().split()))
plus = [0]*(n+1)
minus = [0]*(n+1)
was = [False]*(n+1)
was[1] = True
i = 0
j = 1
q = [0]*(n+100)
q[0] = 1
p[1] = 0
while i < j:
x = q[i]
i += 1
for y in e[x]:
if not was[y]:
was[y] = True
p[y] = x
q[j] = y
j += 1
i = j-1
while i >= 0:
x = q[i]
i -= 1
s = minus[x] - plus[x]
z = v[x-1] + s
pp = p[x]
#print(x, p[x], plus[x], minus[x], '-', s[x], v[x-1]+s[x], v[0]+s[1])
#print(-(plus[x]-minus[x]),s[x])
minus[pp] = max(minus[x],minus[pp])
plus[pp] = max(plus[x],plus[pp])
if z > 0:
plus[pp] = max(plus[pp],plus[x]+z)
elif z < 0:
minus[pp] = max(minus[pp],minus[x]-z)
#print(v[0])
#print(plus[0], minus[0])
print(plus[0] + minus[0])
``` | output | 1 | 15,373 | 13 | 30,747 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,443 | 13 | 30,886 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
def print(x):
sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = readInts()
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(0, n):
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
``` | output | 1 | 15,443 | 13 | 30,887 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,444 | 13 | 30,888 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int, input().split())
M = 10**9+7
a = list(map(int, input().split()))
g = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, input().split())
u -= 1
v -= 1
g[u].append(v)
g[v].append(u)
vis = [0]*n
def dfs(i, prev, j):
s = 1
for v in g[i]:
if 0 < a[v] - a[j] <= d or a[v] == a[j] and v > j:
if v != prev:
s += s * dfs(v, i, j) % M
return s
print(sum(dfs(i, -1, i) for i in range(n))%M)
``` | output | 1 | 15,444 | 13 | 30,889 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,445 | 13 | 30,890 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
``` | output | 1 | 15,445 | 13 | 30,891 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,446 | 13 | 30,892 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
f = lambda: map(int, input().split())
m = 1000000007
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
p[u - 1].append(v - 1)
p[v - 1].append(u - 1)
def g(u, x, y):
s = 1
for v in p[u]:
if 0 < t[v] - t[y] <= d or t[v] == t[y] and v > y:
if v != x: s += s * g(v, u, y) % m
return s
print(sum(g(y, -1, y) for y in range(n)) % m)
``` | output | 1 | 15,446 | 13 | 30,893 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,447 | 13 | 30,894 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
def dfs(nomer,mas,tyt_yge_bili,f,nach):
f[nomer] = 1;
tyt_yge_bili[nomer] = True
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if ((a[j-1] >= a[nach-1]) and (a[j-1] <= a[nach-1] + d)) and ((a[j-1] != a[nach-1]) or (j >= nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
``` | output | 1 | 15,447 | 13 | 30,895 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,448 | 13 | 30,896 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
def print(x):
sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = [0] + readInts()
adj: list = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = readInts()
adj[u].append(v)
adj[v].append(u)
vis = [False for _ in range(n + 1)]
f = [0 for _ in range(n + 1)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(1, n + 1):
vis = [False for _ in range(n + 1)]
f = [0 for _ in range(n + 1)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
``` | output | 1 | 15,448 | 13 | 30,897 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,449 | 13 | 30,898 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if ((a[j-1] >= a[nach-1]) and (a[j-1] <= a[nach-1] + d)) and ((a[j-1] != a[nach-1]) or (j >= nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez = (rez + f[z]) % MOD
print(rez)
``` | output | 1 | 15,449 | 13 | 30,899 |
Provide tags and a correct Python 3 solution for this coding contest problem.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition. | instruction | 0 | 15,450 | 13 | 30,900 |
Tags: dfs and similar, dp, math, trees
Correct Solution:
```
import sys
def readInts(): return [int(x) for x in sys.stdin.readline().split()]
def readInt(): return int(sys.stdin.readline())
# def print(x):
# sys.stdout.write(str(x) + '\n')
def solve():
MOD = int(1e9 + 7)
d, n = readInts()
a = readInts()
adj: list = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = readInts()
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
def dfs(cur, root):
vis[cur] = True
f[cur] = 1
for neigh in adj[cur]:
if vis[neigh]:
continue
if not (a[root] <= a[neigh] <= a[root] + d):
continue
if a[neigh] == a[root] and neigh < root:
continue
dfs(neigh, root)
f[cur] *= f[neigh] + 1
f[cur] %= MOD
ans = 0
for i in range(0, n):
vis = [False for _ in range(n)]
f = [0 for _ in range(n)]
dfs(i, i)
ans += f[i]
ans %= MOD
print(ans)
def main():
t = 1
# t = readInt()
for _ in range(t):
solve()
main()
``` | output | 1 | 15,450 | 13 | 30,901 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
f = lambda: map(int, input().split())
m = 1000000007
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
u -= 1
v -= 1
p[u].append(v)
p[v].append(u)
def g(u, x, a, b, q):
k = 1
for v in p[u]:
if a < t[v] <= b or t[v] == a and v > q:
if v != x: k += k * g(v, u, a, b, q) % m
return k
s = 0
for q in range(n):
a = t[q]
b = a + d
s += g(q, -1, a, b, q)
print(s % m)
``` | instruction | 0 | 15,451 | 13 | 30,902 |
Yes | output | 1 | 15,451 | 13 | 30,903 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
mod=10**9+7
d,n=map(int,input().split())
a=[0]+list(map(int,input().split()))
tree=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=map(int,input().split())
tree[u].append(v)
tree[v].append(u)
def dfs(u,root):
visited[u]=True
f[u]=1
for i in tree[u]:
if visited[i]==False:
if a[i]<a[root] or a[i]>a[root]+d:continue
if a[i]==a[root] and i<root: continue
dfs(i,root)
f[u]=(f[u]*(f[i]+1))%(mod)
ans=0
for i in range(1,n+1):
visited = [False] * (n+1)
f = [0] * (n+1)
dfs(i,i)
ans=(ans+f[i])%mod
print(ans)
``` | instruction | 0 | 15,452 | 13 | 30,904 |
Yes | output | 1 | 15,452 | 13 | 30,905 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
if nomer not in tyt_yge_bili:
tyt_yge_bili.append(nomer)
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if j not in tyt_yge_bili:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = [0 for _ in range(n+1)]
tyt_yge_bili = []
dfs(z,mas,tyt_yge_bili,f , z)
rez += f[z]
print(rez)
``` | instruction | 0 | 15,453 | 13 | 30,906 |
No | output | 1 | 15,453 | 13 | 30,907 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
from bisect import bisect
print( bisect([1,3,7],4))
``` | instruction | 0 | 15,454 | 13 | 30,908 |
No | output | 1 | 15,454 | 13 | 30,909 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
f = lambda: map(int, input().split())
d, n = f()
t = list(f())
p = [[] for i in range(n)]
for j in range(n - 1):
u, v = f()
u -= 1
v -= 1
p[u].append(v)
p[v].append(u)
def g(u, x, a, b, q):
k = 1
for v in p[u]:
if a < t[v] <= b or t[v] == a and v > q:
if v != x: k *= g(v, u, a, b, q)
return k + 1
s = 0
for q in range(n):
a = t[q]
b = a + d
s += g(q, -1, a, b, q)
print(s - n)
``` | instruction | 0 | 15,455 | 13 | 30,910 |
No | output | 1 | 15,455 | 13 | 30,911 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
As you know, an undirected connected graph with n nodes and n - 1 edges is called a tree. You are given an integer d and a tree consisting of n nodes. Each node i has a value ai associated with it.
We call a set S of tree nodes valid if following conditions are satisfied:
1. S is non-empty.
2. S is connected. In other words, if nodes u and v are in S, then all nodes lying on the simple path between u and v should also be presented in S.
3. <image>.
Your task is to count the number of valid sets. Since the result can be very large, you must print its remainder modulo 1000000007 (109 + 7).
Input
The first line contains two space-separated integers d (0 ≤ d ≤ 2000) and n (1 ≤ n ≤ 2000).
The second line contains n space-separated positive integers a1, a2, ..., an(1 ≤ ai ≤ 2000).
Then the next n - 1 line each contain pair of integers u and v (1 ≤ u, v ≤ n) denoting that there is an edge between u and v. It is guaranteed that these edges form a tree.
Output
Print the number of valid sets modulo 1000000007.
Examples
Input
1 4
2 1 3 2
1 2
1 3
3 4
Output
8
Input
0 3
1 2 3
1 2
2 3
Output
3
Input
4 8
7 8 7 5 4 6 4 10
1 6
1 2
5 8
1 3
3 5
6 7
3 4
Output
41
Note
In the first sample, there are exactly 8 valid sets: {1}, {2}, {3}, {4}, {1, 2}, {1, 3}, {3, 4} and {1, 3, 4}. Set {1, 2, 3, 4} is not valid, because the third condition isn't satisfied. Set {1, 4} satisfies the third condition, but conflicts with the second condition.
Submitted Solution:
```
d, n = map(int,input().split())
a = list(map(int, input().split()))
mas = [[] for _ in range(n+1)]
MOD = 1000000007
for _ in range(n-1):
u, v = map(int,input().split())
mas[u].append(v)
mas[v].append(u)
# #mas = [[],[2,3,10],[1,6,7],[1],[7],[9],[2],[2,4,11],[9],[5,8,10],[1,9,12],[7],[10]]
# mas = [[],[2,3],[1],[1,4],[3]]
# a = [0,2,1,3,2]
# d = 1
# print('mas:',mas)
# print('a:',a)
k = 0
def dfs(nomer,mas,tyt_yge_bili,f,nach):
global k
f[nomer] = 1;
# print(nomer ,"--", nach)
tyt_yge_bili[nomer] = True
# f.append(a[nomer-1])
# # print(f)
# if max(f)-min(f)<=d:
# k+=1
# print(f)
for j in mas[nomer]:
if tyt_yge_bili[j]!=True:
if not ((a[j-1] < a[nach-1]) or (a[j-1] > a[nach-1] + d)) and not ((a[j-1] == a[nach-1]) and (j < nach)):
dfs(j,mas,tyt_yge_bili,f,nach)
# print(a[j-1],a[nach-1])
f[nomer] = (f[nomer] * (f[j] + 1)) % MOD
rez = 0
for z in range(1,n+1):
f = []
tyt_yge_bili = []
for _ in range(n+1):
f.append(0)
tyt_yge_bili.append(0)
dfs(z,mas,tyt_yge_bili,f , z)
rez += f[z] % MOD
print(rez)
``` | instruction | 0 | 15,456 | 13 | 30,912 |
No | output | 1 | 15,456 | 13 | 30,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).
Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.
In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:
1. eat the apples, if the node is a leaf.
2. move the apples to one of the children, if the node is non-leaf.
Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.
Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.
Input
The first line will contain one integer n (2 ≤ n ≤ 105) — the number of nodes in the apple tree.
The second line will contain n integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the number of apples on each node of the tree.
The third line will contain n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n) — the parent of each node of the tree. Node i has parent pi (for 2 ≤ i ≤ n). Node 1 is the root of the tree.
It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
Output
On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.
Examples
Input
3
2 2 3
1 1
Output
1
Input
3
1 2 3
1 1
Output
0
Input
8
7 2 2 5 4 3 1 1
1 1 1 4 4 5 6
Output
4
Note
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.
In the second sample, There is no swap that will make Sagheer win the game.
Note that Sagheer must make the swap even if he can win with the initial tree. | instruction | 0 | 15,614 | 13 | 31,228 |
Tags: games, trees
Correct Solution:
```
n= int(input())
a = [int(_) for _ in input().split()]
c = [int(_) for _ in input().split()]
depth = [0] * (n)
for i in range(1,n):
depth[i] = depth[c[i-1]-1] + 1
MAX = max(depth)
t = 0
store = {}
todo = []
p = 0
for i in range(n):
if (MAX-depth[i]) % 2 == 0: # odd, useful
t ^= a[i]
todo.append(a[i])
else:
store[a[i]] = store.get(a[i],0) + 1
p += 1
ans = 0
for i in todo:
ans += store.get(i^t,0)
if t == 0:
ans += (p*(p-1)//2) + (n-p)*(n-p-1)//2
print(ans)
``` | output | 1 | 15,614 | 13 | 31,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Sagheer is playing a game with his best friend Soliman. He brought a tree with n nodes numbered from 1 to n and rooted at node 1. The i-th node has ai apples. This tree has a special property: the lengths of all paths from the root to any leaf have the same parity (i.e. all paths have even length or all paths have odd length).
Sagheer and Soliman will take turns to play. Soliman will make the first move. The player who can't make a move loses.
In each move, the current player will pick a single node, take a non-empty subset of apples from it and do one of the following two things:
1. eat the apples, if the node is a leaf.
2. move the apples to one of the children, if the node is non-leaf.
Before Soliman comes to start playing, Sagheer will make exactly one change to the tree. He will pick two different nodes u and v and swap the apples of u with the apples of v.
Can you help Sagheer count the number of ways to make the swap (i.e. to choose u and v) after which he will win the game if both players play optimally? (u, v) and (v, u) are considered to be the same pair.
Input
The first line will contain one integer n (2 ≤ n ≤ 105) — the number of nodes in the apple tree.
The second line will contain n integers a1, a2, ..., an (1 ≤ ai ≤ 107) — the number of apples on each node of the tree.
The third line will contain n - 1 integers p2, p3, ..., pn (1 ≤ pi ≤ n) — the parent of each node of the tree. Node i has parent pi (for 2 ≤ i ≤ n). Node 1 is the root of the tree.
It is guaranteed that the input describes a valid tree, and the lengths of all paths from the root to any leaf will have the same parity.
Output
On a single line, print the number of different pairs of nodes (u, v), u ≠ v such that if they start playing after swapping the apples of both nodes, Sagheer will win the game. (u, v) and (v, u) are considered to be the same pair.
Examples
Input
3
2 2 3
1 1
Output
1
Input
3
1 2 3
1 1
Output
0
Input
8
7 2 2 5 4 3 1 1
1 1 1 4 4 5 6
Output
4
Note
In the first sample, Sagheer can only win if he swapped node 1 with node 3. In this case, both leaves will have 2 apples. If Soliman makes a move in a leaf node, Sagheer can make the same move in the other leaf. If Soliman moved some apples from a root to a leaf, Sagheer will eat those moved apples. Eventually, Soliman will not find a move.
In the second sample, There is no swap that will make Sagheer win the game.
Note that Sagheer must make the swap even if he can win with the initial tree. | instruction | 0 | 15,615 | 13 | 31,230 |
Tags: games, trees
Correct Solution:
```
def coloring(i, ancestors, color):
while i != 0 and color[ancestors[i - 1]] is None:
color[ancestors[i - 1]] = not color[i]
i = ancestors[i - 1]
def main():
n = int(input())
a = list(map(int, input().split()))
ancestors = list(map(lambda x: int(x) - 1, input().split()))
descendants = [[] for i in range(n)]
for i in range(n - 1):
descendants[ancestors[i]].append(i + 1)
color = [None for i in range(n)]
for i in range(n):
if not descendants[i]:
color[i] = True
coloring(i, ancestors, color)
reds = 0
blues = 0
xor = 0
count_red = dict()
count_blue = dict()
for i in range(n):
if color[i]:
blues += 1
xor ^= a[i]
if str(a[i]) in count_blue:
count_blue[str(a[i])] += 1
else:
count_blue[str(a[i])] = 1
else:
reds += 1
if str(a[i]) in count_red:
count_red[str(a[i])] += 1
else:
count_red[str(a[i])] = 1
res = 0
if xor == 0:
res += (blues - 1) * blues // 2
res += (reds - 1) * reds // 2
for i in count_blue.items():
if i[0] in count_red:
res += i[1] * count_red[i[0]]
else:
for i in count_blue.items():
if str(xor ^ int(i[0])) in count_red:
res += i[1] * count_red[str(xor ^ int(i[0]))]
print(res)
main()
``` | output | 1 | 15,615 | 13 | 31,231 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an strictly convex polygon with n vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once.
More specifically your path can be represented as some sequence of distinct polygon vertices. Your path is the straight line segments between adjacent vertices in order. These segments are not allowed to touch or intersect each other except at the vertices in your sequence.
Given the polygon, print the maximum length non-intersecting path that visits each point at most once.
Input
The first line of input will contain a single integer n (2 ≤ n ≤ 2 500), the number of points.
The next n lines will contain two integers xi, yi (|xi|, |yi| ≤ 109), denoting the coordinates of the i-th vertex.
It is guaranteed that these points are listed in clockwise order.
Output
Print a single floating point number, representing the longest non-intersecting path that visits the vertices at most once.
Your answer will be accepted if it has absolute or relative error at most 10 - 9. More specifically, if your answer is a and the jury answer is b, your answer will be accepted if <image>.
Example
Input
4
0 0
0 1
1 1
1 0
Output
3.4142135624
Note
One optimal path is to visit points 0,1,3,2 in order.
Submitted Solution:
```
import math
n = int(input())
vertices = [x for x in range(n - 1)]
vertices.insert(n // 2, n - 1)
xpos, ypos = [], []
for x in range(n):
a, b = map(int, input().split())
xpos.append(a)
ypos.append(b)
d = 0
for x in range(1, n):
p, q = vertices[x - 1], vertices[x]
x1, y1, x2, y2 = xpos[p], ypos[p], xpos[q], ypos[q]
d += math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
print(d)
``` | instruction | 0 | 15,616 | 13 | 31,232 |
No | output | 1 | 15,616 | 13 | 31,233 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an strictly convex polygon with n vertices. It is guaranteed that no three points are collinear. You would like to take a maximum non intersecting path on the polygon vertices that visits each point at most once.
More specifically your path can be represented as some sequence of distinct polygon vertices. Your path is the straight line segments between adjacent vertices in order. These segments are not allowed to touch or intersect each other except at the vertices in your sequence.
Given the polygon, print the maximum length non-intersecting path that visits each point at most once.
Input
The first line of input will contain a single integer n (2 ≤ n ≤ 2 500), the number of points.
The next n lines will contain two integers xi, yi (|xi|, |yi| ≤ 109), denoting the coordinates of the i-th vertex.
It is guaranteed that these points are listed in clockwise order.
Output
Print a single floating point number, representing the longest non-intersecting path that visits the vertices at most once.
Your answer will be accepted if it has absolute or relative error at most 10 - 9. More specifically, if your answer is a and the jury answer is b, your answer will be accepted if <image>.
Example
Input
4
0 0
0 1
1 1
1 0
Output
3.4142135624
Note
One optimal path is to visit points 0,1,3,2 in order.
Submitted Solution:
```
import math
n = int(input())
vertices = []
p = 0
for x in range(n):
q = x
if x % 2 == 0:
q = n - x
p += q
p %= n
vertices.append(p)
xpos, ypos = [], []
for x in range(n):
a, b = map(int, input().split())
xpos.append(a)
ypos.append(b)
d = 0
for x in range(1, n):
p, q = vertices[x - 1], vertices[x]
x1, y1, x2, y2 = xpos[p], ypos[p], xpos[q], ypos[q]
d += math.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2)
print(d)
``` | instruction | 0 | 15,617 | 13 | 31,234 |
No | output | 1 | 15,617 | 13 | 31,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.
In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.
Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.
<image> In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue.
It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above):
* main grid is a top tree, whose wires are directed 'from the top to the down',
* reserve grid is a lower tree, whose wires are directed 'from the down to the top',
* devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right,
* wires between nodes do not intersect.
Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, ..., n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).
Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
Input
The first line contains an integer n (1 ≤ n ≤ 1000) — the number of devices in the palace.
The next line contains an integer a (1 + n ≤ a ≤ 1000 + n) — the amount of nodes in the main grid.
Next line contains a - 1 integers p_i (1 ≤ p_i ≤ a). Each integer p_i means that the main grid contains a wire from p_i-th node to (i + 1)-th.
The next line contains n integers x_i (1 ≤ x_i ≤ a) — the number of a node in the main grid that is connected to the i-th device.
The next line contains an integer b (1 + n ≤ b ≤ 1000 + n) — the amount of nodes in the reserve grid.
Next line contains b - 1 integers q_i (1 ≤ q_i ≤ b). Each integer q_i means that the reserve grid contains a wire from q_i-th node to (i + 1)-th.
The next line contains n integers y_i (1 ≤ y_i ≤ b) — the number of a node in the reserve grid that is connected to the i-th device.
It is guaranteed that each grid is a tree, which has exactly n leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node 1, that visits leaves in order of connection to devices.
Output
Print a single integer — the maximal amount of wires that can be cut so that each device is powered.
Examples
Input
3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
Output
5
Input
4
6
4 4 1 1 1
3 2 6 5
6
6 6 1 1 1
5 4 3 2
Output
6
Input
5
14
1 1 11 2 14 14 13 7 12 2 5 6 1
9 8 3 10 4
16
1 1 9 9 2 5 10 1 14 3 7 11 6 12 2
8 16 13 4 15
Output
17
Note
For the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red):
<image>
The second and the third examples can be seen below:
<image>
Submitted Solution:
```
from heapq import heappush, heappop
class MinCostFlow:
INF = float("inf")
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
G = self.G
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [0]*N
while f:
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (w, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
dist[w] = r = dist[v] + cost + H[v] - H[w]
prv_v[w] = v; prv_e[w] = i
heappush(que, (r, w))
if dist[t] == INF:
return -1
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
import sys
input = sys.stdin.readline
def solve():
n = int(input())
a = int(input())
ps = list(map(int, input().split()))
xs = list(map(int, input().split()))
b = int(input())
qs = list(map(int, input().split()))
ys = list(map(int, input().split()))
MCF = MinCostFlow(a+b+n)
for i, p in enumerate(ps):
MCF.add_edge(p-1, i+1, 1, 1)
for i, x in enumerate(xs):
MCF.add_edge(x-1, a+i, 1, 0)
MCF.add_edge(a+i, a+n, 1, 0)
for i, q in enumerate(qs):
fr = a+n+q-1 if q != 1 else 0
MCF.add_edge(fr, a+n+i+1, 1, 1)
for i, y in enumerate(ys):
fr = a+n+y-1 if y != 1 else 0
MCF.add_edge(fr, a+i, 1, 0)
ans = MCF.flow(0, a+n, n)
#ans -= 2*n
ans = a-1+b-1-ans
print(ans)
solve()
``` | instruction | 0 | 16,062 | 13 | 32,124 |
No | output | 1 | 16,062 | 13 | 32,125 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.
In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.
Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.
<image> In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue.
It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above):
* main grid is a top tree, whose wires are directed 'from the top to the down',
* reserve grid is a lower tree, whose wires are directed 'from the down to the top',
* devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right,
* wires between nodes do not intersect.
Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, ..., n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).
Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
Input
The first line contains an integer n (1 ≤ n ≤ 1000) — the number of devices in the palace.
The next line contains an integer a (1 + n ≤ a ≤ 1000 + n) — the amount of nodes in the main grid.
Next line contains a - 1 integers p_i (1 ≤ p_i ≤ a). Each integer p_i means that the main grid contains a wire from p_i-th node to (i + 1)-th.
The next line contains n integers x_i (1 ≤ x_i ≤ a) — the number of a node in the main grid that is connected to the i-th device.
The next line contains an integer b (1 + n ≤ b ≤ 1000 + n) — the amount of nodes in the reserve grid.
Next line contains b - 1 integers q_i (1 ≤ q_i ≤ b). Each integer q_i means that the reserve grid contains a wire from q_i-th node to (i + 1)-th.
The next line contains n integers y_i (1 ≤ y_i ≤ b) — the number of a node in the reserve grid that is connected to the i-th device.
It is guaranteed that each grid is a tree, which has exactly n leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node 1, that visits leaves in order of connection to devices.
Output
Print a single integer — the maximal amount of wires that can be cut so that each device is powered.
Examples
Input
3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
Output
5
Input
4
6
4 4 1 1 1
3 2 6 5
6
6 6 1 1 1
5 4 3 2
Output
6
Input
5
14
1 1 11 2 14 14 13 7 12 2 5 6 1
9 8 3 10 4
16
1 1 9 9 2 5 10 1 14 3 7 11 6 12 2
8 16 13 4 15
Output
17
Note
For the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red):
<image>
The second and the third examples can be seen below:
<image>
Submitted Solution:
```
from heapq import heappush, heappop
class MinCostFlow:
INF = float("inf")
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
G = self.G
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [0]*N
while f:
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (w, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
dist[w] = r = dist[v] + cost + H[v] - H[w]
prv_v[w] = v; prv_e[w] = i
heappush(que, (r, w))
if dist[t] == INF:
return -1
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
import sys
input = sys.stdin.readline
def solve():
n = int(input())
a = int(input())
ps = list(map(int, input().split()))
xs = list(map(int, input().split()))
b = int(input())
qs = list(map(int, input().split()))
ys = list(map(int, input().split()))
MCF = MinCostFlow(a+b+n)
for i, p in enumerate(ps):
MCF.add_edge(p-1, i+1, 1, 1)
for i, x in enumerate(xs):
MCF.add_edge(x-1, a+i, 1, 1)
MCF.add_edge(a+i, a+n, 1, 1)
for i, q in enumerate(qs):
fr = a+n+q-1 if q != 1 else 0
MCF.add_edge(fr, a+n+i+1, 1, 1)
for i, y in enumerate(ys):
fr = a+n+y-1 if y != 1 else 0
MCF.add_edge(fr, a+i, 1, 1)
ans = MCF.flow(0, a+n, n)
ans -= 2*n
ans = a-1+b-1-ans
print(ans)
solve()
``` | instruction | 0 | 16,063 | 13 | 32,126 |
No | output | 1 | 16,063 | 13 | 32,127 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.
In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.
Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.
<image> In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue.
It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above):
* main grid is a top tree, whose wires are directed 'from the top to the down',
* reserve grid is a lower tree, whose wires are directed 'from the down to the top',
* devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right,
* wires between nodes do not intersect.
Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, ..., n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).
Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
Input
The first line contains an integer n (1 ≤ n ≤ 1000) — the number of devices in the palace.
The next line contains an integer a (1 + n ≤ a ≤ 1000 + n) — the amount of nodes in the main grid.
Next line contains a - 1 integers p_i (1 ≤ p_i ≤ a). Each integer p_i means that the main grid contains a wire from p_i-th node to (i + 1)-th.
The next line contains n integers x_i (1 ≤ x_i ≤ a) — the number of a node in the main grid that is connected to the i-th device.
The next line contains an integer b (1 + n ≤ b ≤ 1000 + n) — the amount of nodes in the reserve grid.
Next line contains b - 1 integers q_i (1 ≤ q_i ≤ b). Each integer q_i means that the reserve grid contains a wire from q_i-th node to (i + 1)-th.
The next line contains n integers y_i (1 ≤ y_i ≤ b) — the number of a node in the reserve grid that is connected to the i-th device.
It is guaranteed that each grid is a tree, which has exactly n leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node 1, that visits leaves in order of connection to devices.
Output
Print a single integer — the maximal amount of wires that can be cut so that each device is powered.
Examples
Input
3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
Output
5
Input
4
6
4 4 1 1 1
3 2 6 5
6
6 6 1 1 1
5 4 3 2
Output
6
Input
5
14
1 1 11 2 14 14 13 7 12 2 5 6 1
9 8 3 10 4
16
1 1 9 9 2 5 10 1 14 3 7 11 6 12 2
8 16 13 4 15
Output
17
Note
For the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red):
<image>
The second and the third examples can be seen below:
<image>
Submitted Solution:
```
from heapq import heappush, heappop
class MinCostFlow:
INF = 10**18
def __init__(self, N):
self.N = N
self.G = [[] for i in range(N)]
def add_edge(self, fr, to, cap, cost):
G = self.G
G[fr].append([to, cap, cost, len(G[to])])
G[to].append([fr, 0, -cost, len(G[fr])-1])
def flow(self, s, t, f):
N = self.N; G = self.G
INF = MinCostFlow.INF
res = 0
H = [0]*N
prv_v = [0]*N
prv_e = [0]*N
while f:
dist = [INF]*N
dist[s] = 0
que = [(0, s)]
while que:
c, v = heappop(que)
if dist[v] < c:
continue
for i, (w, cap, cost, _) in enumerate(G[v]):
if cap > 0 and dist[w] > dist[v] + cost + H[v] - H[w]:
dist[w] = r = dist[v] + cost + H[v] - H[w]
prv_v[w] = v; prv_e[w] = i
heappush(que, (r, w))
if dist[t] == INF:
return -1
for i in range(N):
H[i] += dist[i]
d = f; v = t
while v != s:
d = min(d, G[prv_v[v]][prv_e[v]][1])
v = prv_v[v]
f -= d
res += d * H[t]
v = t
while v != s:
e = G[prv_v[v]][prv_e[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prv_v[v]
return res
import sys
input = sys.stdin.readline
def solve():
n = int(input())
a = int(input())
ps = list(map(int, input().split()))
xs = list(map(int, input().split()))
b = int(input())
qs = list(map(int, input().split()))
ys = list(map(int, input().split()))
MCF = MinCostFlow(a+b+n)
for i, p in enumerate(ps):
MCF.add_edge(p-1, i+1, 1, 1)
for i, x in enumerate(xs):
MCF.add_edge(x-1, a+i, 1, 1)
MCF.add_edge(a+i, a+n, 1, 1)
for i, q in enumerate(qs):
fr = a+n+q-1 if q != 1 else 0
MCF.add_edge(fr, a+n+i+1, 1, 1)
for i, y in enumerate(ys):
fr = a+n+y-1 if y != 1 else 0
MCF.add_edge(fr, a+i, 1, 1)
ans = MCF.flow(0, a+n, n)
ans -= 2*n
ans = a-1+b-1-ans
print(ans)
solve()
``` | instruction | 0 | 16,064 | 13 | 32,128 |
No | output | 1 | 16,064 | 13 | 32,129 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
An electrical grid in Berland palaces consists of 2 grids: main and reserve. Wires in palaces are made of expensive material, so selling some of them would be a good idea!
Each grid (main and reserve) has a head node (its number is 1). Every other node gets electricity from the head node. Each node can be reached from the head node by a unique path. Also, both grids have exactly n nodes, which do not spread electricity further.
In other words, every grid is a rooted directed tree on n leaves with a root in the node, which number is 1. Each tree has independent enumeration and nodes from one grid are not connected with nodes of another grid.
Also, the palace has n electrical devices. Each device is connected with one node of the main grid and with one node of the reserve grid. Devices connect only with nodes, from which electricity is not spread further (these nodes are the tree's leaves). Each grid's leaf is connected with exactly one device.
<image> In this example the main grid contains 6 nodes (the top tree) and the reserve grid contains 4 nodes (the lower tree). There are 3 devices with numbers colored in blue.
It is guaranteed that the whole grid (two grids and n devices) can be shown in this way (like in the picture above):
* main grid is a top tree, whose wires are directed 'from the top to the down',
* reserve grid is a lower tree, whose wires are directed 'from the down to the top',
* devices — horizontal row between two grids, which are numbered from 1 to n from the left to the right,
* wires between nodes do not intersect.
Formally, for each tree exists a depth-first search from the node with number 1, that visits leaves in order of connection to devices 1, 2, ..., n (firstly, the node, that is connected to the device 1, then the node, that is connected to the device 2, etc.).
Businessman wants to sell (remove) maximal amount of wires so that each device will be powered from at least one grid (main or reserve). In other words, for each device should exist at least one path to the head node (in the main grid or the reserve grid), which contains only nodes from one grid.
Input
The first line contains an integer n (1 ≤ n ≤ 1000) — the number of devices in the palace.
The next line contains an integer a (1 + n ≤ a ≤ 1000 + n) — the amount of nodes in the main grid.
Next line contains a - 1 integers p_i (1 ≤ p_i ≤ a). Each integer p_i means that the main grid contains a wire from p_i-th node to (i + 1)-th.
The next line contains n integers x_i (1 ≤ x_i ≤ a) — the number of a node in the main grid that is connected to the i-th device.
The next line contains an integer b (1 + n ≤ b ≤ 1000 + n) — the amount of nodes in the reserve grid.
Next line contains b - 1 integers q_i (1 ≤ q_i ≤ b). Each integer q_i means that the reserve grid contains a wire from q_i-th node to (i + 1)-th.
The next line contains n integers y_i (1 ≤ y_i ≤ b) — the number of a node in the reserve grid that is connected to the i-th device.
It is guaranteed that each grid is a tree, which has exactly n leaves and each leaf is connected with one device. Also, it is guaranteed, that for each tree exists a depth-first search from the node 1, that visits leaves in order of connection to devices.
Output
Print a single integer — the maximal amount of wires that can be cut so that each device is powered.
Examples
Input
3
6
4 1 1 4 2
6 5 3
4
1 1 1
3 4 2
Output
5
Input
4
6
4 4 1 1 1
3 2 6 5
6
6 6 1 1 1
5 4 3 2
Output
6
Input
5
14
1 1 11 2 14 14 13 7 12 2 5 6 1
9 8 3 10 4
16
1 1 9 9 2 5 10 1 14 3 7 11 6 12 2
8 16 13 4 15
Output
17
Note
For the first example, the picture below shows one of the possible solutions (wires that can be removed are marked in red):
<image>
The second and the third examples can be seen below:
<image>
Submitted Solution:
```
from heapq import heappush, heappop
class MinCostFlow:
def __init__(self, n):
self.n = n
self.G = [[] for i in range(n)]
def add_edge(self, f, t, cap, cost):
self.G[f].append([t, cap, cost, len(self.G[t])])
self.G[t].append([f, 0, -cost, len(self.G[f])-1])
def flow(self, s, t, f):
n = self.n
G = self.G
prevv = [0]*n; preve = [0]*n
INF = 10**9+7
res = 0
while f:
dist = [INF]*n
dist[s] = 0
update = 1
while update:
update = 0
for v in range(n):
if dist[v] == INF:
continue
gv = G[v]
for i in range(len(gv)):
to, cap, cost, rev = gv[i]
if cap > 0 and dist[v] + cost < dist[to]:
dist[to] = dist[v] + cost
prevv[to] = v; preve[to] = i
update = 1
if dist[t] == INF:
return -1
d = f; v = t
while v != s:
d = min(d, G[prevv[v]][preve[v]][1])
v = prevv[v]
f -= d
res += d * dist[t]
v = t
while v != s:
e = G[prevv[v]][preve[v]]
e[1] -= d
G[v][e[3]][1] += d
v = prevv[v]
return res
import sys
input = sys.stdin.readline
def solve():
n = int(input())
a = int(input())
ps = list(map(int, input().split()))
xs = list(map(int, input().split()))
b = int(input())
qs = list(map(int, input().split()))
ys = list(map(int, input().split()))
MCF = MinCostFlow(a+b+n)
for i, p in enumerate(ps):
MCF.add_edge(p-1, i+1, 1, 1)
for i, x in enumerate(xs):
MCF.add_edge(x-1, a+i, 1, 1)
MCF.add_edge(a+i, a+n, 1, 1)
for i, q in enumerate(qs):
fr = a+n+q-1 if q != 1 else 0
MCF.add_edge(fr, a+n+i+1, 1, 1)
for i, y in enumerate(ys):
fr = a+n+y-1 if y != 1 else 0
MCF.add_edge(fr, a+i, 1, 1)
ans = MCF.flow(0, a+n, n)
ans -= 2*n
ans = a-1+b-1-ans
print(ans)
solve()
``` | instruction | 0 | 16,065 | 13 | 32,130 |
No | output | 1 | 16,065 | 13 | 32,131 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,098 | 13 | 32,196 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
from typing import List, Tuple, TypeVar, Generic, Sequence, Union # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
def main():
n, m = map(int, input().split())
adj = [[] for _ in range(n)]
for u, v in (map(int, input().split()) for _ in range(n - 1)):
adj[u - 1].append(v - 1)
adj[v - 1].append(u - 1)
time = 0
tin, tout, depth, par = [-1] * n, [-1] * n, [0] * n, [0] * n
ei = [0] * n
stack = [0]
while stack:
v = stack.pop()
time += 1
if tin[v] == -1:
tin[v] = time
for i, dest in enumerate(adj[v][ei[v]:], start=ei[v]):
if par[v] == dest:
continue
par[dest] = v
depth[dest] = depth[v] + 1
ei[v] = i + 1
stack.append(v)
stack.append(dest)
break
else:
tout[v] = time
ans = ['NO'] * m
for i, (_, *vertices) in enumerate(tuple(map(lambda x: int(x) - 1, input().split())) for _ in range(m)):
v = max(vertices, key=lambda x: depth[x])
if all(tin[par[u]] <= tin[v] <= tout[par[u]] for u in vertices):
ans[i] = 'YES'
sys.stdout.buffer.write('\n'.join(ans).encode('utf-8'))
if __name__ == '__main__':
main()
``` | output | 1 | 16,098 | 13 | 32,197 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,099 | 13 | 32,198 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys, math,os
from io import BytesIO, IOBase
# 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 mdata(): return list(map(int, data().split()))
#sys.setrecursionlimit(100000 + 1)
#INF = float('inf')
mod = 998244353
# from decimal import Decimal
from types import GeneratorType
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
data = lambda: sys.stdin.readline().rstrip("\r\n")
# endregion
T = [0]
def main():
@bootstrap
def dfs(T, par, val, tin, tout, x, p=-1, cnt=0):
tin[x] = T[0]
val[x] = cnt
T[0] += 1
for i in g[x]:
if i != p:
yield (dfs(T, par, val, tin, tout, i, x, cnt + 1))
par[x] = p
tout[x] = T[0]
T[0] += 1
yield
n, m = mdata()
g = [set() for i in range(n)]
for i in range(n - 1):
a, b = mdata()
g[a - 1].add(b - 1)
g[b - 1].add(a - 1)
tin = [0] * n
tout = [0] * n
par = [0] * n
val = [0] * n
dfs(T, par, val, tin, tout, 0)
for i in range(m):
l = list(mdata())
flag = True
max1 = 0
ind = 0
for j in l[1:]:
if val[j - 1] > max1:
max1 = val[j - 1]
ind = j - 1
for j in l[1:]:
if j - 1 != ind and j != 1:
if tin[par[j - 1]] < tin[ind] and tout[par[j - 1]] > tout[ind]:
continue
flag = False
break
if flag == True:
print("YES")
else:
print("NO")
if __name__ == "__main__":
main()
``` | output | 1 | 16,099 | 13 | 32,199 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,100 | 13 | 32,200 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
from collections import Counter
def input(): return sys.stdin.readline().strip()
def list2d(a, b, c): return [[c] * b for i in range(a)]
def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)]
def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)]
def ceil(x, y=1): return int(-(-x // y))
def INT(): return int(input())
def MAP(): return map(int, input().split())
def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)]
def Yes(): print('Yes')
def No(): print('No')
def YES(): print('YES')
def NO(): print('NO')
INF = 10 ** 18
MOD = 10 ** 9 + 7
class LCA:
def __init__(self, nodes, root):
self.N = len(nodes)
nv = 1
MAX = 0
while nv < N:
nv *= 2
MAX += 1
self.MAX = MAX
self.nxt = list2d(MAX, N, -1)
self.depths = self.dfs(N, nodes, root)
for k in range(1, MAX):
for v in range(N):
if self.nxt[k-1][v] == -1:
continue
self.nxt[k][v] = self.nxt[k-1][self.nxt[k-1][v]]
def dfs(self, N, nodes, src):
stack = [(src, -1, 0)]
dist = [INF] * N
while stack:
u, prev, c = stack.pop()
dist[u] = c
self.nxt[0][u] = prev
for v in nodes[u]:
if v != prev:
stack.append((v, u, c+1))
return dist
def get_lca(self, a, b):
if self.depths[a] > self.depths[b]:
a, b = b, a
gap = self.depths[b] - self.depths[a]
for i in range(self.MAX):
if gap & 1<<i:
b = self.nxt[i][b]
if a == b:
return a
else:
for i in range(self.MAX-1, -1, -1):
a2 = self.nxt[i][a]
b2 = self.nxt[i][b]
if a2 != b2:
a = a2
b = b2
return self.nxt[0][a]
N, Q = MAP()
nodes = [[] for i in range(N)]
for _ in range(N-1):
a, b = MAP()
a -= 1; b -= 1
nodes[a].append(b)
nodes[b].append(a)
lca = LCA(nodes, 0)
for _ in range(Q):
li = [v-1 for v in LIST()[1:]]
u = mx = -1
for v in li:
if lca.depths[v] > mx:
mx = lca.depths[v]
u = v
mx = -1
for v in li:
l = lca.get_lca(u, v)
dist = lca.depths[v] - lca.depths[l]
mx = max(mx, dist)
if mx <= 1:
YES()
else:
NO()
``` | output | 1 | 16,100 | 13 | 32,201 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,101 | 13 | 32,202 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
def bfs(s):
q = deque()
q.append(s)
dist = [-1] * (n + 1)
dist[s] = 0
parent = [-1] * (n + 1)
while q:
i = q.popleft()
d = dist[i] + 1
for j in G[i]:
if dist[j] == -1:
dist[j] = d
q.append(j)
parent[j] = i
return dist, parent
n, m = map(int, input().split())
G = [[] for _ in range(n + 1)]
for _ in range(n - 1):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
dist, parent = bfs(1)
dp = []
dp0 = list(parent)
ok = 1
while ok:
ok = 0
dp1 = [-1] * (n + 1)
for i in range(1, n + 1):
if dp0[i] ^ -1:
dp1[i] = dp0[dp0[i]]
if dp1[i] ^ -1:
ok = 1
dp.append(dp0)
dp0 = dp1
for _ in range(m):
v = list(map(int, input().split()))
md = -1
u = []
for i in range(1, len(v)):
vi = v[i]
if vi == 1:
continue
p = parent[vi]
u.append(p)
if md < dist[p]:
md = dist[p]
s = p
ans = "YES"
for i in u:
di = dist[i]
d = md - di
j, p = 0, 1
t = s
while d:
if d & p:
t = dp[j][t]
d -= p
j += 1
p *= 2
if i ^ t:
ans = "NO"
break
print(ans)
``` | output | 1 | 16,101 | 13 | 32,203 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,102 | 13 | 32,204 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from sys import stdin, stdout
tree = []
parent = []
go_in = []
go_out = []
d = []
def main():
global tree
global parent
global go_in
global go_out
global d
n,k = list(map(int, stdin.readline().split()))
tree = [[] for _ in range(n+1)]
parent = [0] * (n+1)
go_in = [0] * (n+1)
go_out = [0] * (n+1)
d = [0] * (n+1)
for _ in range (n-1):
a,b = list(map(int, stdin.readline().split()))
tree[a].append(b)
tree[b].append(a)
stack = []
stack.append(1)
parent[1] = 1
d[1] = 1
while stack:
x = stack.pop()
for y in tree[x]:
if parent[y] == 0:
parent[y] = x
d[y] = d[x] + 1
stack.append(y)
stack = []
stack.append(1)
kk = 1
while stack:
x = stack[-1]
if go_in[x] == 0:
go_in[x] = kk
kk += 1
is_another = False
while tree[x]:
y = tree[x].pop()
if go_in[y] == 0:
stack.append(y)
is_another = True
break
if is_another:
continue
go_out[x] = kk
kk += 1
stack.pop()
for _ in range (k):
branch = 1
mx = -1
arr = list(map(int, stdin.readline().split()))
is_ok = True
for i in range(1,len(arr)):
if d[arr[i]] > mx:
mx = d[arr[i]]
branch = parent[arr[i]]
for i in range(1,len(arr)):
cur = parent[arr[i]]
if (go_in[branch] <= go_in[cur] and go_out[branch] >= go_out[cur]) or (go_in[branch] >= go_in[cur] and go_out[branch] <= go_out[cur]):
continue
is_ok = False
stdout.write("NO\n")
break
if is_ok:
stdout.write("YES\n")
main()
``` | output | 1 | 16,102 | 13 | 32,205 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,103 | 13 | 32,206 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def main():
n,m=readIntArr()
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
parent=[-1 for _ in range(n+1)]
start=[0 for _ in range(n+1)]
end=[0 for _ in range(n+1)]
depths=[0 for _ in range(n+1)]
time=[0]
@bootstrap
def dfs(node,p,d):
depths[node]=d
parent[node]=p
start[node]=time[0]
time[0]+=1
for nex in adj[node]:
if nex!=p:
yield dfs(nex,node,d+1)
end[node]=time[0]
yield None
dfs(1,-1,0)
ans=[]
for _ in range(m):
q=readIntArr()[1:]
nodeWithMaxDepth=q[0]
for node in q:
if depths[node]>depths[nodeWithMaxDepth]:
nodeWithMaxDepth=node
#check that every node's parent is an ancestor of the node with max depth
deepestNodeStart=start[nodeWithMaxDepth]
deepestNodeEnd=end[nodeWithMaxDepth]
ok=True
for node in q:
if node!=1:
node=parent[node]
nodeStart=start[node]
nodeEnd=end[node]
if nodeStart<=deepestNodeStart and nodeEnd>=deepestNodeEnd: #is parent
pass
else: #not parent
ok=False
break
if ok:
ans.append('YES')
else:
ans.append('NO')
multiLineArrayPrint(ans)
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
``` | output | 1 | 16,103 | 13 | 32,207 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,104 | 13 | 32,208 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import defaultdict
from collections import deque
from enum import Enum
"""
Because it asks for node within distance 1.
We can consider parent of the given node.
After that, we've to find whether if there is a node which is child node of every other node in the given list.
If no such node exits, there won't be a path.
"""
nodes, queries = map(int, input().split())
graph = defaultdict(list)
height = [0] * (nodes+1)
in_time = [0] * (nodes+1)
out_time= [0] * (nodes+1)
parent = [1] * (nodes+1)
class Color(Enum):
WHITE = 0
GRAY = 1
BLACK = 2
color = [Color.WHITE] * (nodes+1)
for _ in range(1, nodes):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
#recursive implementation causing stack-overflow possibly
"""
def dfs(curr_node, parent, depth):
parent_dict[curr_node] = parent
height[curr_node] = depth
global time
in_time[curr_node] = time
time += 1
for child in graph[curr_node]:
if child == parent:
continue
dfs(child, curr_node, depth+1)
out_time[curr_node] = time
time += 1
dfs(1, 1, 0)
"""
#non-recursive implementation
def dfs(root):
stack = deque()
time = 0
stack.append(root)
while stack:
node = stack.pop()
if color[node] == Color.WHITE:
time += 1
in_time[node] = time
color[node] = Color.GRAY
stack.append(node)
for neighbor in graph[node]:
if color[neighbor] == Color.WHITE:
height[neighbor] = height[node] + 1
parent[neighbor] = node
stack.append(neighbor)
elif color[node] == Color.GRAY:
time += 1
out_time[node] = time
color[node] = Color.BLACK
dfs(1)
def is_ancestor(high, low):
'''returns True if high is ancestor of low'''
return in_time[high] <= in_time[low] and out_time[low] <= out_time[high]
for _ in range(queries):
a = list(map(int, input().split()))[1:]
parents = set()
max_node = a[0]
for node in a:
if height[max_node] < height[node]:
max_node = node
for node in a:
if node == max_node:
continue
if parent[node] not in parents:
parents.add(parent[node])
ok = True
for node in parents:
if not is_ancestor(node, max_node):
ok = False
break
print("YES") if ok else print("NO")
``` | output | 1 | 16,104 | 13 | 32,209 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u. | instruction | 0 | 16,105 | 13 | 32,210 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
EDGELIST=[[] for i in range(n+1)]
for i in range(n-1):
x,y=map(int,input().split())
EDGELIST[x].append(y)
EDGELIST[y].append(x)
DEPTH=[-1]*(n+1)
DEPTH[1]=0
from collections import deque
QUE = deque([1])
QUE2 = deque()
EULER=[]
USED=[0]*(n+1)
P=[-1]*(n+1)
P[1]=1
while QUE:
x=QUE.pop()
EULER.append((DEPTH[x],x))
if USED[x]==1:
continue
for to in EDGELIST[x]:
if USED[to]==0:
DEPTH[to]=DEPTH[x]+1
P[to]=x
QUE2.append(to)
else:
QUE.append(to)
QUE.extend(QUE2)
QUE2=deque()
USED[x]=1
MINP=[1<<30]*(n+1)
MAXP=[-1]*(n+1)
for ind,(depth,p) in enumerate(EULER):
MINP[p]=min(MINP[p],ind)
MAXP[p]=max(MAXP[p],ind)
LEN=len(EULER)
seg_el=1<<(LEN.bit_length())
SEG=[(1<<30,0)]*(2*seg_el)
for i in range(LEN):
SEG[i+seg_el]=EULER[i]
for i in range(seg_el-1,0,-1):
SEG[i]=min(SEG[i*2],SEG[i*2+1])
def update(n,x,seg_el):
i=n+seg_el
SEG[i]=x
i>>=1
while i!=0:
SEG[i]=min(SEG[i*2],SEG[i*2+1])
i>>=1
def getvalues(l,r):
L=l+seg_el
R=r+seg_el
ANS=(1<<30,0)
while L<R:
if L & 1:
ANS=min(ANS , SEG[L])
L+=1
if R & 1:
R-=1
ANS=min(ANS , SEG[R])
L>>=1
R>>=1
return ANS
def LCA(l,r):
return getvalues(min(MINP[l],MINP[r]),max(MAXP[l],MAXP[r])+1)
for i in range(m):
A=list(map(int,input().split()))[1:]
M=max(A,key=lambda x:DEPTH[x])
for a in A:
if LCA(M,P[a])[1]==P[a]:
continue
else:
sys.stdout.write("NO\n")
break
else:
sys.stdout.write("YES\n")
``` | output | 1 | 16,105 | 13 | 32,211 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
# ===============================================================================================
# some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
#discrete binary search
#minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
#maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##to find factorial and ncr
# N=100000
# mod = 10**9 +7
# fac = [1, 1]
# finv = [1, 1]
# inv = [0, 1]
#
# for i in range(2, N + 1):
# fac.append((fac[-1] * i) % mod)
# inv.append(mod - (inv[mod % i] * (mod // i) % mod))
# finv.append(finv[-1] * inv[-1] % mod)
#
#
# def comb(n, r):
# if n < r:
# return 0
# else:
# return fac[n] * (finv[r] * finv[n - r] % mod) % mod
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
sys.setrecursionlimit(200005)
timer = 0
def solve():
n,m=sep()
graph=[[] for _ in range(n)]
for _ in range(n-1):
a,b=sep()
a-=1
b-=1
graph[a].append(b)
graph[b].append(a)
l = n.bit_length()
up = [[0] * (l+1) for _ in range(n)]
tin = [0] * n
tout = [0] * n
@iterative
def dfs(i, p):
global timer
timer += 1
tin[i] = timer
up[i][0] = p
for j in range(1, l + 1):
up[i][j] = up[up[i][j - 1]][j - 1]
for c in graph[i]:
if c == p:
continue
yield dfs(c, i)
timer += 1
tout[i] = timer
yield
def is_ancestor(a, b):
return tin[a] <= tin[b] and tout[a] >= tout[b]
def lca(u, v):
if is_ancestor(u, v):
return u
if is_ancestor(v, u):
return v
for i in range(l, -1, -1):
if not is_ancestor(up[u][i], v):
u = up[u][i]
return up[u][0]
parent=[0]*n
distance=[0]*n
@iterative
def dfs1(i,p,d):
# print(i,p,d)
distance[i]=d
parent[i]=p
for c in graph[i]:
if c==p:
continue
yield dfs1(c,i,d+1)
yield
dfs1(0,0,0)
dfs(0,0)
# print(parent)
# print(distance)
# print(tin)
# print(tout)
# print(up)
for _ in range(m):
temp=lis()
ma=-1
# print(_)
for i in range(1,len(temp)):
temp[i]-=1
# print(temp[i],distance[temp[i]])
if distance[temp[i]]>ma:
ma=distance[temp[i]]
mat=temp[i]
u=mat
# print(u)
f=0
for i in range(1,len(temp)):
v=temp[i]
anc=lca(u,v)
# print(anc,u,v)
if anc!=v and anc!=parent[v]:
print("NO")
f=1
break
if f==0:
print("YES")
solve()
#testcase(int(inp()))
``` | instruction | 0 | 16,106 | 13 | 32,212 |
Yes | output | 1 | 16,106 | 13 | 32,213 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
def DFS(graph,root,parent):
dist = [-1]*(n+1)
dist[root] = 0
stack = [root]
while stack:
x = stack.pop()
for y in graph[x]:
if dist[y] == -1:
parent[y] = x
dist[y] = dist[x]+1
stack.append(y)
return dist
#親のリスト、頂点v、kが与えられたときに「vのk個上の祖先」を見る
class Doubling:
def __init__(self,graph,root):
self.root = root
n = len(graph)-1
self.ancestor_ls = [[0]*(n+1)]
self.distance = DFS(graph,root,self.ancestor_ls[0])
self.bitn = n.bit_length()
for i in range(1,self.bitn+1):
ancestor_ls_app = [0]*(n+1)
for j in range(1,n+1):
ancestor_ls_app[j] = self.ancestor_ls[i-1][self.ancestor_ls[i-1][j]]
self.ancestor_ls.append(ancestor_ls_app)
def dist(self):
return self.distance
def parent(self):
return self.ancestor_ls[0]
def ancestor(self,v,depth):
if depth == 0:
return v
if n<depth:
return self.root
ret = v
for i in range(self.bitn):
if depth&1<<i:
ret = self.ancestor_ls[i][ret]
return ret
def LCA(self,u,v):
if self.distance[u]<self.distance[v]:
u,v = v,u
dif = self.distance[u]-self.distance[v]
w = self.ancestor(u,dif)
if w == v:
return v
for i in range(self.bitn,-1,-1):
if self.ancestor_ls[i][w] != self.ancestor_ls[i][v]:
w,v = self.ancestor_ls[i][w],self.ancestor_ls[i][v]
return self.ancestor_ls[0][v]
import sys
input = sys.stdin.readline
n,m = map(int,input().split())
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
for a,b in ab:
graph[a].append(b)
graph[b].append(a)
sol = Doubling(graph,1)
par = sol.parent()
d = sol.dist()
for _ in range(m):
k,*ls = map(int,input().split())
dmax = 0
dmind = 0
for i in range(k):
ls[i] = par[ls[i]]
if d[ls[i]] >= dmax:
dmax = d[ls[i]]
dmind = ls[i]
flg = 1
for i in range(k):
if sol.LCA(dmind,ls[i]) != ls[i]:
flg = 0
break
if flg:
print("YES")
else:
print("NO")
``` | instruction | 0 | 16,107 | 13 | 32,214 |
Yes | output | 1 | 16,107 | 13 | 32,215 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
import time
#start_time = time.time()
#def TIME_(): print(time.time()-start_time)
import os, sys
from io import BytesIO, IOBase
from types import GeneratorType
from bisect import bisect_left, bisect_right
from collections import defaultdict as dd, deque as dq, Counter as dc
import math, string, heapq as h
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
import os
self.os = os
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
self.os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
def getInt(): return int(input())
def getStrs(): return input().split()
def getInts(): return list(map(int,input().split()))
def getStr(): return input()
def listStr(): return list(input())
def getMat(n): return [getInts() for _ in range(n)]
def getBin(): return list(map(int,list(input())))
def isInt(s): return '0' <= s[0] <= '9'
def ceil_(a,b): return a//b + (a%b > 0)
"""
For each query we're going to have to go as far as the deepest node(s), so the question is do all the other nodes lie close enough?
Every other node must be a direct ancestor, or the child of a direct ancestor.
*THE PARENT OF EVERY NODE MUST LIE IN A STRAIGHT LINE*
"""
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
N, M = getInts()
G = [[] for _ in range(N)]
for _ in range(N-1):
U, V = getInts()
U -= 1
V -= 1
G[U].append(V)
G[V].append(U)
used = [0]*N
parent = [-1]*N
tin = [0]*N
tout = [0]*N
depth = [0]*N
global curr
curr = 1
@bootstrap
def dfs(node):
global curr
tin[node] = curr
curr += 1
for neigh in G[node]:
if neigh != parent[node]:
parent[neigh] = node
depth[neigh] = depth[node] + 1
yield dfs(neigh)
tout[node] = curr
curr += 1
yield
dfs(0)
def path_(u,v):
return (tin[u] <= tin[v] and tout[v] <= tout[u]) or (tin[v] <= tin[u] and tout[u] <= tout[v])
for m in range(M):
K, *V = getInts()
V = sorted(list(set([(depth[parent[v-1]],parent[v-1]) for v in V if v != 1])))
for i in range(len(V)-1):
if not path_(V[i+1][1],V[i][1]):
print("NO")
break
else:
print("YES")
#TIME_()
``` | instruction | 0 | 16,108 | 13 | 32,216 |
Yes | output | 1 | 16,108 | 13 | 32,217 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
import sys
input = sys.stdin.readline
N, Q = map(int, input().split())
G = [set() for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
G[a].add(b)
G[b].add(a)
S = [None]*(2*N-1)
F = [None]*(N+1)
stack = [1]
visited = set()
depth = [None]*(N+1)
depth[1] = 0
path = []
ii = 0
while stack:
v = stack.pop()
if v > 0:
visited.add(v)
path.append(v)
F[v], S[ii] = ii, v
ii += 1
for u in G[v]:
if u in visited:
continue
stack += [-v, u]
depth[u] = depth[v] + 1
else:
child = path.pop()
S[ii] = -v
ii += 1
INF = (N, None)
M = 2*N
M0 = 2**(M-1).bit_length()
data = [INF]*(2*M0)
for i, v in enumerate(S):
data[M0-1+i] = (depth[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, b = a + M0, b + M0
while a < b:
if b & 1:
b -= 1
yield data[b-1]
if a & 1:
yield data[a-1]
a += 1
a, b = a >> 1, b >> 1
def query(u, v):
fu, fv = F[u], F[v]
if fu > fv:
fu, fv = fv, fu
return abs(S[min(_query(fu, fv+1))[1]])
def dist(x, y):
c = query(x, y)
return depth[x] + depth[y] - 2*depth[c]
for _ in range(Q):
X = list(map(int, input().split()))[1:]
# print(X)
x = X[0]
for y in X[1:]:
c = query(x, y)
if depth[x] < depth[y]:
u, v = x, y
else:
u, v = y, x
if depth[u] - depth[c] > 1:
print("NO")
break
x = v
else:
print("YES")
``` | instruction | 0 | 16,109 | 13 | 32,218 |
Yes | output | 1 | 16,109 | 13 | 32,219 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def main():
n,m=readIntArr()
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
parent=[-1 for _ in range(n+1)]
start=[0 for _ in range(n+1)]
end=[0 for _ in range(n+1)]
depths=[0 for _ in range(n+1)]
time=[0]
@bootstrap
def dfs(node,p,d):
depths[node]=d
parent[node]=p
start[node]=time[0]
time[0]+=1
for nex in adj[node]:
if nex!=p:
yield dfs(nex,node,d+1)
end[node]=time[0]
yield None
dfs(1,-1,0)
# print(parent)
# print(start)
# print(end)
# print(depths)
for node in range(2,n+1):
assert parent[node]!=-1
assert start[node]>0
assert end[node]>0
assert depths[node]>0
ans=[]
for _ in range(m):
q=readIntArr()
nodeWithMaxDepth=q[0]
for node in q:
if depths[node]>depths[nodeWithMaxDepth]:
nodeWithMaxDepth=node
#check that every node's parent is an ancestor of the node with max depth
deepestNodeStart=start[nodeWithMaxDepth]
deepestNodeEnd=end[nodeWithMaxDepth]
ok=True
for node in q:
if node!=1:
node=parent[node]
nodeStart=start[node]
nodeEnd=end[node]
if nodeStart<=deepestNodeStart and nodeEnd>=deepestNodeEnd: #is parent
pass
else: #not parent
ok=False
break
if ok:
ans.append('YES')
else:
ans.append('NO')
multiLineArrayPrint(ans)
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
``` | instruction | 0 | 16,110 | 13 | 32,220 |
No | output | 1 | 16,110 | 13 | 32,221 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
from sys import stdin, gettrace
from collections import deque
# if not gettrace():
# def input():
# return next(stdin)[:-1]
#
def input():
return stdin.buffer.readline()
def readTree(n):
adj = [set() for _ in range(n)]
for _ in range(n-1):
u,v = map(int, input().split())
adj[u-1].add(v-1)
adj[v-1].add(u-1)
return adj
def treeOrderByDepth(n, adj, root=0):
parent = [-2] + [-1]*(n-1)
ordered = []
q = deque()
q.append(root)
while q:
c =q.popleft()
ordered.append(c)
for a in adj[c]:
if parent[a] == -1:
parent[a] = c
q.append(a)
return (ordered, parent)
def main():
n,m = map(int, input().split())
adj = readTree(n)
ordered, parent = treeOrderByDepth(n, adj)
depth = [0] + [None] * (n-1)
for node in ordered[1:]:
depth[node] = depth[parent[node]] + 1
for _ in range(m):
solve(depth, parent)
def solve(depth, parent):
vv = [int(a)-1 for a in input().split()]
m = vv[0] + 1
vv = vv[1:]
vv.sort(key=lambda v: depth[v], reverse=True)
pos = 0
p = parent[vv[0]]
while pos < m:
cdepth = depth[vv[pos]]
while pos < m and depth[vv[pos]] == cdepth:
if parent[vv[pos]] != p:
print('NO')
return
pos += 1
p = parent[p]
print("YES")
if __name__ == "__main__":
main()
``` | instruction | 0 | 16,111 | 13 | 32,222 |
No | output | 1 | 16,111 | 13 | 32,223 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
import sys
from collections import defaultdict
T = 0
def dfs(x, par = -1, d = 1):
global T
if parent[x] != 0:
return
tin[x] = T
deg[x] = d
parent[x] = par
T += 1
for y in g[x]:
if y != par:
dfs(y,x,d+1)
tout[x] = T
T += 1
def solve(v):
global T
l,r = 0,T
for x in v:
if x != 1: x = parent[x]
l,r = max(1,tin[x]),min(r,tout[x])
return "YES" if l <= r else "NO"
n,m = map(int,input().split())
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)
tin, tout = [0]*(n+1),[0]*(n+1)
deg = [0]*(n+1)
parent = [0]*(n+1)
try:
dfs(1)
except Exception as e:
print(str(e))
for _ in range(m):
v = list(map(int,input().split()))[1:]
print(solve(v))
``` | instruction | 0 | 16,112 | 13 | 32,224 |
No | output | 1 | 16,112 | 13 | 32,225 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree consisting of n vertices numbered from 1 to n. The root of the tree is a vertex number 1.
A tree is a connected undirected graph with n-1 edges.
You are given m queries. The i-th query consists of the set of k_i distinct vertices v_i[1], v_i[2], ..., v_i[k_i]. Your task is to say if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path.
Input
The first line of the input contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices in the tree and the number of queries.
Each of the next n-1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
The next m lines describe queries. The i-th line describes the i-th query and starts with the integer k_i (1 ≤ k_i ≤ n) — the number of vertices in the current query. Then k_i integers follow: v_i[1], v_i[2], ..., v_i[k_i] (1 ≤ v_i[j] ≤ n), where v_i[j] is the j-th vertex of the i-th query.
It is guaranteed that all vertices in a single query are distinct.
It is guaranteed that the sum of k_i does not exceed 2 ⋅ 10^5 (∑_{i=1}^{m} k_i ≤ 2 ⋅ 10^5).
Output
For each query, print the answer — "YES", if there is a path from the root to some vertex u such that each of the given k vertices is either belongs to this path or has the distance 1 to some vertex of this path and "NO" otherwise.
Example
Input
10 6
1 2
1 3
1 4
2 5
2 6
3 7
7 8
7 9
9 10
4 3 8 9 10
3 2 4 6
3 2 1 5
3 4 8 2
2 6 10
3 5 4 7
Output
YES
YES
YES
YES
NO
NO
Note
The picture corresponding to the example:
<image>
Consider the queries.
The first query is [3, 8, 9, 10]. The answer is "YES" as you can choose the path from the root 1 to the vertex u=10. Then vertices [3, 9, 10] belong to the path from 1 to 10 and the vertex 8 has distance 1 to the vertex 7 which also belongs to this path.
The second query is [2, 4, 6]. The answer is "YES" as you can choose the path to the vertex u=2. Then the vertex 4 has distance 1 to the vertex 1 which belongs to this path and the vertex 6 has distance 1 to the vertex 2 which belongs to this path.
The third query is [2, 1, 5]. The answer is "YES" as you can choose the path to the vertex u=5 and all vertices of the query belong to this path.
The fourth query is [4, 8, 2]. The answer is "YES" as you can choose the path to the vertex u=9 so vertices 2 and 4 both have distance 1 to the vertex 1 which belongs to this path and the vertex 8 has distance 1 to the vertex 7 which belongs to this path.
The fifth and the sixth queries both have answer "NO" because you cannot choose suitable vertex u.
Submitted Solution:
```
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def main():
n,m=readIntArr()
adj=[[] for _ in range(n+1)]
for _ in range(n-1):
u,v=readIntArr()
adj[u].append(v)
adj[v].append(u)
parent=[-1 for _ in range(n+1)]
start=[0 for _ in range(n+1)]
end=[0 for _ in range(n+1)]
depths=[0 for _ in range(n+1)]
time=[0]
@bootstrap
def dfs(node,p,d):
depths[node]=d
parent[node]=p
start[node]=time[0]
time[0]+=1
for nex in adj[node]:
if nex!=p:
yield dfs(nex,node,d+1)
end[node]=time[0]
yield None
dfs(1,-1,0)
# print(parent)
# print(start)
# print(end)
ans=[]
for _ in range(m):
q=readIntArr()
nodeWithMaxDepth=q[0]
for node in q:
if depths[node]>depths[nodeWithMaxDepth]:
nodeWithMaxDepth=node
#check that every node's parent is an ancestor of the node with max depth
deepestNodeStart=start[nodeWithMaxDepth]
deepestNodeEnd=end[nodeWithMaxDepth]
ok=True
for node in q:
if node!=1:
node=parent[node]
nodeStart=start[node]
nodeEnd=end[node]
if nodeStart<=deepestNodeStart and nodeEnd>=deepestNodeEnd: #is parent
pass
else: #not parent
ok=False
break
if ok:
ans.append('YES')
else:
ans.append('NO')
multiLineArrayPrint(ans)
return
#import sys
#input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok)
import sys
input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS.
def oneLineArrayPrint(arr):
print(' '.join([str(x) for x in arr]))
def multiLineArrayPrint(arr):
print('\n'.join([str(x) for x in arr]))
def multiLineArrayOfArraysPrint(arr):
print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))
def readIntArr():
return [int(x) for x in input().split()]
inf=float('inf')
MOD=10**9+7
main()
``` | instruction | 0 | 16,113 | 13 | 32,226 |
No | output | 1 | 16,113 | 13 | 32,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1 | instruction | 0 | 16,283 | 13 | 32,566 |
Tags: constructive algorithms, dfs and similar, trees
Correct Solution:
```
from collections import defaultdict
class Solution:
def __init__(self):
pass
def solve_and_print(self):
tree = Tree()
parents = [None] * (tree.n+1)
parents[1] = 1
tree.set_parents(1, parents)
leaves_path = defaultdict(list)
for leaf in tree.leaves:
node = leaf
path = []
while node != 1:
path.append(node)
node = parents[node]
path.append(1)
leaves_path[leaf] = list(reversed(path))
path = tree.create_path(leaves_path)
counter = defaultdict(int)
for i in range(len(path) - 1):
counter[(min(path[i], path[i + 1]), max(path[i], path[i + 1]))] += 1
counter = counter.values()
if max(counter) == 2 and min(counter) == 2:
print(' '.join([str(i) for i in tree.create_path(leaves_path)]))
else:
print(-1)
class Tree:
def __init__(self):
self.n = int(input())
self.tree = defaultdict(list)
for _ in range(self.n-1):
u, v = [int(x) for x in input().split()]
self.tree[u].append(v)
self.tree[v].append(u)
self.leaves = [int(x) for x in input().split()]
def set_parents(self, node, parents):
for i in self.tree[node]:
if parents[i] is None:
parents[i] = node
self.set_parents(i, parents)
def create_path(self, leaves_path):
output = []
node = 0
for i in range(len(self.leaves) - 1):
leaf = self.leaves[i]
output += leaves_path[leaf][node:]
j = 0
while j < len(leaves_path[leaf]) and j < len(leaves_path[self.leaves[i + 1]]) and \
leaves_path[leaf][j] == leaves_path[self.leaves[i + 1]][j]:
j += 1
node = j - 1
output += list(reversed(leaves_path[leaf][j:-1]))
leaf = self.leaves[-1]
output += leaves_path[leaf][node:]
output += list(reversed(leaves_path[leaf][:-1]))
return output
if __name__ == "__main__":
Solution().solve_and_print()
``` | output | 1 | 16,283 | 13 | 32,567 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1 | instruction | 0 | 16,284 | 13 | 32,568 |
Tags: constructive algorithms, dfs and similar, trees
Correct Solution:
```
import sys
from array import array # noqa: F401
def input():
return sys.stdin.buffer.readline().decode('utf-8')
n = int(input())
adj = [[] for _ in range(n + 1)]
deg = [0] * (n + 1)
deg[1] = 1
for _ in range(n - 1):
u, v = map(int, input().split())
adj[u].append(v)
adj[v].append(u)
deg[u] += 1
deg[v] += 1
ks = list(map(int, input().split()))
priority = [10**9] * (n + 1)
for i, v in enumerate(ks):
priority[v] = i
stack = [v for v in range(1, n + 1) if deg[v] == 1]
while stack:
v = stack.pop()
deg[v] = 0
adj[v].sort(key=lambda i: priority[i])
for dest in adj[v]:
if deg[dest] == 0:
continue
priority[dest] = min(priority[dest], priority[v])
deg[dest] -= 1
if deg[dest] == 1:
stack.append(dest)
ks = ks[::-1]
stack = [(1, 0, -1)]
ans = []
while stack:
v, ei, par = stack.pop()
ans.append(v)
if ks and ks[-1] == v:
ks.pop()
if ei < len(adj[v]) and adj[v][ei] == par:
ei += 1
if len(adj[v]) == ei:
continue
stack.extend(((v, ei + 1, par), (adj[v][ei], 0, v)))
if not ks:
print(*ans)
else:
print(-1)
``` | output | 1 | 16,284 | 13 | 32,569 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1 | instruction | 0 | 16,285 | 13 | 32,570 |
Tags: constructive algorithms, dfs and similar, trees
Correct Solution:
```
class Node:
def __init__(self, data=None):
self.data = data
self.connections = []
self.path = []
class Tree:
def __init__(self):
self.root = None
self.nodes = {}
def addConnections(self, p, c):
if p not in self.nodes:
parent = Node(p)
self.nodes[p] = parent
else:
parent = self.nodes[p]
if c not in self.nodes:
child = Node(c)
self.nodes[c] = child
else:
child = self.nodes[c]
if p == 1:
self.root = parent
self.root.path = [1]
if c == 1:
self.root = child
self.root.path = [1]
parent.connections.append(child)
child.connections.append(parent)
def dfsWithPath(self, nodeDict):
currentNode = self.root
stack = [currentNode]
visited = []
while stack:
currentNode = stack.pop()
visited.append(currentNode.data)
stack.extend([x for x in currentNode.connections if x.data not in visited])
for node in currentNode.connections:
node.path = currentNode.path + [node.data]
nodeDict[node.data] = node.path
n = int(input())
tree = Tree()
for i in range(n - 1):
[p, c] = [int(x) for x in input().split()]
tree.addConnections(p, c)
nodeDict = {}
tree.dfsWithPath(nodeDict)
leaves = [int(x) for x in input().split()]
root = tree.root
totalPath = [root.data]
currentNode = root.data
currentNumber = root.data
currentPath = []
for leaf in leaves:
found = False
while not found:
if currentNode in nodeDict[leaf]:
found = True
totalPath = totalPath + nodeDict[leaf][nodeDict[leaf].index(currentNode) + 1:]
currentNode = leaf
currentPath = nodeDict[leaf].copy()
currentNumber = -2
else:
currentNode = currentPath[currentNumber]
totalPath.append(currentNode)
currentNumber -= 1
totalPath = totalPath + nodeDict[leaf][::-1][1:]
if len(totalPath) == 2 * n - 1:
res = ""
for i in totalPath:
res = res + str(i) + " "
print(res)
else:
print('-1')
``` | output | 1 | 16,285 | 13 | 32,571 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1 | instruction | 0 | 16,286 | 13 | 32,572 |
Tags: constructive algorithms, dfs and similar, trees
Correct Solution:
```
from collections import defaultdict
def set_parents(tree, node, parents):
for i in tree[node]:
if parents[i] is None:
parents[i] = node
set_parents(tree, i, parents)
def create_path(leaves, leaves_path):
output = []
node = 0
for i in range(len(leaves) - 1):
leave = leaves[i]
output += leaves_path[leave][node:]
j = 0
while j < len(leaves_path[leave]) and j < len(leaves_path[leaves[i + 1]]) and leaves_path[leave][j] == leaves_path[leaves[i + 1]][j]:
j += 1
node = j - 1
output += list(reversed(leaves_path[leave][j:-1]))
leave = leaves[-1]
output += leaves_path[leave][node:]
output += list(reversed(leaves_path[leave][:-1]))
return output
tree = defaultdict(list)
n = int(input())
for _ in range(n - 1):
u, v = map(int, input().split())
tree[u].append(v)
tree[v].append(u)
parents = [None] * (n + 1)
parents[1] = 1
set_parents(tree, 1, parents)
leaves = list(map(int, input().split()))
leaves_path = defaultdict(list)
for leave in leaves:
node = leave
path = []
while node != 1:
path.append(node)
node = parents[node]
path.append(1)
leaves_path[leave] = list(reversed(path))
path = create_path(leaves, leaves_path)
counter = defaultdict(int)
for i in range(len(path) - 1):
counter[(min(path[i], path[i + 1]), max(path[i], path[i + 1]))] += 1
counter = counter.values()
if max(counter) == 2 and min(counter) == 2:
print(' '.join([str(i) for i in create_path(leaves, leaves_path)]))
else:
print(-1)
``` | output | 1 | 16,286 | 13 | 32,573 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1 | instruction | 0 | 16,287 | 13 | 32,574 |
Tags: constructive algorithms, dfs and similar, trees
Correct Solution:
```
n = int(input())
adj = [[] for i in range(n)]
adj2 = [[] for i in range(n)]
for i in range(n-1):
u,v = map(int,input().split())
adj[u-1].append(v-1)
adj[v-1].append(u-1)
leaf = {}
a = list(map(int,input().split()))
for i in range(len(a)):
leaf[a[i]-1] = i
inf = 200000
def dfs1(v,frm,adj2):
if len(adj[v]) == 1 and v!=0:
return (inf if v not in leaf else leaf[v],v)
best = float("inf")
for u in adj[v]:
if u != frm:
c = dfs1(u,v,adj2)
adj2[v].append(c)
best = min(best,c[0])
return (best,v)
dfs1(0,-1,adj2)
path = []
for i in range(n):
adj2[i].sort()
#print(*adj2)
def dfs2(v,frm,path):
path.append(v+1)
for _,u in adj2[v]:
if u!=frm:
dfs2(u,v,path)
if frm!=-1:
path.append(frm+1)
dfs2(0,-1,path)
gd = []
for i in path:
if i-1 in leaf:
gd.append(i)
if gd == a:
print(*path)
else:
print(-1)
``` | output | 1 | 16,287 | 13 | 32,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1
Submitted Solution:
```
# from dust i have come, dust i will be
class graph(object):
def __init__(self,n):
self.n=n
self.adj=[list() for i in range(n+1)]
self.parent=[0]*(n+1)
self.vis=[0]*(n+1)
def insert(self,u,v):
self.adj[u].append(v)
def dfs(self,s,pr):
self.vis[s]=1
if(pr==1):
print(s,end=' ')
cnt=0
for i in range(len(self.adj[s])):
if self.vis[self.adj[s][i]]==0:
cnt+=1
self.parent[self.adj[s][i]]=s
self.dfs(self.adj[s][i],pr)
if(pr==1):
print(s,end=' ')
def reset(self):
for i in range(n+1):
self.vis[i]=0;
n=int(input())
g=graph(n)
for i in range(n-1):
u,v=map(int,input().split())
g.insert(u,v)
g.insert(v,u)
k=list(map(int,input().split()))
g.dfs(1,0)
a=g.parent
dict={}
for i in range(len(k)):
v=a[k[i]]
if v not in dict:
dict[v]=1
else:
if a[k[i]]==a[k[i-1]]:
continue
else:
print(-1)
exit(0)
g.reset()
g.dfs(1,1)
``` | instruction | 0 | 16,288 | 13 | 32,576 |
No | output | 1 | 16,288 | 13 | 32,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1
Submitted Solution:
```
#TO MAKE THE PROGRAM FAST
''' ---------------------------------------------------------------------------------------------------- '''
import sys
from collections import *
input = sys.stdin.readline
sys.setrecursionlimit(100000)
''' ---------------------------------------------------------------------------------------------------- '''
#FOR TAKING INPUTS
''' ---------------------------------------------------------------------------------------------------- '''
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def val():return int(input().rstrip('\n'))
def st():return input().rstrip('\n')
def sttoli():return [int(i) for i in input().rstrip('\n')]
''' ---------------------------------------------------------------------------------------------------- '''
def deepcopysets(root,maind,finald):
try:
finald[root] = set()
if not len(maind[root]):
finald[root].add(root)
else:
for i in maind[root]:
temp = deepcopysets(i,maind,finald)
for j in temp[i]:
finald[root].add(j)
finald[root] = sorted(list(finald[root]))
return finald
except:
print(-1)
exit()
def givearraysorted(l,helpset,kdict):
return sorted(l,key = lambda x:kdict[helpset[x][0]])
def dfs(root,arr,d,k,helpset,kdict):
try:
temp = givearraysorted(d[root],helpset,kdict)
for i in temp:
if not len(d[i]):
arr.append(root)
arr.append(i)
else:
arr.append(root)
arr = dfs(i,arr,d,k,helpset,kdict)
arr.append(root)
return arr
except:
print(-1)
exit()
#MAIN PROGRAM
''' ---------------------------------------------------------------------------------------------------- '''
n = val()
d = defaultdict(set)
root = None
for i in range(n-1):
s = li()
d[s[0]].add(s[1])
if not root:
root = s[0]
k = li()
k2 = set(k)
kdict = {}
for ind,i in enumerate(k):
kdict[i] = ind
ans = []
helpset = deepcopysets(root,d,{})
ans = dfs(root,ans,d,k,helpset,kdict)
j = 0
for i in ans:
if i in k2:
if k[j] != i:
print(-1)
exit()
else:
j+=1
print(*ans)
''' ---------------------------------------------------------------------------------------------------- '''
``` | instruction | 0 | 16,289 | 13 | 32,578 |
No | output | 1 | 16,289 | 13 | 32,579 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1
Submitted Solution:
```
#TO MAKE THE PROGRAM FAST
''' ---------------------------------------------------------------------------------------------------- '''
import sys
from collections import *
input = sys.stdin.readline
sys.setrecursionlimit(100000)
''' ---------------------------------------------------------------------------------------------------- '''
#FOR TAKING INPUTS
''' ---------------------------------------------------------------------------------------------------- '''
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def val():return int(input().rstrip('\n'))
def st():return input().rstrip('\n')
def sttoli():return [int(i) for i in input().rstrip('\n')]
''' ---------------------------------------------------------------------------------------------------- '''
def deepcopysets(root,maind,finald):
try:
finald[root] = set()
if not len(maind[root]):
finald[root].add(root)
else:
for i in maind[root]:
temp = deepcopysets(i,maind,finald)
for j in temp[i]:
finald[root].add(j)
finald[root] = sorted(list(finald[root]))
return finald
except:
print(-1)
exit()
def givearraysorted(l,helpset,kdict):
return sorted(l,key = lambda x:kdict[helpset[x][0]])
def dfs(root,arr,d,k,helpset,kdict):
try:
temp = givearraysorted(d[root],helpset,kdict)
for i in temp:
if not len(d[i]):
arr.append(root)
arr.append(i)
else:
arr.append(root)
arr = dfs(i,arr,d,k,helpset,kdict)
arr.append(root)
return arr
except:
print(-1)
exit()
#MAIN PROGRAM
''' ---------------------------------------------------------------------------------------------------- '''
n = val()
d = defaultdict(set)
root = 1
templist = []
for i in range(n-1):
templist.append(li())
k = li()
k2 = set(k)
kdict = {}
for ind,i in enumerate(k):
kdict[i] = ind
for i in templist:
if i[0] not in k2:
d[i[0]].add(i[1])
else:d[i[1]].add(i[0])
# print(d)
ans = []
# print(d)
helpset = deepcopysets(root,d,{})
ans = dfs(root,ans,d,k,helpset,kdict)
j = 0
if len(ans) != 2*n-1:
print(-1)
exit()
for i in ans:
if i in k2:
if k[j] != i:
print(-1)
exit()
else:
j+=1
print(*ans)
''' ---------------------------------------------------------------------------------------------------- '''
``` | instruction | 0 | 16,290 | 13 | 32,580 |
No | output | 1 | 16,290 | 13 | 32,581 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Connected undirected graph without cycles is called a tree. Trees is a class of graphs which is interesting not only for people, but for ants too.
An ant stands at the root of some tree. He sees that there are n vertexes in the tree, and they are connected by n - 1 edges so that there is a path between any pair of vertexes. A leaf is a distinct from root vertex, which is connected with exactly one other vertex.
The ant wants to visit every vertex in the tree and return to the root, passing every edge twice. In addition, he wants to visit the leaves in a specific order. You are to find some possible route of the ant.
Input
The first line contains integer n (3 ≤ n ≤ 300) — amount of vertexes in the tree. Next n - 1 lines describe edges. Each edge is described with two integers — indexes of vertexes which it connects. Each edge can be passed in any direction. Vertexes are numbered starting from 1. The root of the tree has number 1. The last line contains k integers, where k is amount of leaves in the tree. These numbers describe the order in which the leaves should be visited. It is guaranteed that each leaf appears in this order exactly once.
Output
If the required route doesn't exist, output -1. Otherwise, output 2n - 1 numbers, describing the route. Every time the ant comes to a vertex, output it's index.
Examples
Input
3
1 2
2 3
3
Output
1 2 3 2 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 6 3
Output
1 2 4 5 4 6 4 2 1 3 1
Input
6
1 2
1 3
2 4
4 5
4 6
5 3 6
Output
-1
Submitted Solution:
```
#TO MAKE THE PROGRAM FAST
''' ---------------------------------------------------------------------------------------------------- '''
import sys
from collections import *
input = sys.stdin.readline
sys.setrecursionlimit(100000)
''' ---------------------------------------------------------------------------------------------------- '''
#FOR TAKING INPUTS
''' ---------------------------------------------------------------------------------------------------- '''
def li():return [int(i) for i in input().rstrip('\n').split(' ')]
def val():return int(input().rstrip('\n'))
def st():return input().rstrip('\n')
def sttoli():return [int(i) for i in input().rstrip('\n')]
''' ---------------------------------------------------------------------------------------------------- '''
try:
def deepcopysets(root,maind,finald):
finald[root] = set()
if not len(maind[root]):
finald[root].add(root)
else:
for i in maind[root]:
temp = deepcopysets(i,maind,finald)
for j in temp[i]:
finald[root].add(j)
finald[root] = sorted(list(finald[root]))
return finald
except:
print(-1)
exit()
def givearraysorted(l,helpset,kdict):
try:
return sorted(l,key = lambda x:kdict[helpset[x][0]])
except:
print(-1)
exit()
try:
def dfs(root,arr,d,k,helpset,kdict):
temp = givearraysorted(d[root],helpset,kdict)
for i in temp:
if not len(d[i]):
arr.append(root)
arr.append(i)
else:
arr.append(root)
arr = dfs(i,arr,d,k,helpset,kdict)
arr.append(root)
return arr
except:
print(-1)
exit()
#MAIN PROGRAM
''' ---------------------------------------------------------------------------------------------------- '''
n = val()
d = defaultdict(set)
root = 1
templist = []
for i in range(n-1):
templist.append(sorted(li()))
templist.sort()
k = li()
k2 = set(k)
kdict = {}
for ind,i in enumerate(k):
kdict[i] = ind
for i in templist:
if i[0] not in k2 and i[1] != 1 and i[1] not in d:
d[i[0]].add(i[1])
else:d[i[1]].add(i[0])
# print(d,k2)
ans = []
# print(d)
helpset = deepcopysets(root,d,{})
ans = dfs(root,ans,d,k,helpset,kdict)
j = 0
if len(ans) != (2*n)-1:
print(-1)
exit()
else:
for i in ans:
if i in k2:
if k[j] != i:
print(-1)
exit()
else:
j+=1
print(*ans)
''' ---------------------------------------------------------------------------------------------------- '''
``` | instruction | 0 | 16,291 | 13 | 32,582 |
No | output | 1 | 16,291 | 13 | 32,583 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.