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 an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied.
Output
Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)).
If there are multiple possible answers, print any of them.
Examples
Input
5 5
1 2
2 3
3 5
4 3
1 5
Output
3 5
2 1
3 2
3 4
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
4 1
1 2
1 3
Input
8 9
1 2
2 3
2 5
1 6
3 4
6 5
4 5
2 7
5 8
Output
3 2
2 5
8 5
6 1
2 7
1 2
3 4
Note
Picture corresponding to the first example: <image>
In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.
Picture corresponding to the second example: <image>
In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.
Picture corresponding to the third example: <image>
In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
Submitted Solution:
```
def find(x):
if(par[x]==x):
return x
par[x]=find(par[x])
return par[x]
def union(a,b):
xa=find(a)
xb=find(b)
if(xa==xb):
return 0
if(size[xa]>size[xb]):
xa,xb=xb,xa
par[xa]=xb
size[xb]+=size[xa]
return 1
n,m,d=map(int,input().split())
par=[i for i in range(n+1)]
size=[1 for i in range(n+1)]
count=0
ans=0
last=[]
arr=[]
one_saver=[]
for i in range(m):
a,b=map(int,input().split())
if(a==1 or b==1):
if(a==1):
one_saver.append(b)
else:
one_saver.append(a)
elif(union(a,b)):
last.append([a,b])
dif_par=set()
for i in range(2,n+1):
par[i]=find(par[i])
if par[i] not in dif_par:
dif_par.add(par[i])
flag=0
if(d>len(one_saver) or d<len(dif_par)):
flag=1
print("NO")
idntfy1=set()
idntfy2=set()
idntfy3=set()
if(flag==0):
print("YES")
for i in one_saver:
if par[i] not in idntfy1:
print(1,i)
idntfy1.add(par[i])
idntfy2.add(i)
idntfy3.add(i)
i=0
j=0
while(j<d-len(dif_par)):
if one_saver[i] not in idntfy2:
print(one_saver[i],1)
j+=1
idntfy3.add(one_saver[i])
i+=1
for i in last:
if i[0] not in idntfy3 or i[1] not in idntfy3:
print(i[0],i[1])
idntfy3.add(i[0])
idntfy3.add(i[1])
``` | instruction | 0 | 105,303 | 13 | 210,606 |
No | output | 1 | 105,303 | 13 | 210,607 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph.
Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it.
Input
The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively.
The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied.
Output
Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)).
If there are multiple possible answers, print any of them.
Examples
Input
5 5
1 2
2 3
3 5
4 3
1 5
Output
3 5
2 1
3 2
3 4
Input
4 6
1 2
1 3
1 4
2 3
2 4
3 4
Output
4 1
1 2
1 3
Input
8 9
1 2
2 3
2 5
1 6
3 4
6 5
4 5
2 7
5 8
Output
3 2
2 5
8 5
6 1
2 7
1 2
3 4
Note
Picture corresponding to the first example: <image>
In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.
Picture corresponding to the second example: <image>
In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer.
Picture corresponding to the third example: <image>
In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
Submitted Solution:
```
n,m=map(int,input().split())
G={}
v=0
c=-1
for i in range(m):
a,b=map(int,input().split())
try:
G[a].append(b)
if (len(G[a])>v):
c=a
v=len(G[a])
except:
G[a]=[b]
if (v<1):
c=a
v=1
try:
G[b].append(a)
if (len(G[b])>v):
c=b
v=len(G[b])
except:
G[b]=[a]
if (v<1):
c=b
v=1
A={}
for i in G.keys():
A[i]=-1
q=[v]
A[v]=1
while(len(q)!=0):
a=q.pop()
for i in G[a]:
if (A[i]==-1):
print(a,i)
q.append(i)
A[i]=1
``` | instruction | 0 | 105,304 | 13 | 210,608 |
No | output | 1 | 105,304 | 13 | 210,609 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,403 | 13 | 210,806 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
import sys
n, *ab = map(int, sys.stdin.read().split())
graph = [[] for _ in range(n)]
for a, b in zip(*[iter(ab)] * 2):
a -= 1
b -= 1
graph[a].append(b)
graph[b].append(a)
def main():
rank = [None] * n; rank[0] = 0
parent = [None] * n
leaves = []
stack = [0]
while stack:
u = stack.pop()
if (not u == 0) and len(graph[u]) == 1:
leaves.append(u)
continue
for v in graph[u]:
if v == parent[u]:
continue
parent[v] = u
rank[v] = rank[u] + 1
stack.append(v)
if len(graph[0]) == 1:
leaves.append(0)
parent[0] = graph[0][0]
parent[graph[0][0]] = None
pars = set()
for leaf in leaves:
pars.add(parent[leaf])
ma = n - 1 - (len(leaves) - len(pars))
rs = set([rank[leaf] & 1 for leaf in leaves])
mi = 1 if len(rs) == 1 else 3
print(mi, ma)
if __name__ == '__main__':
main()
``` | output | 1 | 105,403 | 13 | 210,807 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,404 | 13 | 210,808 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
import sys
import math
from collections import deque
def solve():
#f = open("b.txt")
f = sys.stdin
n = int(f.readline())
edges = [[] for i in range(n)]
for i in range(n - 1):
s = f.readline().strip()
a, b = [int(x) for x in s.split(' ', 2)]
edges[a - 1].append(b - 1)
edges[b - 1].append(a - 1)
root = 0
for i in range(n):
if len(edges[i]) > 1:
root = i
break
#print(root)
odd_dist = False
even_dist = False
minf = 1
maxf = n - 1
dist = [0 for i in range(n)]
q = deque()
q.append(root)
while len(q) > 0:
cur = q.popleft()
child_leaves = 0
for next in edges[cur]:
if dist[next] == 0 and next != root:
q.append(next)
dist[next] = dist[cur] + 1
if len(edges[next]) == 1:
child_leaves += 1
if dist[next] % 2 == 1:
odd_dist = True
else:
even_dist = True
if child_leaves > 1:
maxf = maxf - child_leaves + 1
if odd_dist and even_dist:
minf = 3
print(str(minf) + " " + str(maxf))
solve()
``` | output | 1 | 105,404 | 13 | 210,809 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,405 | 13 | 210,810 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
I=lambda:list(map(int,input().split()))
n,=I()
g=[[] for i in range(n+1)]
for i in range(n-1):
x,y=I()
g[x].append(y)
g[y].append(x)
leaf=[]
for i in range(1,n+1):
if len(g[i])==1:
leaf.append(i)
st=[1]
visi=[-1]*(n+1)
visi[1]=0
while st:
x=st.pop()
for y in g[x]:
if visi[y]==-1:
visi[y]=1-visi[x]
st.append(y)
ch=visi[leaf[0]]
fl=1
temp=0
for i in leaf:
if visi[i]!=ch:
fl=0
mi=1
if not fl:
mi=3
an=[0]*(n+1)
ma=n-1
for i in leaf:
for j in g[i]:
if an[j]==1:
ma-=1
else:
an[j]=1
print(mi,ma)
``` | output | 1 | 105,405 | 13 | 210,811 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,406 | 13 | 210,812 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
import collections,sys
n = int(sys.stdin.readline())
g = []
sys.setrecursionlimit(2**20)
for i in range(n+1):
g.append([])
for i in range(n-1):
a,b = list(map(int,sys.stdin.readline().split(' ')))
g[a].append(b)
g[b].append(a)
leaf = {}
mx = n-1
for i in range(1,n+1,1):
if(len(g[i]) == 1):
leaf[i] = True
else:
s = i
for i in range(1,n+1,1):
l = 0
for v in g[i]:
if(v in leaf):
l+=1
if(l != 0):
mx = mx-l+1
mn = 1
l = s
dst = [0]*(n+1)
a = collections.deque([])
exp = {}
exp[l] = True
a.append(l)
o = 0
e = 0
while(a):
v = a.pop()
h = dst[v]+1
for u in g[v]:
if(u not in exp):
dst[u] = h
exp[u] = True
a.append(u)
if(u in leaf):
if(h % 2 == 1):
o += 1
else:
e += 1
if(o == 0 or e ==0):
mn = 1
else:
mn = 3
print(mn,mx)
``` | output | 1 | 105,406 | 13 | 210,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,407 | 13 | 210,814 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
from sys import stdin
from collections import deque
input=stdin.readline
n=int(input())
graph=[set() for i in range(n+1)]
visited2=[False]*(n+2)
for i in range(n - 1):
a,b=map(int,input().split())
graph[a].add(b)
graph[b].add(a)
k=0
for i in range(n + 1):
if len(graph[i]) == 1:
k=i
break
m=[1,n-1]
def dfs(node, depth):
nodes=deque([node])
depths=deque([depth])
while len(nodes) > 0:
node=nodes.popleft()
depth=depths.popleft()
visited2[node] = True
went=False
for i in graph[node]:
if not visited2[i]:
nodes.appendleft(i)
depths.appendleft(depth+1)
went=True
if not went:
if depth % 2 == 1 and depth != 1:
m[0] = 3
dfs(k,0)
oneBranches=[0]*(n+1)
for i in range(1,n+1):
if len(graph[i]) == 1:
oneBranches[graph[i].pop()] += 1
for i in range(n+1):
if oneBranches[i] > 1:
m[1] -= oneBranches[i] - 1
print(*m)
#if there is odd path length, min is 3 else 1
#max length: each odd unvisited path gives n, while each even unvisited path gives n - 1
``` | output | 1 | 105,407 | 13 | 210,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,408 | 13 | 210,816 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
import io, os, collections
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
n = int(input())
nb = [[] for _ in range(n)]
for i in range(n-1):
u, v = [int(s)-1 for s in input().split()]
nb[u].append(v)
nb[v].append(u)
leaves = []
father = set()
for i in range(n):
if len(nb[i])==1:
leaves.append(i)
father.add(nb[i][0])
maxAns = n-1-(len(leaves)-len(father))
minAns = 1
q = collections.deque()
q.append(leaves[0])
d = [0]*n # 1/-1
d[leaves[0]] = 1
while q:
node = q.popleft()
tag = - d[node]
for neibor in nb[node]:
if d[neibor] == 0:
d[neibor] = tag
q.append(neibor)
for lv in leaves:
if d[lv] != 1:
minAns = 3
break
print('{} {}'.format(minAns, maxAns))
``` | output | 1 | 105,408 | 13 | 210,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,409 | 13 | 210,818 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
import sys
from collections import defaultdict
# sys.setrecursionlimit(100000)
input = sys.stdin.readline
INF = 2**62-1
def read_int():
return int(input())
def read_int_n():
return list(map(int, input().split()))
def read_float():
return float(input())
def read_float_n():
return list(map(float, input().split()))
def read_str():
return input().strip()
def read_str_n():
return list(map(str, input().split()))
def error_print(*args):
print(*args, file=sys.stderr)
def mt(f):
import time
def wrap(*args, **kwargs):
s = time.time()
ret = f(*args, **kwargs)
e = time.time()
error_print(e - s, 'sec')
return ret
return wrap
@mt
def slv(N, AB):
ans = 0
g = defaultdict(list)
for a, b in AB:
g[a].append(b)
g[b].append(a)
leaves = set()
lp = defaultdict(set)
for i in range(1, N+1):
if len(g[i]) == 1:
leaves.add(i)
lp[g[i][0]].add(i)
def dfs(s):
stack = [s]
d = {s:0}
while stack:
u = stack.pop()
for v in g[u]:
if v not in d:
d[v] = d[u] + 1
stack.append(v)
return d
fmin = 1
d = dfs(1)
leaves = list(leaves)
oe = d[leaves[0]] % 2
for l in leaves:
if oe != d[l] % 2:
fmin = 3
break
fmax = N - 1
for l in lp.values():
fmax -= len(l) - 1
return fmin, fmax
def main():
N = read_int()
AB = [read_int_n() for _ in range(N-1)]
print(*slv(N, AB))
if __name__ == '__main__':
main()
``` | output | 1 | 105,409 | 13 | 210,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,410 | 13 | 210,820 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
import sys
readline = sys.stdin.readline
def parorder(Edge, p):
N = len(Edge)
par = [0]*N
par[p] = -1
stack = [p]
order = []
visited = set([p])
ast = stack.append
apo = order.append
while stack:
vn = stack.pop()
apo(vn)
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
ast(vf)
return par, order
def getcld(p):
res = [[] for _ in range(len(p))]
for i, v in enumerate(p[1:], 1):
res[v].append(i)
return res
N = int(readline())
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, readline().split())
a -= 1
b -= 1
Edge[a].append(b)
Edge[b].append(a)
Leaf = [i for i in range(N) if len(Edge[i]) == 1]
sLeaf = set(Leaf)
for i in range(N):
if i not in sLeaf:
root = i
break
P, L = parorder(Edge, root)
dp = [0]*N
used = set([root])
stack = [root]
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf not in used:
used.add(vf)
stack.append(vf)
dp[vf] = 1-dp[vn]
if len(set([dp[i] for i in Leaf])) == 1:
mini = 1
else:
mini = 3
k = set()
for l in Leaf:
k.add(P[l])
maxi = N-1 - len(Leaf) + len(k)
print(mini, maxi)
``` | output | 1 | 105,410 | 13 | 210,821 |
Provide tags and a correct Python 2 solution for this coding contest problem.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image> | instruction | 0 | 105,411 | 13 | 210,822 |
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees
Correct Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
#main code
def get(n):
p=2**32
c=32
while p:
if p&n:
return c+1
c-=1
p/=2
return 0
inp=inp()
n=inp[0]
pos=1
mx=0
root=0
deg=Counter()
d=[[] for i in range(n+1)]
for i in range(n-1):
u,v=inp[pos],inp[pos+1]
pos+=2
d[u].append(v)
d[v].append(u)
deg[u]+=1
deg[v]+=1
if deg[u]>mx:
mx=deg[u]
root=u
if deg[v]>mx:
mx=deg[v]
root=v
vis=[0]*(n+1)
vis[root]=1
q=[(root,0)]
f1,f2=0,0
mx=0
c1=0
d1=Counter()
while q:
x,w=q.pop(0)
ft=0
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append((i,w+1))
ft=1
if not ft:
c1+=1
d1[d[x][0]]+=1
if w%2:
#print 1,x
f1=1
else:
#print 2,x
f2=1
if f1 and f2:
ans1=3
else:
ans1=1
ans2=n-1-(c1-len(d1.keys()))
pr_arr((ans1,ans2))
``` | output | 1 | 105,411 | 13 | 210,823 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
mod = 1000000007
eps = 10**-9
def main():
import sys
input = sys.stdin.buffer.readline
N = int(input())
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
from collections import deque
que = deque()
que.append(1)
seen = [-1] * (N+1)
seen[1] = 0
par = [0] * (N+1)
child = [[] for _ in range(N+1)]
seq = []
while que:
v = que.popleft()
seq.append(v)
for u in adj[v]:
if seen[u] == -1:
seen[u] = seen[v] + 1
par[u] = v
child[v].append(u)
que.append(u)
seq.reverse()
ok = 1
flg = -1
is_leaf = [0] * (N+1)
for v in range(1, N+1):
if len(adj[v]) == 1:
if flg == -1:
flg = seen[v] & 1
else:
if flg != seen[v] & 1:
ok = 0
is_leaf[v] = 1
if ok:
m = 1
else:
m = 3
M = N-1
for v in range(1, N+1):
cnt = 0
for u in adj[v]:
if is_leaf[u]:
cnt += 1
if cnt:
M -= cnt-1
print(m, M)
if __name__ == '__main__':
main()
``` | instruction | 0 | 105,412 | 13 | 210,824 |
Yes | output | 1 | 105,412 | 13 | 210,825 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
def solveAll():
case = readCase()
print(*solve(case))
def readCase():
treeSize = int(input())
graph = [[] for i in range(treeSize)]
for _ in range(1, treeSize):
a, b = (int(x) for x in input().split())
a -= 1
b -= 1
graph[a] += [b]
graph[b] += [a]
return graph
def solve(graph):
leafs = computeLeafs(graph)
return minF(graph, leafs), maxF(graph, leafs)
def computeLeafs(graph):
leafs = [node for node in range(0, len(graph)) if len(graph[node]) == 1]
return leafs
def minF(graph, leafs):
color = [None] * len(graph)
queue = [0]
color[0] = "a"
head = 0
while head < len(queue):
currentNode = queue[head]
head += 1
for neighbor in graph[currentNode]:
if color[neighbor] != None: continue
color[neighbor] = "b" if color[currentNode] == "a" else "a"
queue += [neighbor]
if all(color[leafs[0]] == color[leaf] for leaf in leafs):
return 1
return 3
def maxF(graph, leafs):
group = [0] * len(graph)
for leaf in leafs:
parent = graph[leaf][0]
group[parent] += 1
ans = len(graph) - 1
for size in group:
if size >= 2:
ans -= size - 1
return ans
solveAll()
``` | instruction | 0 | 105,413 | 13 | 210,826 |
Yes | output | 1 | 105,413 | 13 | 210,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
n = int(input())
l = [[] for _ in range(n)]
for _ in range(n-1):
p1, p2 = map(lambda x : x-1, map(int, input().split()))
l[p1].append(p2)
l[p2].append(p1)
leaf = []
e = [0] * n
maxans = n-1
for i in range(n):
temp = l[i]
if len(temp) == 1:
if e[temp[0]] == 1:
maxans -= 1
else:
e[temp[0]] = 1
leaf.append(i)
q = [0]
visited = [-1]*n
visited[0] = 0
while q:
node = q.pop()
for i in l[node]:
if visited[i] == -1:
q.append(i)
visited[i] = 1 - visited[node]
f = visited[leaf[0]]
for i in leaf:
if visited[i] != f:
minans = 3
break
else:
minans = 1
print(minans, maxans)
``` | instruction | 0 | 105,414 | 13 | 210,828 |
Yes | output | 1 | 105,414 | 13 | 210,829 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
def main():
n = int(input())
g = [[] for _ in range(n)]
for i in range(n-1):
a, b = map(int, input().split())
a, b = a-1, b-1
g[a].append(b)
g[b].append(a)
# min
leaf = []
for i in range(n):
if len(g[i]) == 1:
leaf.append(i)
#print(leaf)
from collections import deque
root = leaf[0]
q = deque()
dist = [-1]*n
q.append(root)
dist[root] = 0
#order = []
#par = [-1]*n
while q:
v = q.popleft()
#order.append(v)
for u in g[v]:
if dist[u] == -1:
dist[u] = dist[v]+1
#par[u] = v
q.append(u)
#print(dist)
for v in leaf:
if dist[v]%2 != 0:
m = 3
break
else:
m = 1
# max
root = leaf[0]
q = deque()
visit = [-1]*n
q.append(root)
visit[root] = 0
x = 0
while q:
v = q.popleft()
flag = False
for u in g[v]:
if len(g[u]) == 1:
flag = True
if visit[u] == -1:
visit[u] = 0
q.append(u)
if flag:
x += 1
#print(x)
M = (n-1)-len(leaf)+x
print(m, M)
if __name__ == '__main__':
main()
``` | instruction | 0 | 105,415 | 13 | 210,830 |
Yes | output | 1 | 105,415 | 13 | 210,831 |
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
from sys import stdin, stdout
from collections import Counter, defaultdict
from itertools import permutations, combinations
raw_input = stdin.readline
pr = stdout.write
def in_num():
return int(raw_input())
def in_arr():
return map(int,raw_input().split())
def pr_num(n):
stdout.write(str(n)+'\n')
def pr_arr(arr):
pr(' '.join(map(str,arr))+'\n')
# fast read function for total integer input
def inp():
# this function returns whole input of
# space/line seperated integers
# Use Ctrl+D to flush stdin.
return map(int,stdin.read().split())
range = xrange # not for python 3.0+
#main code
def get(n):
p=2**32
c=32
while p:
if p&n:
return c+1
c-=1
p/=2
return 0
inp=inp()
n=inp[0]
pos=1
mx=0
root=0
deg=Counter()
d=[[] for i in range(n+1)]
for i in range(n-1):
u,v=inp[pos],inp[pos+1]
pos+=2
d[u].append(v)
d[v].append(u)
deg[u]+=1
deg[v]+=1
if deg[u]>mx:
mx=deg[u]
root=u
if deg[v]>mx:
mx=deg[v]
root=v
vis=[0]*(n+1)
vis[root]=1
q=[(root,0)]
f1,f2=0,0
mx=0
c1=0
d1=Counter()
while q:
x,w=q.pop(0)
ft=0
for i in d[x]:
if not vis[i]:
vis[i]=1
q.append((i,w+1))
ft=1
if not ft:
c1+=1
d1[x]+=1
if w%2:
#print 1,x
f1=1
else:
#print 2,x
f2=1
if f1 and f2:
ans1=3
else:
ans1=1
ans2=n-1-(c1-len(d1.keys()))
pr_arr((ans1,ans2))
``` | instruction | 0 | 105,416 | 13 | 210,832 |
No | output | 1 | 105,416 | 13 | 210,833 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
print("YES")
``` | instruction | 0 | 105,417 | 13 | 210,834 |
No | output | 1 | 105,417 | 13 | 210,835 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
n = int(input())
e = dict.fromkeys(list(range(1,n+1)))
for _ in range(n-1):
v1,v2 = map(int,input().split())
if(e[v1]== None and e[v1]!= -1 ):
e[v1] = v2
else:
e[v1] = -1;
if(e[v2]== None and e[v2]!= -1 ):
e[v2] = v1
else:
e[v2] = -1;
le = [0]*n
for i in range(1,n+1):
if(e[i]!=-1):
le[e[i]]+=1
m = 1
for i in range(n):
m +=int(le[i]/2)
if(m>2):
print(m,n-1 - m+1)
elif(m>1):
print(1,n-m)
else:
print(1,n-1)
if(n>1000):
print(m)
``` | instruction | 0 | 105,418 | 13 | 210,836 |
No | output | 1 | 105,418 | 13 | 210,837 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
from sys import stdin
input=stdin.readline
n=int(input())
graph=[set() for i in range(n+1)]
visited=[False]*(n+1)
visited2=[False]*(n+2)
for i in range(n - 1):
a,b=map(int,input().split())
graph[a].add(b)
graph[b].add(a)
m=[1,n-1]
def dfs2(node,depth):
went=False
visited2[node]=True
for i in graph[node]:
if not visited2[i]:
dfs2(i, depth + 1)
went=True
if not went:
if depth % 2 == 1 and depth != 1:
m[0]=3
dfs2(1,0)
oneBranches=[0]*(n+1)
for i in range(1,n+1):
if len(graph[i]) == 1:
oneBranches[graph[i].pop()] += 1
for i in range(n+1):
if oneBranches[i] > 1:
m[1] -= oneBranches[i] - 1
print(*m)
#if there is odd path length, min is 3 else 1
#max length: each odd unvisited path gives n, while each even unvisited path gives n - 1
``` | instruction | 0 | 105,419 | 13 | 210,838 |
No | output | 1 | 105,419 | 13 | 210,839 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold:
* For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0.
Note that you can put very large positive integers (like 10^{(10^{10})}).
It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment.
<image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5).
<image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0.
What are the minimum and the maximum possible values of f for the given tree? Find and print both.
Input
The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree.
The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices.
Output
Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints.
Examples
Input
6
1 3
2 3
3 4
4 5
5 6
Output
1 4
Input
6
1 3
2 3
3 4
4 5
4 6
Output
3 3
Input
7
1 2
2 7
3 4
4 7
5 6
6 7
Output
1 6
Note
In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3.
<image>
In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum.
<image>
Submitted Solution:
```
def main():
n = int(input())
graph = dict()
for i in range(n - 1):
a, b = map(int, input().split())
if not a in graph:
graph[a] = {b}
else:
graph[a].add(b)
if not b in graph:
graph[b] = {a}
else:
graph[b].add(a)
almost_corner = set()
corners = set()
for i in graph:
if len(graph[i]) == 1:
corners.add(i)
for k in graph[i]:
almost_corner.add(k)
dif_corners = len(almost_corner)
not_check = set()
cor_min_dif = 0
for i in almost_corner:
add_two = False
not_check.add(i)
for c in graph[i]:
if c in almost_corner and c not in not_check:
not_check.add(c)
add_two = True
if add_two:
cor_min_dif += 2
print(1 + cor_min_dif, n - len(corners) + dif_corners - 1)
if __name__ == "__main__":
t = 1
for i in range(t):
main()
``` | instruction | 0 | 105,420 | 13 | 210,840 |
No | output | 1 | 105,420 | 13 | 210,841 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The New Year holidays are over, but Resha doesn't want to throw away the New Year tree. He invited his best friends Kerim and Gural to help him to redecorate the New Year tree.
The New Year tree is an undirected tree with n vertices and root in the vertex 1.
You should process the queries of the two types:
1. Change the colours of all vertices in the subtree of the vertex v to the colour c.
2. Find the number of different colours in the subtree of the vertex v.
Input
The first line contains two integers n, m (1 ≤ n, m ≤ 4·105) — the number of vertices in the tree and the number of the queries.
The second line contains n integers ci (1 ≤ ci ≤ 60) — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the vertices of the j-th edge. It is guaranteed that you are given correct undirected tree.
The last m lines contains the description of the queries. Each description starts with the integer tk (1 ≤ tk ≤ 2) — the type of the k-th query. For the queries of the first type then follows two integers vk, ck (1 ≤ vk ≤ n, 1 ≤ ck ≤ 60) — the number of the vertex whose subtree will be recoloured with the colour ck. For the queries of the second type then follows integer vk (1 ≤ vk ≤ n) — the number of the vertex for which subtree you should find the number of different colours.
Output
For each query of the second type print the integer a — the number of different colours in the subtree of the vertex given in the query.
Each of the numbers should be printed on a separate line in order of query appearing in the input.
Examples
Input
7 10
1 1 1 1 1 1 1
1 2
1 3
1 4
3 5
3 6
3 7
1 3 2
2 1
1 4 3
2 1
1 2 5
2 1
1 6 4
2 1
2 2
2 3
Output
2
3
4
5
1
2
Input
23 30
1 2 2 6 5 3 2 1 1 1 2 4 5 3 4 4 3 3 3 3 3 4 6
1 2
1 3
1 4
2 5
2 6
3 7
3 8
4 9
4 10
4 11
6 12
6 13
7 14
7 15
7 16
8 17
8 18
10 19
10 20
10 21
11 22
11 23
2 1
2 5
2 6
2 7
2 8
2 9
2 10
2 11
2 4
1 12 1
1 13 1
1 14 1
1 15 1
1 16 1
1 17 1
1 18 1
1 19 1
1 20 1
1 21 1
1 22 1
1 23 1
2 1
2 5
2 6
2 7
2 8
2 9
2 10
2 11
2 4
Output
6
1
3
3
2
1
2
3
5
5
1
2
2
1
1
1
2
3
Submitted Solution:
```
def dfs_list(graph, start):
visited = []
stack = [start]
while stack:
vertex = stack.pop()
if vertex not in visited:
visited.append(vertex)
stack.extend(graph[vertex])
else:
visited.append(vertex)
return visited
def get_nodes(tree_list, node):
temp = tree_list[:]
tree_list.reverse()
i, j = temp.index(node), len(temp) - 1 - tree_list.index(node)
stack = set()
if i == j:
stack.add(node)
return stack
for k in range(i, j):
if temp[k] not in stack:
stack.add(temp[k])
return stack
def change_colors(colors, tree_list, node, color):
stack = get_nodes(tree_list, node)
for element in stack:
colors[element-1] = color
return colors
def get_number_of_colors(tree_list, node, colors):
stack = get_nodes(tree_list, node)
dif_colors = set()
for element in stack:
if colors[element-1] not in dif_colors:
dif_colors.add(colors[element-1])
return len(dif_colors)
n, m = map(int, input().split())
tree = {}
index = 1
colors = []
for color in input().split():
tree[index] = []
colors.append(int(color))
index += 1
for i in range(n-1):
key, value = map(int, input().split())
tree[key].append(value)
tree[value].append(key)
list_tree = dfs_list(tree, 1)
for i in range(m):
command = [int(item) for item in input().split()]
if len(command) == 3:
colors = change_colors(colors, list_tree, command[1], command[2])
else:
print(get_number_of_colors(list_tree, command[1], colors))
``` | instruction | 0 | 105,720 | 13 | 211,440 |
No | output | 1 | 105,720 | 13 | 211,441 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Heidi got tired of deciphering the prophecy hidden in the Tree of Life and decided to go back to her headquarters, rest a little and try there. Of course, she cannot uproot the Tree and take it with her, so she made a drawing of the Tree on a piece of paper. On second thought, she made more identical drawings so as to have n in total (where n is the number of vertices of the Tree of Life) – who knows what might happen?
Indeed, on her way back Heidi was ambushed by a group of zombies. While she managed to fend them off, they have damaged her drawings in a peculiar way: from the i-th copy, the vertex numbered i was removed, along with all adjacent edges. In each picture, the zombies have also erased all the vertex numbers and relabeled the remaining n - 1 vertices arbitrarily using numbers 1 to n (fortunately, each vertex still has a distinct number). What's more, the drawings have been arbitrarily shuffled/reordered.
Now Heidi wants to recover the Tree of Life from her descriptions of all the drawings (as lists of edges).
Input
The first line of the input contains Z ≤ 20 – the number of test cases. Z descriptions of single test cases follow.
In each test case, the first line of input contains numbers n (2 ≤ n ≤ 100) and k (where k is the number of drawings; we have k = n). In the following lines, the descriptions of the k drawings are given. The description of the i-th drawing is a line containing mi – the number of edges in this drawing, followed by mi lines describing edges, each of which contains two space-separated integers –- the numbers of the two vertices connected by the edge.
Output
If Heidi's drawings cannot possibly come from a single tree, you should output the word NO. Otherwise, output one line containing the word YES and n - 1 lines describing any tree that Heidi's drawings could have come from. For every edge you should output the numbers of the vertices that it connects, separated with a single space. If there are many solutions, print any of them.
Example
Input
1
5 5
2
4 1
2 1
1
3 1
3
4 1
4 3
2 1
3
3 1
3 2
4 1
3
2 1
3 2
4 2
Output
YES
2 5
4 2
3 2
5 1
Submitted Solution:
```
n = int(input())
t = [0] * (n + 1)
out = 0
for _ in range(n-1):
a, b = map(lambda x: int(x),input().split(' '))
out += t[a]
out += t[b]
t[a] += 1
t[b] += 1
print(out)
``` | instruction | 0 | 105,746 | 13 | 211,492 |
No | output | 1 | 105,746 | 13 | 211,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There are two rooted trees, each with N vertices. The vertices of each tree are numbered 1 through N. In the first tree, the parent of Vertex i is Vertex A_i. Here, A_i=-1 if Vertex i is the root of the first tree. In the second tree, the parent of Vertex i is Vertex B_i. Here, B_i=-1 if Vertex i is the root of the second tree.
Snuke would like to construct an integer sequence of length N, X_1 , X_2 , ... , X_N, that satisfies the following condition:
* For each vertex on each tree, let the indices of its descendants including itself be a_1 , a_2 , ..., a_k. Then, abs(X_{a_1} + X_{a_2} + ... + X_{a_k})=1 holds.
Determine whether it is possible to construct such a sequence. If the answer is possible, find one such sequence.
Constraints
* 1 \leq N \leq 10^5
* 1 \leq A_i \leq N, if Vertex i is not the root in the first tree.
* A_i = -1, if Vertex i is the root in the first tree.
* 1 \leq B_i \leq N, if Vertex i is not the root in the second tree.
* B_i = -1, if Vertex i is the root in the second tree.
* Input corresponds to valid rooted trees.
Input
Input is given from Standard Input in the following format:
N
A_1 A_2 .. A_N
B_1 B_2 .. B_N
Output
If it is not possible to construct an integer sequence that satisfies the condition, print `IMPOSSIBLE`. If it is possible, print `POSSIBLE` in the first line. Then, in the second line, print X_1 , X_2 , ... , X_N, an integer sequence that satisfies the condition.
Examples
Input
5
3 3 4 -1 4
4 4 1 -1 1
Output
POSSIBLE
1 -1 -1 3 -1
Input
6
-1 5 1 5 1 3
6 5 5 3 -1 3
Output
IMPOSSIBLE
Input
8
2 7 1 2 2 1 -1 4
4 -1 4 7 4 4 2 4
Output
POSSIBLE
1 2 -1 0 -1 1 0 -1
Submitted Solution:
```
オイオイオイ アイツ死ぬわ
``` | instruction | 0 | 105,994 | 13 | 211,988 |
No | output | 1 | 105,994 | 13 | 211,989 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 105,995 | 13 | 211,990 |
"Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
stone = [0]+list(map(int,input().split()))
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0]*(n+1)
for a,b in ab:
if stone[a] < stone[b]:
graph[a].append(b)
deg[b] += 1
elif stone[a] > stone[b]:
graph[b].append(a)
deg[a] += 1
que = deque()
dp = [[] for i in range(n+1)]
wl = [0]*(n+1)
ans = []
for i in range(1,n+1):
if deg[i] == 0:
que.append(i)
wl[i] = 0
while que:
x = que.popleft()
if dp[x]:
if dp[x].count(0) >= 1:
ans.append(x)
wl[x] = 1
for y in graph[x]:
if deg[y]:
dp[y].append(wl[x])
deg[y] -= 1
if deg[y] == 0:
que.append(y)
ans.sort()
print(*ans)
``` | output | 1 | 105,995 | 13 | 211,991 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 105,996 | 13 | 211,992 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
sys.setrecursionlimit(2*10**5)
N=int(input())
A=list(map(int,input().split()))
edge=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
edge[a-1].append(b-1)
edge[b-1].append(a-1)
grundy=[-1]*N
def dfs(v):
if grundy[v]!=-1:
return grundy[v]
mex=[False]*(len(edge[v])+1)
for nv in edge[v]:
if A[nv]<A[v]:
g=dfs(nv)
if g<=len(edge[v]):
mex[g]=True
for i in range(len(edge[v])+1):
if not mex[i]:
grundy[v]=i
return i
ans=[]
for i in range(N):
if dfs(i)!=0:
ans.append(i+1)
print(*ans)
``` | output | 1 | 105,996 | 13 | 211,993 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 105,997 | 13 | 211,994 |
"Correct Solution:
```
"""
Writer : SPD_9X2
https://atcoder.jp/contests/agc010/tasks/agc010_f
Nが小さいので、各頂点に関して木を探索できる
つまり、この頂点に置いた時勝てるか?がわかれば解ける
まず2頂点で考えると、Aがもう片方以上の方に置けばかつ
→値の大小が重要そう
置いた点から小さい方に下っていくのが最適。
●→高橋
〇→青木とする
●-〇-●-〇
小さい方に下って行って、周囲に自分より小さいノードが無かったら
先っぽのノードの持ち主が負けになる
複数小さいノードがある場合、一つでも勝ちがある場合勝てるノードになる
一つもない場合負け
→結局dfsしてあげればいい
"""
import sys
sys.setrecursionlimit(5000)
N = int(input())
A = list(map(int,input().split()))
lis = [ [] for i in range(N) ]
for i in range(N-1):
a,b = map(int,input().split())
a -= 1
b -= 1
lis[a].append(b)
lis[b].append(a)
def dfs(p,state): #0=tk 1=ao
temp = [0,0]
for nex in lis[p]:
if A[nex] < A[p]:
temp[ dfs(nex,state^1) ] += 1
if temp[state] > 0:
return state
else:
return state ^ 1
ans = []
for i in range(N):
if dfs(i,0) == 0:
ans.append(i+1)
print (*ans)
``` | output | 1 | 105,997 | 13 | 211,995 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 105,998 | 13 | 211,996 |
"Correct Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fractions import gcd
def readln():
_res = list(map(int,str(input()).split(' ')))
return _res
def calc(x,line):
if line == 0:
for l in v[x]:
if e[l][0] == x: son = e[l][1]
else: son = e[l][0]
if a[son-1] < a[x-1] and calc(son,l) == -1:
return 1
return -1
else:
if e[line][0] == x: y = 0
else: y = 1
if f[line][y] != 0: return f[line][y]
for l in v[x]:
if l != line:
if e[l][0] == x: son = e[l][1]
else: son = e[l][0]
if a[son-1] < a[x-1] and calc(son,l) == -1:
f[line][y] = 1
return 1
f[line][y] = -1
return -1
n = int(input())
v = [set([]) for i in range(0,n+1)]
e = [0 for i in range(0,n)]
a = readln()
for i in range(1,n):
s = readln()
v[s[0]].add(i)
v[s[1]].add(i)
e[i] = s
f = [[0,0] for i in range(0,n)]
ans = []
for i in range(1,n+1):
if calc(i,0) == 1:
ans.append(i)
ans = list(map(str,ans))
print(' '.join(ans))
``` | output | 1 | 105,998 | 13 | 211,997 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 105,999 | 13 | 211,998 |
"Correct Solution:
```
import copy, sys
sys.setrecursionlimit(10 ** 6)
n = int(input())
A = [int(i) for i in input().split()]
edge = [[] for i in range(n)]
grundy = [-1] * n
for i in range(n-1):
a, b = [int(i) for i in input().split()]
edge[a-1].append(b-1)
edge[b-1].append(a-1)
def dfs(v):
if grundy[v] != -1: return grundy[v]
mex = [0] * (len(edge[v]) + 1)
for vv in edge[v]:
if A[vv] < A[v]:
gg = dfs(vv)
if gg <= len(edge[v]): mex[gg] = 1
for i in range(len(edge[v])+1):
if mex[i] == 0:
grundy[v] = i
return i
ans = []
for i in range(n):
if dfs(i) != 0: ans.append(i+1)
print(*ans)
``` | output | 1 | 105,999 | 13 | 211,999 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 106,000 | 13 | 212,000 |
"Correct Solution:
```
import sys
input=sys.stdin.readline
sys.setrecursionlimit(10000000)
n=int(input())
a=list(map(int,input().split()))
edge=[[]for _ in range(n)]
for x,y in[list(map(int,input().split()))for _ in range(n-1)]:
edge[x-1].append(y-1)
edge[y-1].append(x-1)
def bfs(r,v):
for i in edge[v]:
if(r!=i)and(a[v]>a[i])and(not(bfs(v,i))):return True
return False
print(*[i+1 for i in range(n)if bfs(-1,i)])
``` | output | 1 | 106,000 | 13 | 212,001 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 106,001 | 13 | 212,002 |
"Correct Solution:
```
import copy, sys
sys.setrecursionlimit(10 ** 6)
n = int(input())
A = [int(i) for i in input().split()]
edge = [[] for i in range(n)]
grundy = [-1] * n
for i in range(n-1):
a, b = [int(i) for i in input().split()]
edge[a-1].append(b-1)
edge[b-1].append(a-1)
def dfs(v):
if grundy[v] != -1: return grundy[v]
mex = [0] * (len(edge[v]) + 1)
for vv in edge[v]:
if A[vv] < A[v]:
gg = dfs(vv)
if gg <= len(edge[v]): mex[gg] = 1
for i in range(len(edge[v])+1):
if mex[i] == 0:
grundy[v] = i
return i
for i in range(n):
dfs(i)
ans = []
for i in range(n):
if grundy[i] != 0: ans.append(i+1)
print(*ans)
``` | output | 1 | 106,001 | 13 | 212,003 |
Provide a correct Python 3 solution for this coding contest problem.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output | instruction | 0 | 106,002 | 13 | 212,004 |
"Correct Solution:
```
n=int(input());a=list(map(int,input().split()));e=[[]for _ in[0]*n]
for x,y in[map(int,input().split())for _ in[0]*(n-1)]:e[x-1].append(y-1);e[y-1].append(x-1)
def b(r,v):return sum((r!=i)and(a[v]>a[i])and(not(b(v,i)))for i in e[v])
print(*[i+1for i in range(n)if b(n,i)])
``` | output | 1 | 106,002 | 13 | 212,005 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output
Submitted Solution:
```
n = int(input().strip())
a = [int(x) for x in input().strip().split()]
flg = [-1 for i in range(n)]
b = []
l = [[] for i in range(n)]
for i in range(n - 1):
b.append([int(x) - 1 for x in input().strip().split()])
for x in b:
l[x[0]].append(x[1])
l[x[1]].append(x[0])
while True:
minimum = a[0]
idx = []
for i, x in enumerate(a):
if flg[i] != -1 or x > minimum:
continue
if x < minimum:
minimum = x
idx =[i]
else:
idx.append(i)
while True:
w = []
for i in idx:
flg[i] = 0
for x in l[i]:
if flg[x] == -1 and a[x] != a[i]:
flg[x] = 1
w.append(x)
idx = []
for i in w:
for x in l[i]:
if flg[x] == -1:
flg[x] = 0
for y in l[x]:
if flg[y] == -1 and a[x] > a[y]:
flg[x] = -1
break
if flg[x] == 0:
idx.append(x)
if len(idx) == 0:
break
if -1 not in flg:
break
sep = ''
s = ''
for i, x in enumerate(flg):
if x == 1:
s += sep + str(i + 1)
sep = ' '
print(s)
``` | instruction | 0 | 106,003 | 13 | 212,006 |
No | output | 1 | 106,003 | 13 | 212,007 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output
Submitted Solution:
```
n = int(input())
a = list(map(int, input().split()))
g = [[] for _ in range(n)]
for _ in range(n - 1):
x, y = map(int, input().split())
g[x - 1].append(y - 1)
g[y - 1].append(x - 1)
res = [False] * n
for i in range(n):
for node in g[i]:
if a[i] > a[node]:
break
else:
res[i] = True
ans = []
for i in range(n):
if res[i]:
continue
s = [i]
d = [-1] * n
while s:
p = s.pop()
if d[p] == -1:
s.append(p)
d[p] = 0
for node in g[p]:
if d[node] == -1:
s.append(node)
else:
for node in g[p]:
if d[node] == 1:
d[p] = 2
break
else:
d[p] = 1
if d[i] == 2:
ans.append(i + 1)
print(' '.join(map(str, ans)))
``` | instruction | 0 | 106,004 | 13 | 212,008 |
No | output | 1 | 106,004 | 13 | 212,009 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
n = int(input())
stone = [0]+list(map(int,input().split()))
ab = [list(map(int,input().split())) for i in range(n-1)]
graph = [[] for i in range(n+1)]
deg = [0]*(n+1)
for a,b in ab:
if stone[a] < stone[b]:
graph[a].append(b)
deg[b] += 1
elif stone[a] > stone[b]:
graph[b].append(a)
deg[a] += 1
que = deque()
dp = [-1]*(n+1)
ans = []
for i in range(1,n+1):
if deg[i] == 0:
que.append(i)
dp[i] = 0
while que:
x = que.popleft()
for y in graph[x]:
if dp[y] == -1:
dp[y] = dp[x]+1
if dp[y]%2:
ans.append(y)
que.append(y)
ans.sort()
print(*ans)
``` | instruction | 0 | 106,005 | 13 | 212,010 |
No | output | 1 | 106,005 | 13 | 212,011 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
There is a tree with N vertices, numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i.
Currently, there are A_i stones placed on vertex i. Takahashi and Aoki will play a game using this tree.
First, Takahashi will select a vertex and place a piece on it. Then, starting from Takahashi, they will alternately perform the following operation:
* Remove one stone from the vertex currently occupied by the piece.
* Then, move the piece to a vertex that is adjacent to the currently occupied vertex.
The player who is left with no stone on the vertex occupied by the piece and thus cannot perform the operation, loses the game. Find all the vertices v such that Takahashi can place the piece on v at the beginning and win the game.
Constraints
* 2 ≦ N ≦ 3000
* 1 ≦ a_i,b_i ≦ N
* 0 ≦ A_i ≦ 10^9
* The given graph is a tree.
Input
The input is given from Standard Input in the following format:
N
A_1 A_2 … A_N
a_1 b_1
:
a_{N-1} b_{N-1}
Output
Print the indices of the vertices v such that Takahashi can place the piece on v at the beginning and win the game, in a line, in ascending order.
Examples
Input
3
1 2 3
1 2
2 3
Output
2
Input
5
5 4 1 2 3
1 2
1 3
2 4
2 5
Output
1 2
Input
3
1 1 1
1 2
2 3
Output
Submitted Solution:
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from fractions import gcd
def readln():
_res = list(map(int,str(input()).split(' ')))
return _res
def calc(x,line):
if line == 0:
for l in v[x]:
if e[l][0] == x: son = e[l][1]
else: son = e[l][0]
if a[son-1] < a[x-1] and calc(son,l) == -1:
return 1
return -1
else:
if e[line][0] == x: y = 0
else: y = 1
if f[x][y] != 0: return f[x][y]
if len(v[x]) == 1:
f[x][y] = -1
return -1
for l in v[x]:
if l != line:
if e[l][0] == x: son = e[l][1]
else: son = e[l][0]
if a[son-1] < a[x-1] and calc(son,l) == -1:
f[x][y] = 1
return 1
f[x][y] = -1
return -1
n = int(input())
v = [set([]) for i in range(0,n+1)]
e = [0 for i in range(0,n)]
a = readln()
for i in range(1,n):
s = readln()
v[s[0]].add(i)
v[s[1]].add(i)
e[i] = s
f = [[0,0] for i in range(0,n)]
ans = []
for i in range(1,n+1):
if calc(i,0) == 1:
ans.append(i)
ans = list(map(str,ans))
print(' '.join(ans))
``` | instruction | 0 | 106,006 | 13 | 212,012 |
No | output | 1 | 106,006 | 13 | 212,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1.
You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.
Input
The first line contains a single integer n (2 ≤ n ≤ 5 ⋅ 10^5) – the number of vertices of the tree.
Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 ≤ u_i, v_i ≤ n) meaning that there is an edge between vertices u_i and v_i.
It is guaranteed that the given graph is tree.
Output
Output a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.
Examples
Input
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
Note
Consider the first example.
* The only maximum almost-1-uniform set is \{1, 2, 3, 4\}.
* One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}.
* A maximum almost-3-uniform set is any pair of vertices on distance 3.
* Any single vertex is an almost-k-uniform set for k ≥ 1.
In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}.
Submitted Solution:
```
def almost_same_distance(n,adj,edges):
max_deg =max_degree(adj)
result = [max_deg+1]
for k in range(2,n+1):
max = find_almost_k_uniform(n,k,adj,edges)
result.append(max)
return result
def find_almost_k_uniform(n,k,adj,edges):
max_len = 0
if k % 2 == 1:
max_len = find_k_odd(n,k,adj,edges)
else:
max_len = find_k_even(n,k,adj,edges)
return max_len
def find_k_odd(n,k,adj,edges):
d_s = {}
max_len = 0
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
l = k//2
for v in range(1,n+1):
r = {i:-1 for i in range(1,n+1)}
#buscar un vertice de longitud l o l+1 por subarbol
depth,subtree = d_s[v]
for w in range(1,n+1):
if depth[w] == l+1:
r[subtree[w]] = l+1
if depth[w] == l and r[subtree[w]] == -1:
r[subtree[w]] = l
len_r = 0
found_l = False
for t in r.values():
if t != -1:
if t == l and not found_l:
len_r += 1
found_l =True
elif t== l+1:
len_r += 1
if len_r > max_len:
max_len = len_r
return max_len
def find_k_even(n,k,adj,edges):
d_s = {}
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
max_len = 0
l = k/2
for v in range(1,n+1):
depth,subtree = d_s[v]
r = {}
for w in range(1,n+1):
if depth[w] == l:
r[subtree[w]] = w
if len(r) > max_len:
max_len = len(r)
#print("max_lena vert--", max_len)
for e in edges:#O(n-1)
u = e[0]
v = e[1]
r_u = {}
r_v = {}
depth_u,subtree_u = bfs(n,u,adj,v)#O(n-1)
depth_v,subtree_v = bfs(n,v,adj,u)
#print(e)
#print("u--",depth_u,"--",subtree_u)
#print("v--",depth_v,"--",subtree_v)
for w in range(1,n+1):#O(n-1)
if depth_u[w] == l:
r_u[subtree_u[w]] = w
for w in range(1,n+1):#O(n-1)
if depth_v[w] == l:
r_v[subtree_v[w]] = w
t = len(r_u) + len(r_v)
if t > max_len:
max_len = t
#print("edge",e,"---",max_len)
#print("max_lena vert--", max_len)
return max_len
def bfs(n,x,adj,y=-1):
#depth[x]: longitud camino entre el vertice inicial y x
visited = [False for i in range(n+1)]
visited [x] = True
depth = [-1 for _ in range(n+1)]
subtree = [-1 for _ in range(n+1)]
if y!=-1:
visited[y] =True
q = [x]
depth[x] = 0
for w in adj[x]:
subtree[w] = w
while len(q) > 0:
v = q[0]
q.remove(v)
for w in adj[v]:
if not visited[w]:
q.append(w)
depth[w] = depth[v] + 1
if v!= x:
subtree[w] = subtree[v]
visited[w] = True
return depth,subtree
def max_degree(adj):
m_d = 0
for x in adj:
x_degree = len(x)
if m_d < x_degree:
m_d = x_degree
return m_d
def main():
n= int(input())
adj = [[]for i in range(n+1)]
edges = []
for _ in range(n-1):
x,y = [ int(i) for i in input().split()]
edges.append((x,y))
adj[x].append(y)
adj[y].append(x)
max_len = almost_same_distance(n,adj,edges)
print(' '.join(str(i) for i in max_len))
main()
``` | instruction | 0 | 106,253 | 13 | 212,506 |
No | output | 1 | 106,253 | 13 | 212,507 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1.
You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.
Input
The first line contains a single integer n (2 ≤ n ≤ 5 ⋅ 10^5) – the number of vertices of the tree.
Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 ≤ u_i, v_i ≤ n) meaning that there is an edge between vertices u_i and v_i.
It is guaranteed that the given graph is tree.
Output
Output a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.
Examples
Input
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
Note
Consider the first example.
* The only maximum almost-1-uniform set is \{1, 2, 3, 4\}.
* One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}.
* A maximum almost-3-uniform set is any pair of vertices on distance 3.
* Any single vertex is an almost-k-uniform set for k ≥ 1.
In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}.
Submitted Solution:
```
v = int(input())
graph = dict.fromkeys(range(1, v+1))
for _ in range(v-1):
key, value = map(int, input().split())
try:
graph[key].append(value)
except AttributeError:
graph[key] = [value]
try:
graph[value].append(key)
except AttributeError:
graph[value] = [key]
def dfs(graph, key, search_level):
stack = [(key, 0)]
vertex_set = set()
vertex_set.add(key)
visited = set()
visited.add(key)
while len(stack) > 0:
current, level = stack.pop()
if level == search_level or level == search_level+1:
vertex_set.add(current)
for i in graph[current]:
if i not in visited:
stack.append((i, level+1))
visited.add(i)
return vertex_set
n = 1
from functools import reduce
from itertools import combinations
redu = reduce
comb = combinations
for i in range(v):
current_result = {}
max_set_len = 0
for j in graph.keys():
current_result[j] = dfs(graph, j, n)
for key in graph.keys():
sizes = len(current_result[key])+1
for size in range(2, sizes):
for c in comb(current_result[key], size):
length = len(redu(set.intersection, [current_result[j] for j in c]))
if length > max_set_len and length == len(c):
max_set_len = length
n += 1
print(max_set_len if max_set_len > 0 else 1, end=' ')
``` | instruction | 0 | 106,254 | 13 | 212,508 |
No | output | 1 | 106,254 | 13 | 212,509 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1.
You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.
Input
The first line contains a single integer n (2 ≤ n ≤ 5 ⋅ 10^5) – the number of vertices of the tree.
Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 ≤ u_i, v_i ≤ n) meaning that there is an edge between vertices u_i and v_i.
It is guaranteed that the given graph is tree.
Output
Output a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.
Examples
Input
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
Note
Consider the first example.
* The only maximum almost-1-uniform set is \{1, 2, 3, 4\}.
* One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}.
* A maximum almost-3-uniform set is any pair of vertices on distance 3.
* Any single vertex is an almost-k-uniform set for k ≥ 1.
In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}.
Submitted Solution:
```
def almost_same_distance(n,adj,edges):
max_deg =max_degree(adj)
result = [max_deg+1]
#max = find_almost_k_uniform(n,3,adj,edges)
#print(4,"--->",max)
for k in range(2,n+1):
max = find_almost_k_uniform(n,k,adj,edges)
result.append(max)
return result
def find_almost_k_uniform(n,k,adj,edges):
max_len = 0
if k % 2 == 1:
max_len = find_k_odd(n,k,adj,edges)
else:
max_len = find_k_even(n,k,adj,edges)
return max_len
def find_k_odd(n,k,adj,edges):
d_s = {}
max_len = 0
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
l = k//2
for v in range(1,n+1):
r = {i:-1 for i in range(1,n+1)}
#buscar un vertice de longitud l o l+1 por subarbol
depth,subtree = d_s[v]
for w in range(1,n+1):
if depth[w] == l+1:
r[subtree[w]] = l+1
if depth[w] == l and r[subtree[w]] == -1:
r[subtree[w]] = l
len_r = 0
found_l = False
for t in r.values():
if t != -1:
if t == l and not found_l:
len_r += 1
found_l =True
elif t== l+1:
len_r += 1
if len_r > max_len:
max_len = len_r
return max_len
def find_k_even(n,k,adj,edges):
d_s = {}
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
max_len = 0
l = k/2
for v in range(1,n+1):
depth,subtree = d_s[v]
r = {}
for w in range(1,n+1):
if depth[w] == l:
r[subtree[w]] = w
if len(r) > max_len:
max_len = len(r)
#print("max_lena vert--", max_len)
for e in edges:#O(n-1)
u = e[0]
v = e[1]
r_u = {}
r_v = {}
depth_u,subtree_u = bfs(n,u,adj,v)#O(n-1)
depth_v,subtree_v = bfs(n,v,adj,u)
#print(e)
#print("u--",depth_u,"--",subtree_u)
#print("v--",depth_v,"--",subtree_v)
for w in range(1,n+1):#O(n-1)
if depth_u[w] == l:
r_u[subtree_u[w]] = w
for w in range(1,n+1):#O(n-1)
if depth_v[w] == l:
r_v[subtree_v[w]] = w
t = len(r_u) + len(r_v)
if t > max_len:
max_len = t
#print("edge",e,"---",max_len)
#print("max_lena vert--", max_len)
return max_len
def bfs(n,x,adj,y=-1):
#depth[x]: longitud camino entre el vertice inicial y x
visited = [False for i in range(n+1)]
visited [x] = True
depth = [-1 for _ in range(n+1)]
subtree = [-1 for _ in range(n+1)]
if y!=-1:
visited[y] =True
q = [x]
depth[x] = 0
for w in adj[x]:
subtree[w] = w
while len(q) > 0:
v = q[0]
q.remove(v)
for w in adj[v]:
if not visited[w]:
q.append(w)
depth[w] = depth[v] + 1
if v!= x:
subtree[w] = subtree[v]
visited[w] = True
return depth,subtree
def max_degree(adj):
m_d = 0
for x in adj:
x_degree = len(x)
if m_d < x_degree:
m_d = x_degree
return m_d
def main():
n= int(input())
adj = [[]for i in range(n+1)]
edges = []
for _ in range(n-1):
x,y = [ int(i) for i in input().split()]
edges.append((x,y))
adj[x].append(y)
adj[y].append(x)
max_len = almost_same_distance(n,adj,edges)
print(' '.join(str(i) for i in max_len))
main()
``` | instruction | 0 | 106,255 | 13 | 212,510 |
No | output | 1 | 106,255 | 13 | 212,511 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let G be a simple graph. Let W be a non-empty subset of vertices. Then W is almost-k-uniform if for each pair of distinct vertices u,v ∈ W the distance between u and v is either k or k+1.
You are given a tree on n vertices. For each i between 1 and n, find the maximum size of an almost-i-uniform set.
Input
The first line contains a single integer n (2 ≤ n ≤ 5 ⋅ 10^5) – the number of vertices of the tree.
Then n-1 lines follows, the i-th of which consisting of two space separated integers u_i, v_i (1 ≤ u_i, v_i ≤ n) meaning that there is an edge between vertices u_i and v_i.
It is guaranteed that the given graph is tree.
Output
Output a single line containing n space separated integers a_i, where a_i is the maximum size of an almost-i-uniform set.
Examples
Input
5
1 2
1 3
1 4
4 5
Output
4 3 2 1 1
Input
6
1 2
1 3
1 4
4 5
4 6
Output
4 4 2 1 1 1
Note
Consider the first example.
* The only maximum almost-1-uniform set is \{1, 2, 3, 4\}.
* One of the maximum almost-2-uniform sets is or \{2, 3, 5\}, another one is \{2, 3, 4\}.
* A maximum almost-3-uniform set is any pair of vertices on distance 3.
* Any single vertex is an almost-k-uniform set for k ≥ 1.
In the second sample there is an almost-2-uniform set of size 4, and that is \{2, 3, 5, 6\}.
Submitted Solution:
```
def almost_same_distance(n,adj,edges):
max_deg =max_degree(adj)
result = [max_deg+1]
for k in range(2,n+1):
max = find_almost_k_uniform(n,k,adj,edges)
result.append(max)
return result
def find_almost_k_uniform(n,k,adj,edges):
max_len = 0
if k % 2 == 1:
max_len = find_k_odd(n,k,adj,edges)
else:
max_len = find_k_even(n,k,adj,edges)
return max_len
def find_k_odd(n,k,adj,edges):
d_s = {}
max_len = 0
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
l = k//2
for v in range(1,n+1):
r = {i:-1 for i in range(1,n+1)}
#buscar un vertice de longitud l o l+1 por subarbol
depth,subtree = d_s[v]
for w in range(1,n+1):
if depth[w] == l+1:
r[subtree[w]] = l+1
if depth[w] == l and r[subtree[w]] == -1:
r[subtree[w]] = l
len_r = 0
found_l = False
for t in r.values():
if t != -1:
if t == l and not found_l:
len_r += 1
found_l =True
elif t== l+1:
len_r += 1
if len_r > max_len:
max_len = len_r
print(r)
return max_len
def find_k_even(n,k,adj,edges):
d_s = {}
for v in range(1,n+1):
d_s[v] = bfs(n,v,adj)
max_len = 0
l = k/2
for v in range(1,n+1):
depth,subtree = d_s[v]
r = {}
for w in range(1,n+1):
if depth[w] == l:
r[subtree[w]] = w
if len(r) > max_len:
max_len = len(r)
#print("max_lena vert--", max_len)
for e in edges:#O(n-1)
u = e[0]
v = e[1]
r_u = {}
r_v = {}
depth_u,subtree_u = bfs(n,u,adj,v)#O(n-1)
depth_v,subtree_v = bfs(n,v,adj,u)
#print(e)
#print("u--",depth_u,"--",subtree_u)
#print("v--",depth_v,"--",subtree_v)
for w in range(1,n+1):#O(n-1)
if depth_u[w] == l:
r_u[subtree_u[w]] = w
for w in range(1,n+1):#O(n-1)
if depth_v[w] == l:
r_v[subtree_v[w]] = w
t = len(r_u) + len(r_v)
if t > max_len:
max_len = t
#print("edge",e,"---",max_len)
#print("max_lena vert--", max_len)
return max_len
def bfs(n,x,adj,y=-1):
#depth[x]: longitud camino entre el vertice inicial y x
visited = [False for i in range(n+1)]
visited [x] = True
depth = [-1 for _ in range(n+1)]
subtree = [-1 for _ in range(n+1)]
if y!=-1:
visited[y] =True
q = [x]
depth[x] = 0
for w in adj[x]:
subtree[w] = w
while len(q) > 0:
v = q[0]
q.remove(v)
for w in adj[v]:
if not visited[w]:
q.append(w)
depth[w] = depth[v] + 1
if v!= x:
subtree[w] = subtree[v]
visited[w] = True
return depth,subtree
def max_degree(adj):
m_d = 0
for x in adj:
x_degree = len(x)
if m_d < x_degree:
m_d = x_degree
return m_d
def main():
n= int(input())
adj = [[]for i in range(n+1)]
edges = []
for _ in range(n-1):
x,y = [ int(i) for i in input().split()]
edges.append((x,y))
adj[x].append(y)
adj[y].append(x)
max_len = almost_same_distance(n,adj,edges)
print(' '.join(str(i) for i in max_len))
main()
``` | instruction | 0 | 106,256 | 13 | 212,512 |
No | output | 1 | 106,256 | 13 | 212,513 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for. | instruction | 0 | 106,677 | 13 | 213,354 |
Tags: data structures, dfs and similar
Correct Solution:
```
from collections import deque
nodes = []
parents = []
values = []
broken = []
upperBound = []
lowerBound = []
n = int(input())
for _ in range(n):
v, l, r = map(int, input().split())
nodes.append((v, l - 1, r - 1))
parents.append(-1)
values.append(v)
broken.append(False)
upperBound.append(10 ** 9)
lowerBound.append(-10 ** 9)
for i, (v, l, r) in enumerate(nodes):
if l > -1:
parents[l] = i
if r > -1:
parents[r] = i
root = -1
for i in range(n):
if parents[i] == -1:
root = i
proc = deque([root])
while len(proc) > 0:
node = proc.popleft()
v, l, r = nodes[node]
if l > -1:
proc.append(l)
upperBound[l] = min(upperBound[node], v)
lowerBound[l] = lowerBound[node]
if not (lowerBound[l] <= nodes[l][0] <= upperBound[l]):
broken[l] = True
if r > -1:
proc.append(r)
upperBound[r] = upperBound[node]
lowerBound[r] = max(lowerBound[node], v)
if not (lowerBound[r] <= nodes[r][0] <= upperBound[r]):
broken[r] = True
s = set([])
for v, b in zip(values, broken):
if not b:
s.add(v)
ans = 0
for v in values:
if v not in s:
ans += 1
print(ans)
``` | output | 1 | 106,677 | 13 | 213,355 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for. | instruction | 0 | 106,678 | 13 | 213,356 |
Tags: data structures, dfs and similar
Correct Solution:
```
#!/usr/bin/env python3
# solution after hint:(
# though it was not necessary
# reduced recursion version
n = int(input().strip())
vlrs = [tuple(map(int, input().strip().split())) for _ in range(n)]
# shift numeration
vlrs = [(v, l - (0 if l < 0 else 1), r - (0 if r < 0 else 1)) for v, l, r in vlrs]
isroot = [True for _ in range(n)]
for v, l, r in vlrs:
if l != -1:
isroot[l] = False
if r != -1:
isroot[r] = False
root = isroot.index(True)
vs = [v for v, l, r in vlrs]
vmin = min(vs)
vmax = max(vs)
found = set()
def DFS(U, vl, vr):
while vlrs[U].count(-1) == 1:
v, L, R = vlrs[U]
if vl <= v <= vr:
found.add(v)
if L != -1:
U, vl, vr = L, vl, min(v, vr)
else:
U, vl, vr = R, max(v, vl), vr
v, L, R = vlrs[U]
if vl <= v <= vr:
found.add(v)
if L != -1 and R != -1:
DFS(L, vl, min(v, vr))
DFS(R, max(v, vl), vr)
DFS(root, vmin, vmax)
res = sum(1 for v in vs if v not in found)
print (res)
``` | output | 1 | 106,678 | 13 | 213,357 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for. | instruction | 0 | 106,679 | 13 | 213,358 |
Tags: data structures, dfs and similar
Correct Solution:
```
import sys
from collections import Counter
n = int(sys.stdin.buffer.readline().decode('utf-8'))
parent = [-1]*n
value = [0]*n
left, right = [-1]*n, [-1]*n
for i, (v, l, r) in enumerate(map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
value[i] = v
if l != -1:
left[i] = l-1
parent[l-1] = i
if r != -1:
right[i] = r-1
parent[r-1] = i
root = parent.index(-1)
stack = [(root, -1, 10**9+10)]
cnt_v = Counter()
cnt_ok = Counter()
while stack:
i, lb, ub = stack.pop()
cnt_v[value[i]] += 1
if lb < value[i] < ub:
cnt_ok[value[i]] = 1
if left[i] != -1:
stack.append((left[i], lb, min(ub, value[i])))
if right[i] != -1:
stack.append((right[i], max(lb, value[i]), ub))
ans = 0
for k, v in cnt_v.items():
if cnt_ok[k] == 0:
ans += v
print(ans)
``` | output | 1 | 106,679 | 13 | 213,359 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
Submitted Solution:
```
#! /bin/python
n = int(input())
tab = []
questions = []
root = -1
V = []
noRoot = []
maxi = 0
mini = 0
for i in range(n):
v, l, r = map(int, input().split())
v, l, r = v - 1, l - 1, r - 1
V.append({'v': v, 'l': l, 'r': r})
if l != -2:
noRoot.append(l)
if r != -2:
noRoot.append(r)
questions.append(v)
if i == 0:
maxi = v
mini = v
maxi = max(maxi, v)
mini = min(mini, v)
for i in range(len(questions)):
if i not in noRoot:
root = i
break
def dfs(i, a, b):
v = V[i]['v']
l = V[i]['l']
r = V[i]['r']
fail = 1 if not (a <= v and v + 1 < b) else 0
failL, failR = 0, 0
if l != -2:
failL = dfs(l, a, v)
if r != -2:
failR = dfs(r, v, b)
return failL + failR + fail
print(dfs(root, mini, maxi + 1))
``` | instruction | 0 | 106,680 | 13 | 213,360 |
No | output | 1 | 106,680 | 13 | 213,361 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
Submitted Solution:
```
import sys
n = int(sys.stdin.buffer.readline().decode('utf-8'))
parent = [-1]*n
value = [0]*n
left, right = [-1]*n, [-1]*n
for i, (v, l, r) in enumerate(map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer):
value[i] = v
if l != -1:
left[i] = l-1
parent[l-1] = i
if r != -1:
right[i] = r-1
parent[r-1] = i
root = parent.index(-1)
stack = [(root, -1, 10**9+10)]
ans = 0
while stack:
i, lb, ub = stack.pop()
if not (lb < value[i] < ub):
ans += 1
if left[i] != -1:
stack.append((left[i], lb, min(ub, value[i])))
if right[i] != -1:
stack.append((right[i], max(lb, value[i]), ub))
print(ans)
``` | instruction | 0 | 106,681 | 13 | 213,362 |
No | output | 1 | 106,681 | 13 | 213,363 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
Submitted Solution:
```
#! /bin/python
n = int(input())
tab = []
questions = []
root = -1
V = []
noRoot = []
maxi = 0
mini = 0
for i in range(n):
v, l, r = map(int, input().split())
v, l, r = v, l - 1, r - 1
V.append({'v': v, 'l': l, 'r': r})
if l != -2:
noRoot.append(l)
if r != -2:
noRoot.append(r)
questions.append(v)
if i == 0:
maxi = v
mini = v
maxi = max(maxi, v)
mini = min(mini, v)
for i in range(n):
if i not in noRoot:
root = i
break
def dfs(i, a, b):
if i == -2:
return 0
v = V[i]['v']
l = V[i]['l']
r = V[i]['r']
fail = 1 if not (a <= v and v < b) else 0
fail += dfs(l, a, v)
fail += dfs(r, v, b + 1)
return fail
print(dfs(root, mini, maxi))
``` | instruction | 0 | 106,682 | 13 | 213,364 |
No | output | 1 | 106,682 | 13 | 213,365 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Let T be arbitrary binary tree — tree, every vertex of which has no more than two children. Given tree is rooted, so there exists only one vertex which doesn't have a parent — it's the root of a tree. Every vertex has an integer number written on it. Following algorithm is run on every value from the tree T:
1. Set pointer to the root of a tree.
2. Return success if the value in the current vertex is equal to the number you are looking for
3. Go to the left child of the vertex if the value in the current vertex is greater than the number you are looking for
4. Go to the right child of the vertex if the value in the current vertex is less than the number you are looking for
5. Return fail if you try to go to the vertex that doesn't exist
Here is the pseudo-code of the described algorithm:
bool find(TreeNode t, int x) {
if (t == null)
return false;
if (t.value == x)
return true;
if (x < t.value)
return find(t.left, x);
else
return find(t.right, x);
}
find(root, x);
The described algorithm works correctly if the tree is binary search tree (i.e. for each node the values of left subtree are less than the value in the node, the values of right subtree are greater than the value in the node). But it can return invalid result if tree is not a binary search tree.
Since the given tree is not necessarily a binary search tree, not all numbers can be found this way. Your task is to calculate, how many times the search will fail being running on every value from the tree.
If the tree has multiple vertices with the same values on them then you should run algorithm on every one of them separately.
Input
First line contains integer number n (1 ≤ n ≤ 105) — number of vertices in the tree.
Each of the next n lines contains 3 numbers v, l, r (0 ≤ v ≤ 109) — value on current vertex, index of the left child of the vertex and index of the right child of the vertex, respectively. If some child doesn't exist then number - 1 is set instead. Note that different vertices of the tree may contain the same values.
Output
Print number of times when search algorithm will fail.
Examples
Input
3
15 -1 -1
10 1 3
5 -1 -1
Output
2
Input
8
6 2 3
3 4 5
12 6 7
1 -1 8
4 -1 -1
5 -1 -1
14 -1 -1
2 -1 -1
Output
1
Note
In the example the root of the tree in vertex 2. Search of numbers 5 and 15 will return fail because on the first step algorithm will choose the subtree which doesn't contain numbers you are looking for.
Submitted Solution:
```
#tree is a map of (index) -> (value, left child, right child)
#root is the index of the tree root
def brokenBST(tree, root):
to_visit = [(root, False, False)]
unreachable = 0
while len(to_visit) != 0:
current = to_visit.pop()
v, l, r = tree[current[0]]
if current[1] and not v < current[1]: #value lesser than minimum
unreachable += 1
elif current[2] and not v > current[2]: #value greater than maximum
unreachable += 1
if l != -1:
to_visit.append((l, v, current[2]))
if r != -1:
to_visit.append((r, current[1], v))
return unreachable
if __name__ == "__main__":
n = int(input())
tree = {}
root = set(range(1, n+1))
for i in range(1, n+1):
v, l, r = [int(x) for x in input().split(' ')]
if l in root:
root.remove(l)
if r in root:
root.remove(r)
tree[i] = (v, l, r)
print(brokenBST(tree, root.pop()))
``` | instruction | 0 | 106,683 | 13 | 213,366 |
No | output | 1 | 106,683 | 13 | 213,367 |
Provide a correct Python 3 solution for this coding contest problem.
Escape
An undirected graph with positive values at the vertices is given. The vertices are numbered from 1 to N, and the i-th vertex has a value of w_i. You can start from the first vertex and move on the graph with the constraint that you cannot pass the edge that you just passed. At each vertex, you can get the score of the value that the vertex has only when you visit it for the first time.
Find the maximum sum of the points you can get.
Constraints
* 1 ≤ N ≤ 100000
* N − 1 ≤ M ≤ 100000
* 1 ≤ w_i ≤ 1000
* 1 ≤ u_i, v_i ≤ N
* There are no multiple edges or self edges
* The graph is concatenated
Input Format
Input is given from standard input in the following format.
N M
w_1 w_2 ... w_N
u_1 v_1
u_2 v_2
...
u_M v_M
In the first line, the number of vertices N of the graph and the integer M representing the number of edges are entered.
The value w_i of each vertex is entered in the second line.
In addition, the number of the two vertices connected by each side is entered in the M line.
Output Format
Print the answer on one line.
Sample Input 1
6 6
1 2 3 4 5 6
1 2
twenty three
3 4
14
4 5
5 6
Sample Output 1
twenty one
<image>
You can collect the points of all vertices by going from vertices 1 → 2 → 3 → 4 → 5 → 6.
Sample Input 2
7 8
1 3 3 5 2 2 3
1 2
twenty three
3 1
14
1 7
1 5
1 6
5 6
Sample Output 2
16
<image>
You can collect 16 points by going from vertices 1 → 2 → 3 → 1 → 5 → 6 → 1 → 4.
Example
Input
6 6
1 2 3 4 5 6
1 2
2 3
3 4
1 4
4 5
5 6
Output
21 | instruction | 0 | 106,978 | 13 | 213,956 |
"Correct Solution:
```
# 前の提出は1が葉のときまずかったので再提出。
import sys
input = sys.stdin.readline
n,m=map(int,input().split())
W=[0]+list(map(int,input().split()))
E=[tuple(map(int,input().split())) for i in range(m)]
S=1
ELIST=[[] for i in range(n+1)]
EW=[0]*(n+1)
for x,y in E:
ELIST[x].append(y)
ELIST[y].append(x)
EW[x]+=1
EW[y]+=1
from collections import deque
Q=deque()
USED=[0]*(n+1)
for i in range(1,n+1):
if EW[i]==1 and i!=S:
USED[i]=1
Q.append(i)
EW[S]+=1<<50
USED[S]=1
while Q:
x=Q.pop()
EW[x]-=1
for to in ELIST[x]:
if USED[to]==1:
continue
EW[to]-=1
if EW[to]==1 and USED[to]==0:
Q.append(to)
USED[to]=1
#print(EW)
LOOP=[]
ANS=0
for i in range(1,n+1):
if EW[i]!=0:
ANS+=W[i]
LOOP.append(i)
SCORE=[0]*(n+1)
USED=[0]*(n+1)
for l in LOOP:
SCORE[l]=ANS
USED[l]=1
Q=deque(LOOP)
while Q:
x=Q.pop()
for to in ELIST[x]:
if USED[to]==1:
continue
SCORE[to]=W[to]+SCORE[x]
Q.append(to)
USED[to]=1
print(max(SCORE))
``` | output | 1 | 106,978 | 13 | 213,957 |
Provide a correct Python 3 solution for this coding contest problem.
Escape
An undirected graph with positive values at the vertices is given. The vertices are numbered from 1 to N, and the i-th vertex has a value of w_i. You can start from the first vertex and move on the graph with the constraint that you cannot pass the edge that you just passed. At each vertex, you can get the score of the value that the vertex has only when you visit it for the first time.
Find the maximum sum of the points you can get.
Constraints
* 1 ≤ N ≤ 100000
* N − 1 ≤ M ≤ 100000
* 1 ≤ w_i ≤ 1000
* 1 ≤ u_i, v_i ≤ N
* There are no multiple edges or self edges
* The graph is concatenated
Input Format
Input is given from standard input in the following format.
N M
w_1 w_2 ... w_N
u_1 v_1
u_2 v_2
...
u_M v_M
In the first line, the number of vertices N of the graph and the integer M representing the number of edges are entered.
The value w_i of each vertex is entered in the second line.
In addition, the number of the two vertices connected by each side is entered in the M line.
Output Format
Print the answer on one line.
Sample Input 1
6 6
1 2 3 4 5 6
1 2
twenty three
3 4
14
4 5
5 6
Sample Output 1
twenty one
<image>
You can collect the points of all vertices by going from vertices 1 → 2 → 3 → 4 → 5 → 6.
Sample Input 2
7 8
1 3 3 5 2 2 3
1 2
twenty three
3 1
14
1 7
1 5
1 6
5 6
Sample Output 2
16
<image>
You can collect 16 points by going from vertices 1 → 2 → 3 → 1 → 5 → 6 → 1 → 4.
Example
Input
6 6
1 2 3 4 5 6
1 2
2 3
3 4
1 4
4 5
5 6
Output
21 | instruction | 0 | 106,979 | 13 | 213,958 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
def solve():
readline = sys.stdin.readline
write = sys.stdout.write
N, M = map(int, readline().split())
*W, = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
U = [0]*N
L = [0]*N
D = [0]*N
R = [0]*N
U[0] = 1
stk = [0]
it = [0]*N
while stk:
v = stk[-1]
p = stk[-2] if len(stk) > 1 else -1
if it[v] == 0:
U[v] = 1
else:
w = G[v][it[v]-1]
D[v] = max(D[v], D[w])
if L[w]:
L[v] = 1
while it[v] < len(G[v]):
w = G[v][it[v]]; it[v] += 1
if U[w]:
if w != p:
L[v] = 1
continue
U[w] = 1
stk.append(w)
break
else:
D[v] = D[v] + W[v]
stk.pop()
ans = su = 0
for i in range(N):
if L[i]:
ans += W[i]
else:
su = max(su, D[i])
write("%d\n" % (ans + su))
solve()
``` | output | 1 | 106,979 | 13 | 213,959 |
Provide a correct Python 3 solution for this coding contest problem.
Escape
An undirected graph with positive values at the vertices is given. The vertices are numbered from 1 to N, and the i-th vertex has a value of w_i. You can start from the first vertex and move on the graph with the constraint that you cannot pass the edge that you just passed. At each vertex, you can get the score of the value that the vertex has only when you visit it for the first time.
Find the maximum sum of the points you can get.
Constraints
* 1 ≤ N ≤ 100000
* N − 1 ≤ M ≤ 100000
* 1 ≤ w_i ≤ 1000
* 1 ≤ u_i, v_i ≤ N
* There are no multiple edges or self edges
* The graph is concatenated
Input Format
Input is given from standard input in the following format.
N M
w_1 w_2 ... w_N
u_1 v_1
u_2 v_2
...
u_M v_M
In the first line, the number of vertices N of the graph and the integer M representing the number of edges are entered.
The value w_i of each vertex is entered in the second line.
In addition, the number of the two vertices connected by each side is entered in the M line.
Output Format
Print the answer on one line.
Sample Input 1
6 6
1 2 3 4 5 6
1 2
twenty three
3 4
14
4 5
5 6
Sample Output 1
twenty one
<image>
You can collect the points of all vertices by going from vertices 1 → 2 → 3 → 4 → 5 → 6.
Sample Input 2
7 8
1 3 3 5 2 2 3
1 2
twenty three
3 1
14
1 7
1 5
1 6
5 6
Sample Output 2
16
<image>
You can collect 16 points by going from vertices 1 → 2 → 3 → 1 → 5 → 6 → 1 → 4.
Example
Input
6 6
1 2 3 4 5 6
1 2
2 3
3 4
1 4
4 5
5 6
Output
21 | instruction | 0 | 106,980 | 13 | 213,960 |
"Correct Solution:
```
def find(x):
if par[x] == x:
return x
else:
par[x] = find(par[x])
return par[x]
def union(x, y):
par_x = find(x)
par_y = find(y)
if rank[par_x] < rank[par_y]:
par[par_x] = par_y
w[par_y]+=w[par_x]
else:
par[par_y] = par_x
w[par_x]+=w[par_y]
if rank[par_x] == rank[par_y]:
rank[par_x] += 1
def same(x, y):
return find(x)==find(y)
def dfs(cur, prev):
if visited[cur] or cur!=find(cur):
while len(path)>0:
union(0, path.pop())
return
visited[cur] = 1
path.append(cur)
for to in graph[cur]:
if to==prev:
continue
dfs(to, cur)
visited[cur] = 0
if len(path)>0 and path[-1]==cur:
path.pop()
def dfs2(cur):
visited[cur] = 1
ret = 0
for i in range(len(graph2[cur])):
for ele in graph[graph2[cur][i]]:
if visited[find(ele)] == 0:
ret = max(ret, dfs2(find(ele)))
return ret+w[find(cur)]
import sys
from collections import defaultdict
sys.setrecursionlimit(1000000)
n, m = map(int, input().split())
w = [0]
w.extend(list(map(int, input().split())))
graph = defaultdict(list)
for _ in range(m):
u, v = map(int, input().split())
graph[u].append(v)
graph[v].append(u)
path = []
graph2 = [[] for _ in range(n+1)]
visited = [0]*(n+1)
par = [i for i in range(n+1)]
rank = [0]*(n+1)
dfs(1, -1)
for i in range(1, n+1):
graph2[find(i)].append(i)
print(dfs2(find(1)))
``` | output | 1 | 106,980 | 13 | 213,961 |
Provide a correct Python 3 solution for this coding contest problem.
Mr. Endo wanted to write the code that performs breadth-first search (BFS), which is a search algorithm to explore all vertices on an undirected graph. An example of pseudo code of BFS is as follows:
1: $current \leftarrow \{start\_vertex\}$
2: $visited \leftarrow current$
3: while $visited \ne $ the set of all the vertices
4: $found \leftarrow \{\}$
5: for $v$ in $current$
6: for each $u$ adjacent to $v$
7: $found \leftarrow found \cup\{u\}$
8: $current \leftarrow found \setminus visited$
9: $visited \leftarrow visited \cup found$
However, Mr. Endo apparently forgot to manage visited vertices in his code. More precisely, he wrote the following code:
1: $current \leftarrow \{start\_vertex\}$
2: while $current \ne $ the set of all the vertices
3: $found \leftarrow \{\}$
4: for $v$ in $current$
5: for each $u$ adjacent to $v$
6: $found \leftarrow found \cup \{u\}$
7: $current \leftarrow found$
You may notice that for some graphs, Mr. Endo's program will not stop because it keeps running infinitely. Notice that it does not necessarily mean the program cannot explore all the vertices within finite steps. See example 2 below for more details.Your task here is to make a program that determines whether Mr. Endo's program will stop within finite steps for a given graph in order to point out the bug to him. Also, calculate the minimum number of loop iterations required for the program to stop if it is finite.
Input
The input consists of a single test case formatted as follows.
$N$ $M$
$U_1$ $V_1$
...
$U_M$ $V_M$
The first line consists of two integers $N$ ($2 \leq N \leq 100,000$) and $M$ ($1 \leq M \leq 100,000$), where $N$ is the number of vertices and $M$ is the number of edges in a given undirected graph, respectively. The $i$-th line of the following $M$ lines consists of two integers $U_i$ and $V_i$ ($1 \leq U_i, V_i \leq N$), which means the vertices $U_i$ and $V_i$ are adjacent in the given graph. The vertex 1 is the start vertex, i.e. $start\\_vertex$ in the pseudo codes. You can assume that the given graph also meets the following conditions.
* The graph has no self-loop, i.e., $U_i \ne V_i$ for all $1 \leq i \leq M$.
* The graph has no multi-edge, i.e., $\\{Ui,Vi\\} \ne \\{U_j,V_j\\}$ for all $1 \leq i < j \leq M$.
* The graph is connected, i.e., there is at least one path from $U$ to $V$ (and vice versa) for all vertices $1 \leq U, V \leq N$
Output
If Mr. Endo's wrong BFS code cannot stop within finite steps for the given input graph, print -1 in a line. Otherwise, print the minimum number of loop iterations required to stop.
Examples
Input
3 3
1 2
1 3
2 3
Output
2
Input
4 3
1 2
2 3
3 4
Output
-1
Input
4 4
1 2
2 3
3 4
4 1
Output
-1
Input
8 9
2 1
3 5
1 6
2 5
3 1
8 4
2 7
7 1
7 4
Output
3 | instruction | 0 | 106,981 | 13 | 213,962 |
"Correct Solution:
```
from collections import deque
import sys
readline = sys.stdin.readline
write = sys.stdout.write
def solve():
N, M = map(int, readline().split())
G = [[] for i in range(N)]
for i in range(M):
u, v = map(int, readline().split())
G[u-1].append(v-1)
G[v-1].append(u-1)
cnts = [1, 0]
dist = [[-1]*N for i in range(2)]
dist[0][0] = 0
que = deque([(0, 0)])
while que:
v, t = que.popleft()
t1 = t^1
dist1 = dist[t^1]
d1 = dist[t][v]+1
for w in G[v]:
if dist1[w] != -1:
continue
dist1[w] = d1
que.append((w, t1))
cnts[t1] += 1
if cnts[t1] == N:
write("%d\n" % d1)
break
else:
continue
break
else:
write("-1\n")
solve()
``` | output | 1 | 106,981 | 13 | 213,963 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.