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.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6; 1 ≤ c_i ≤ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
Submitted Solution:
```
from collections import deque
import sys
input = sys.stdin.readline
def bfs(r):
q = deque()
q.append(r)
visit = [0] * (n + 1)
visit[r] = 1
parent = [-1] * (n + 1)
p = []
e = [-1] * (n - 1)
cnt = [1] * (n + 1)
while q:
i = q.popleft()
for j, c in G[i]:
if not visit[j]:
q.append(j)
visit[j] = 1
parent[j] = i
p.append(j)
e[c] = j
cnt[i] = 0
while p:
i = p.pop()
j = parent[i]
cnt[j] += cnt[i]
return cnt, e
t = int(input())
inf = 114514
for _ in range(t):
n, s = map(int, input().split())
G = [[] for _ in range(n + 1)]
x, y = [], []
for i in range(n - 1):
u, v, w, c = map(int, input().split())
G[u].append((v, i))
G[v].append((u, i))
x.append(w)
y.append(c)
cnt, e = bfs(1)
a, b = [-inf, -inf], [-inf, -inf]
s0 = 0
for i in range(n - 1):
xi, ci = x[i], cnt[e[i]]
s0 += xi * ci
if y[i] == 1:
while xi:
a.append((xi - xi // 2) * ci)
xi //= 2
else:
while xi:
b.append((xi - xi // 2) * ci)
xi //= 2
a.sort()
b.sort()
ans = 0
while s0 > s:
if s0 - a[-1] <= s:
ans += 1
s0 -= a.pop()
else:
if a[-1] + a[-2] >= b[-1]:
ans += 1
s0 -= a.pop()
else:
ans += 2
s0 -= b.pop()
print(ans)
``` | instruction | 0 | 47,200 | 13 | 94,400 |
Yes | output | 1 | 47,200 | 13 | 94,401 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6; 1 ≤ c_i ≤ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
Submitted Solution:
```
from collections import deque
from heapq import heappop, heappush
import sys
input = sys.stdin.readline
def solve():
n,s = map(int,input().split())
e = [[] for i in range(n)]
for i in range(n-1):
u,v,w,c = map(int,input().split())
u -= 1
v -= 1
e[u].append((v,w,c))
e[v].append((u,w,c))
par = [-1]*n
dep = [n]*n
dep[0] = 0
topo = []
q = deque([0])
count = [0]*n
while q:
now= q.pop()
topo.append(now)
lea = 1
for nex,_,_ in e[now]:
if dep[nex] < dep[now]:
continue
lea = 0
par[nex] = now
dep[nex] = dep[now]+1
q.append(nex)
if lea:
count[now] = 1
cum = 0
h1 = [0]
h2 = []
for now in topo[::-1]:
num = count[now]
for nex,w,c in e[now]:
if dep[nex] > dep[now]:
continue
cum += num*w
count[nex] += num
if c == 2:
while w:
h2.append((w-w//2)*num)
w //= 2
else:
while w:
h1.append((w-w//2)*num)
w //= 2
if cum <= s:
return 0
h1.sort(reverse=True)
h2.sort(reverse=True)
h2cum = [0]
for i in h2:
h2cum.append(i+h2cum[-1])
h2cum = h2cum[::-1]
ans = 10**10
now = 0
sub = 0
for i,h in enumerate(h1):
while now < len(h2cum) and cum-sub-h2cum[now] <= s:
now += 1
ans = min(ans,i+(len(h2cum)-now)*2)
sub += h
return ans
t = int(input())
for _ in range(t):
print(solve())
``` | instruction | 0 | 47,201 | 13 | 94,402 |
No | output | 1 | 47,201 | 13 | 94,403 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6; 1 ≤ c_i ≤ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
Submitted Solution:
```
from collections import *
from sys import stdin, stdout
input = stdin.buffer.readline
print = stdout.write
# "". join(strings)
def ri():
return int(input())
def rl():
return list(map(int, input().split()))
def topo_sort(tree, root, n):
visited = [False]*(n+1)
visited[root]=True
stack = [root]
result = [root]
while stack:
u = stack.pop()
for v in tree[u]:
if visited[v]==False:
visited[v]=True
result.append(v)
stack.append(v)
return result[::-1]
t =ri()
for _ in range(t):
n,S = rl()
edges=[]
for i in range(n-1):
edges.append(rl())
tree = defaultdict(list)
# tree = [[] for i in range(n+1)]
for u,v,w_ , c_ in edges:
tree[u].append(v)
tree[v].append(u)
root = 1
topo = topo_sort(tree, root, n)
cnt =[-1]*(n+1)
for u in topo:
this_cnt =0
for v in tree[u]:
#only add value from the children
if cnt[v]!=-1:
this_cnt+=cnt[v]
cnt[u]=this_cnt
#put value at 1 for leaves (no children)
if cnt[u]==0:
cnt[u]=1
gains=[[],[]]
sum_weights=0
for child, parent, weight, cost in edges:
#make sure child is really the child:
if cnt[child]> cnt[parent]:
child, parent = parent, child
sum_weights += weight * cnt[child]
count = cnt[child]
gain = count * (weight - weight//2)
while gain>0:
gains[cost-1].append(gain)
weight = weight//2
gain = count * (weight - weight//2)
gains[0].sort(reverse=True)
gains[1].sort(reverse=True)
idx1=0
idx2=1
idx22=0
ans=0
while sum_weights>S:
n1 = len(gains[0])
n2 = len(gains[1])
if idx1<n1 and sum_weights - gains[0][idx1]<=S:
ans+=1
break
if idx2< n1 and idx22<n2:
if gains[0][idx1]+gains[0][idx2]>=gains[1][idx22]:
if sum_weights - gains[0][idx1] - gains[0][idx2] > S and sum_weights - gains[1][idx22] - gains[0][idx1]<=S:
ans+=3
break
ans+=2
sum_weights -= gains[0][idx1] + gains[0][idx2]
idx1+=2
idx2+=2
else:
ans+=2
sum_weights -= gains[1][idx22]
idx22+=1
elif idx22>=n2:
ans+=1
sum_weights -= gains[0][idx1]
idx1+=1
idx2+=1
else: #idx2>=n1 and if idx1<n1 then sum_weights - gains[0][idx1]>S, so we need to take out a move of cost 2 anyway
ans+=2
sum_weights -= gains[1][idx22]
idx22+=1
print(str(ans)+"\n")
``` | instruction | 0 | 47,202 | 13 | 94,404 |
No | output | 1 | 47,202 | 13 | 94,405 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6; 1 ≤ c_i ≤ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import sys
# sys.setrecursionlimit(5010)
from heapq import *
# from collections import deque as dq
# from math import ceil,floor,sqrt,pow
# import bisect as bs
# from collections import Counter
from collections import defaultdict as dc
for _ in range(N()):
n,s = RL()
edges = [ RLL() for _ in range(n-1)]
dic = [[] for _ in range(n+1)]
gress = [0]*(n+1)
gress[1]=-n-1
for u,v,_,_ in edges:
dic[u].append(v)
dic[v].append(u)
gress[u]+=1
gress[v]+=1
leaf = []
count = [0]*(n+1)
for i in range(2,n+1):
if gress[i]==1:
leaf.append(i)
count[i] = 1
father = [0]*(n+1)
now = [1]
while now:
node = now.pop()
for child in dic[node]:
if child!=father[node]:
father[child] = node
now.append(child)
W = [0]*(n+1)
C = [0]*(n+1)
for u,v,w,c in edges:
if father[u]==v:
W[u] = w
C[u] = c
elif father[v]==u:
W[v] = w
C[v] = c
weight1 = []
weight2 = []
now = 0
D = [0.1,0.2,0.3,0.2]
while leaf:
node = leaf.pop()
f = father[node]
count[f]+=count[node]
gress[f]-=1
if gress[f]==1:
leaf.append(f)
d = W[node]*count[node]
now+=d
dd = d>>1
if W[node]&1:
dd+=(count[node]>>1)
if count[node]&1:
dd+=1
if C[node]==1:
weight1.append((-dd-D[W[node]%4],node))
else:
weight2.append((-dd-D[W[node]%4],node))
heapify(weight1)
heapify(weight2)
res = 0
while now>s:
if not weight1:
delta,node = heappop(weight2)
elif not weight2:
delta,node = heappop(weight1)
else:
if now+weight1[0][0]<=s or weight1[0][0]*2<weight2[0][0]:
delta,node = heappop(weight1)
else:
delta,node = heappop(weight2)
res+=C[node]
delta = int(delta)
now+=delta
dd = (-delta)>>1
w = W[node]
W[node]>>=1
if W[node]>0:
if w&1==1 and W[node]&1==0:
dd-=(count[node]>>1)
elif w&1==0 and W[node]&1==1:
dd+=(count[node]>>1)
if count[node]&1:
dd+=1
if C[node]==1:
heappush(weight1,(-dd-D[W[node]%4],node))
else:
heappush(weight2,(-dd-D[W[node]%4],node))
print(res)
``` | instruction | 0 | 47,203 | 13 | 94,406 |
No | output | 1 | 47,203 | 13 | 94,407 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Easy and hard versions are actually different problems, so we advise you to read both statements carefully.
You are given a weighted rooted tree, vertex 1 is the root of this tree. Also, each edge has its own cost.
A tree is a connected graph without cycles. A rooted tree has a special vertex called the root. A parent of a vertex v is the last different from v vertex on the path from the root to the vertex v. Children of vertex v are all vertices for which v is the parent. A vertex is a leaf if it has no children. The weighted tree is such a tree that each edge of this tree has some weight.
The weight of the path is the sum of edges weights on this path. The weight of the path from the vertex to itself is 0.
You can make a sequence of zero or more moves. On each move, you select an edge and divide its weight by 2 rounding down. More formally, during one move, you choose some edge i and divide its weight by 2 rounding down (w_i := \left⌊(w_i)/(2)\right⌋).
Each edge i has an associated cost c_i which is either 1 or 2 coins. Each move with edge i costs c_i coins.
Your task is to find the minimum total cost to make the sum of weights of paths from the root to each leaf at most S. In other words, if w(i, j) is the weight of the path from the vertex i to the vertex j, then you have to make ∑_{v ∈ leaves} w(root, v) ≤ S, where leaves is the list of all leaves.
You have to answer t independent test cases.
Input
The first line of the input contains one integer t (1 ≤ t ≤ 2 ⋅ 10^4) — the number of test cases. Then t test cases follow.
The first line of the test case contains two integers n and S (2 ≤ n ≤ 10^5; 1 ≤ S ≤ 10^{16}) — the number of vertices in the tree and the maximum possible sum of weights you have to obtain. The next n-1 lines describe edges of the tree. The edge i is described as four integers v_i, u_i, w_i and c_i (1 ≤ v_i, u_i ≤ n; 1 ≤ w_i ≤ 10^6; 1 ≤ c_i ≤ 2), where v_i and u_i are vertices the edge i connects, w_i is the weight of this edge and c_i is the cost of this edge.
It is guaranteed that the sum of n does not exceed 10^5 (∑ n ≤ 10^5).
Output
For each test case, print the answer: the minimum total cost required to make the sum of weights paths from the root to each leaf at most S.
Example
Input
4
4 18
2 1 9 2
3 2 4 1
4 1 1 2
3 20
2 1 8 1
3 1 7 2
5 50
1 3 100 1
1 5 10 2
2 3 123 2
5 4 55 1
2 100
1 2 409 2
Output
0
0
11
6
Submitted Solution:
```
from collections import defaultdict, deque
from bisect import bisect_left as lower
import heapq
import sys, threading
input = sys.stdin.readline
def put():
return map(int, input().split())
def dfs(tree,i, sum, p):
if len(tree[i])==1 and i!=0:
return 1
cnt=0
for j,w,c in tree[i]:
if j!=p:
z=dfs(tree,j, sum+w, i)
cnt+=z
if c==1:
one.append((w, z))
else:
two.append((w, z))
return cnt
def solve():
t = int(input())
for _ in range(t):
n, w = put()
tree = [[] for i in range(n)]
for i in range(n-1):
x,y,z,c = put()
x,y = x-1,y-1
tree[x].append((y,z,c))
tree[y].append((x,z,c))
dfs(tree, 0,0,-1)
s = 0
diffone, difftwo = [],[]
flag = True
for arr in [one, two]:
for i in range(len(arr)):
s+= arr[i][0]*arr[i][1]
while arr:
i,j = arr.pop()
while i>0:
if flag:
diffone.append((i-i//2)*j)
else:
difftwo.append((i-i//2)*j)
i//=2
flag = False
diffone.sort()
difftwo.sort()
i,j = len(diffone)-1, len(difftwo)-1
cnt=0
while s>w:
if i>=0 and j>=0:
if s-diffone[i]<=w:
s-=diffone[i]
cnt+=1
elif i>=1 and s-diffone[i]+diffone[i-1]<=w:
s-= diffone[i]+diffone[i-1]
cnt+=2
elif s-difftwo[j]<=w:
s-= difftwo[j]
cnt+=2
elif s-diffone[i]-difftwo[j]<=w:
s-= diffone[i]+difftwo[j]
cnt+=3
elif i>=1 and diffone[i]+diffone[i-1]>difftwo[j]:
s-= diffone[i]+diffone[i-1]
i-=2
cnt+=2
else:
s-= difftwo[j]
j-=1
cnt+=2
elif i>=0:
s-= diffone[i]
i-=1
cnt+=1
else:
s-= difftwo[j]
j-=1
cnt+=2
print(cnt)
one,two = [],[]
max_recur_size = 10**5*2 + 1000
max_stack_size = max_recur_size*500
sys.setrecursionlimit(max_recur_size)
threading.stack_size(max_stack_size)
thread = threading.Thread(target=solve)
thread.start()
``` | instruction | 0 | 47,204 | 13 | 94,408 |
No | output | 1 | 47,204 | 13 | 94,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,406 | 13 | 94,812 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys
def dfs(tree, root, priv_root, cur_lvl, priv_lvl, diff, pick_list):
if not tree:
return
stack = [(root, priv_root, cur_lvl, priv_lvl)]
while stack:
(root, priv_root, cur_lvl, priv_lvl) = stack.pop()
if cur_lvl ^ diff[root]:
cur_lvl ^= 1
pick_list.append(str(root))
stack += [(vertex, root, priv_lvl, cur_lvl)
for vertex in tree[root] if vertex != priv_root]
def main():
n = int(input())
tree = dict()
for _ in range(n - 1):
(u, v) = map(int, input().split())
tree[u] = tree.get(u, set()) | set([v])
tree[v] = tree.get(v, set()) | set([u])
init = [0] + list(map(int, input().split()))
goal = [0] + list(map(int, input().split()))
diff = [i ^ j for (i, j) in zip(init, goal)]
pick_list = list()
dfs(tree, 1, 0, 0, 0, diff, pick_list)
num = len(pick_list)
print(num)
if num:
print('\n'.join(pick_list))
if __name__ == '__main__':
sys.exit(main())
``` | output | 1 | 47,406 | 13 | 94,813 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,407 | 13 | 94,814 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys
read = lambda t=int: list(map(t,sys.stdin.readline().split()))
n, = read()
graph = [[] for _ in range(n)]
for _ in range(n-1):
a,b = read()
graph[a-1].append(b-1)
graph[b-1].append(a-1)
initial = read()
goal = read()
ansList = []
def dfs(node, par, odd, even, level):
if level == 0:
if initial[node]^even != goal[node]:
ansList.append(node)
even^=1
if level == 1:
if initial[node]^odd != goal[node]:
ansList.append(node)
odd^=1
for item in graph[node]:
if item!=par:
yield(item, node, odd, even, level^1)
stack = [(0,-1,0,0,0)]
while stack:
for item in dfs(*stack.pop()):
stack.append(item)
print(len(ansList))
for ele in ansList:
print(ele+1)
``` | output | 1 | 47,407 | 13 | 94,815 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,408 | 13 | 94,816 |
Tags: dfs and similar, trees
Correct Solution:
```
from sys import stdin,stdout
n=int(input())
a=[[] for i in range(n)]
for i in range(n-1):
c,d=(int(o) for o in stdin.readline().split())
a[c-1].append(d-1);a[d-1].append(c-1)
b=list(int(o) for o in stdin.readline().split())
c=list(int(o) for o in stdin.readline().split())
lv=[0]*n;lv[0]=1
q=[0]
while len(q)!=0:
r=q.pop()
for i in a[r]:
if lv[i]==0:
lv[i]=lv[r]+1
q.append(i)
ans='';vis=[True]*n
vis[0]=False;k=0
if b[0]==c[0]:
q=[(0,0,0)]
else:
q=[(0,1,0)];ans+=('1'+'\n');k+=1
while len(q)!=0:
no,o,e=q.pop()
for i in a[no]:
if vis[i]:
l=e;m=o
vis[i]=False
if lv[i]%2==0:
if b[i]==c[i] and l%2!=0:
ans+=(str(i+1)+'\n')
l+=1;k+=1
elif b[i]!=c[i] and l%2==0:
ans+=(str(i+1)+'\n')
l+=1;k+=1
else:
if b[i]==c[i] and m%2!=0:
ans+=(str(i+1)+'\n')
m+=1;k+=1
elif b[i]!=c[i] and m%2==0:
ans+=(str(i+1)+'\n')
m+=1;k+=1
q.append((i,m,l))
print(k)
stdout.write(ans)
``` | output | 1 | 47,408 | 13 | 94,817 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,409 | 13 | 94,818 |
Tags: dfs and similar, trees
Correct Solution:
```
n=int(input())
L=[[] for i in range(n)]
for i in range(n-1) :
a,b=map(int,input().split())
L[a-1].append(b-1)
L[b-1].append(a-1)
l=list(map(int,input().split()))
l1=list(map(int,input().split()))
W=[]
for i in range(n) :
W.append(abs(l[i]-l1[i]))
was=[0 for i in range(n)]
q=[[0,0,0]]
ans=[]
while q :
e=q[0]
was[e[0]]=1
if e[1]!=W[e[0]] :
ans.append(e[0]+1)
e[1]=1-e[1]
for x in L[e[0]] :
if was[x]==0 :
q.append([x,e[2],e[1]])
del q[0]
print(len(ans))
print('\n'.join(map(str,ans)))
``` | output | 1 | 47,409 | 13 | 94,819 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,410 | 13 | 94,820 |
Tags: dfs and similar, trees
Correct Solution:
```
intin=lambda:map(int,input().split())
iin=lambda:int(input())
Ain=lambda:list(map(int,input().split()))
from queue import LifoQueue
mod=1000000007
n=iin()
m=n+1
v=[[] for i in range(m)]
p=[0]*m
for _ in range(n-1):
a,b=intin()
v[a].append(b)
v[b].append(a)
vis=[False]*m
flipped=[0]*m
flip=[0]*m
ans=[]
def dfs(root):
q=[root]
while len(q)>0:
node=q.pop()
vis[node]=True
flipped[node]=flipped[p[p[node]]]
if flipped[node]!=flip[node]:
flipped[node]^=1
ans.append(node)
for i in range(len(v[node])):
son=v[node][i]
if not vis[son]:
q.append(son)
p[son]=node
a=Ain();b=Ain()
for i in range(n):
flip[i+1]=a[i]^b[i]
dfs(1)
print(len(ans))
for i in range(len(ans)):
print(ans[i])
``` | output | 1 | 47,410 | 13 | 94,821 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,411 | 13 | 94,822 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys
read = lambda t=int: list(map(t,sys.stdin.readline().split()))
# import resource, sys
# resource.setrlimit(resource.RLIMIT_STACK, (2**20,-1))
# sys.setrecursionlimit(10**5+5)
N, = read()
tree = [[] for _ in range(N)]
for _ in range(N-1):
a, b = read()
tree[a-1].append(b-1)
tree[b-1].append(a-1)
labels = read()
goals = read()
res = []
def dfs(root, par, xor0, xor1, depth):
if depth == 0:
if labels[root]^xor0 != goals[root]:
res.append(root)
xor0 ^= 1
if depth == 1:
if labels[root]^xor1 != goals[root]:
res.append(root)
xor1 ^= 1
for v in tree[root]:
if v != par:
yield (v, root, xor0, xor1, depth^1)
stack = [(0,-1,0,0,0)]
while stack:
for item in dfs(*stack.pop()):
stack.append(item)
# dfs(0, -1, 0, 0, 0)
print(len(res))
for x in res:
print(x+1)
``` | output | 1 | 47,411 | 13 | 94,823 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,412 | 13 | 94,824 |
Tags: dfs and similar, trees
Correct Solution:
```
from collections import defaultdict, deque, Counter, OrderedDict
from bisect import insort, bisect_right, bisect_left
import threading
def main():
n = int(input())
adj = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
a, b = a - 1, b - 1
adj[a].append(b)
adj[b].append(a)
init = [int(i) for i in input().split()]
goal = [int(i) for i in input().split()]
visited = [0] * n
par = [[] for i in range(n)]
dq = deque()
dq.append((0, 0))
while len(dq) > 0:
(s, p) = dq.pop()
if visited[s]: continue
visited[s] = 1
par[p].append(s)
for i in adj[s]:
dq.append((i, s))
par[0] = par[0][1:]
ans = []
dq = deque()
dq.append((0, 0, 0, 0))
while len(dq) > 0:
(s, l, fo, fe) = dq.pop()
if l % 2 == 0:
if fe % 2 == 1:
init[s] = 1 - init[s]
else:
if fo % 2 == 1:
init[s] = 1 - init[s]
if init[s] != goal[s]:
ans.append(s + 1)
if l % 2:
fo += 1
else:
fe += 1
for j in par[s]:
dq.append((j, l + 1, fo, fe))
print(len(ans))
print("\n".join(map(str, ans)))
if __name__ == "__main__":
"""sys.setrecursionlimit(200000)
threading.stack_size(10240000)"""
thread = threading.Thread(target=main)
thread.start()
``` | output | 1 | 47,412 | 13 | 94,825 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Iahub is very proud of his recent discovery, propagating trees. Right now, he invented a new tree, called xor-tree. After this new revolutionary discovery, he invented a game for kids which uses xor-trees.
The game is played on a tree having n nodes, numbered from 1 to n. Each node i has an initial value initi, which is either 0 or 1. The root of the tree is node 1.
One can perform several (possibly, zero) operations on the tree during the game. The only available type of operation is to pick a node x. Right after someone has picked node x, the value of node x flips, the values of sons of x remain the same, the values of sons of sons of x flips, the values of sons of sons of sons of x remain the same and so on.
The goal of the game is to get each node i to have value goali, which can also be only 0 or 1. You need to reach the goal of the game by using minimum number of operations.
Input
The first line contains an integer n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ui and vi (1 ≤ ui, vi ≤ n; ui ≠ vi) meaning there is an edge between nodes ui and vi.
The next line contains n integer numbers, the i-th of them corresponds to initi (initi is either 0 or 1). The following line also contains n integer numbers, the i-th number corresponds to goali (goali is either 0 or 1).
Output
In the first line output an integer number cnt, representing the minimal number of operations you perform. Each of the next cnt lines should contain an integer xi, representing that you pick a node xi.
Examples
Input
10
2 1
3 1
4 2
5 1
6 2
7 5
8 6
9 8
10 5
1 0 1 1 0 1 0 1 0 1
1 0 1 0 0 1 1 1 0 1
Output
2
4
7 | instruction | 0 | 47,413 | 13 | 94,826 |
Tags: dfs and similar, trees
Correct Solution:
```
import sys;readline = sys.stdin.readline
def i1(): return int(readline())
def nl(): return [int(s) for s in readline().split()]
def nn(n): return [int(readline()) for i in range(n)]
def nnp(n,x): return [int(readline())+x for i in range(n)]
def nmp(n,x): return (int(readline())+x for i in range(n))
def nlp(x): return [int(s)+x for s in readline().split()]
def nll(n): return [[int(s) for s in readline().split()] for i in range(n)]
def mll(n): return ([int(s) for s in readline().split()] for i in range(n))
def s1(): return readline().rstrip()
def sl(): return [s for s in readline().split()]
def sn(n): return [readline().rstrip() for i in range(n)]
def sm(n): return (readline().rstrip() for i in range(n))
def redir(s): global readline;import os;fn=sys.argv[0] + f'/../in-{s}.txt';readline = open(fn).readline if os.path.exists(fn) else readline
redir('a')
n = i1()
nodes = [[] for i in range(n+1)]
for i in range(n-1):
u, v = nl()
nodes[u].append(v)
nodes[v].append(u)
init = [0] + nl()
goal = [0] + nl()
roots = [1]
flip = [[0] * (n+1), [0] * (n+1)]
# notseen = [True] * (n+1)
fa = [0] * (n+1)
fa[1] = 1
# fa[1], fa[n+1] = -1, 1
level = 0
# cnt = 0
m = []
while roots:
_roots = []
fli = flip[level%2]
# fli2 = flip[1-level%2]
# print(level, roots, [(fli[r], init[r], goal[r]) for r in roots])
for r in roots:
# notseen[r] = False
assert fa[r] > 0 or r == 1
f = fli[fa[fa[r]]]
if f ^ init[r] != goal[r]:
# cnt += 1
f = 1 - f
m.append(r)
fli[r] = f
for i in nodes[r]:
if fa[i] == 0:
_roots.append(i)
fa[i] = r
# print(level, roots, [(fli[r], init[r], goal[r]) for r in roots])
roots = _roots
level += 1
# print(cnt)
init[0] = goal[0] = None
# print(init)
# print(goal)
print(len(m))
print('\n'.join(str(i) for i in m))
``` | output | 1 | 47,413 | 13 | 94,827 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study.
Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory. Yury Dmitrievich doesn't like Noora, so he always gives the girl the most difficult tasks. So it happened this time.
The teacher gives Noora a tree with n vertices. Vertices are numbered with integers from 1 to n. The length of all the edges of this tree is 1. Noora chooses a set of simple paths that pairwise don't intersect in edges. However each vertex should belong to at least one of the selected path.
For each of the selected paths, the following is done:
1. We choose exactly one edge (u, v) that belongs to the path.
2. On the selected edge (u, v) there is a point at some selected distance x from the vertex u and at distance 1 - x from vertex v. But the distance x chosen by Noora arbitrarily, i. e. it can be different for different edges.
3. One of the vertices u or v is selected. The point will start moving to the selected vertex.
Let us explain how the point moves by example. Suppose that the path consists of two edges (v1, v2) and (v2, v3), the point initially stands on the edge (v1, v2) and begins its movement to the vertex v1. Then the point will reach v1, then "turn around", because the end of the path was reached, further it will move in another direction to vertex v2, then to vertex v3, then "turn around" again, then move to v2 and so on. The speed of the points is 1 edge per second. For example, for 0.5 second the point moves to the length of the half of an edge.
A stopwatch is placed at each vertex of the tree. The time that the stopwatches indicate at start time is 0 seconds. Then at the starting moment of time, all points simultaneously start moving from the selected positions to selected directions along the selected paths, and stopwatches are simultaneously started. When one of the points reaches the vertex v, the stopwatch at the vertex v is automatically reset, i.e. it starts counting the time from zero.
Denote by resv the maximal time that the stopwatch at the vertex v will show if the point movement continues infinitely. Noora is asked to select paths and points on them so that res1 is as minimal as possible. If there are several solutions to do this, it is necessary to minimize res2, then res3, res4, ..., resn.
Help Noora complete the teacher's task.
For the better understanding of the statement, see the explanation for the example.
Input
The first line contains single integer n (2 ≤ n ≤ 100) — number of vertices in the given tree.
Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — vertices connected by an edge.
Guaranteed that input defines a valid tree.
Output
In the first line print single integer paths — number of paths you want to choose.
In the next paths lines print path's descriptions:
1. Single integer len — number of edges in the current path.
2. len integers — indices of the edges in the path. The edges are numbered from 1 to n - 1 in order they are given in input.
3. Two integers u and v — means that you put point on the edge between vertices u and v (obviously the edge should belong to the path) and a point will start moving to the vertex v. Note that order of printing of the edge's ends is important. For example if you print "1 2" (without quotes), then point will start moving to vertex 2; but if you print "2 1" (without quotes), then point will start moving to vertex 1.
4. Single real number x (0 ≤ x ≤ 1) — distance between point and vertex u (the same vertex that you print first in the third paragraph).
Scoring
Judge system will generate array res using the output data provided by the participant. Also system will generate array resOptimal by the jury answer. Your answer will be accepted if only for each i (1 ≤ i ≤ n) the following is satisfied: <image>.
Example
Input
3
1 2
2 3
Output
2
1 1 1 2 0.6666666666
1 2 2 3 0.6666666666
Note
Consider an example.
In starting moment of time points are located as following:
<image>
The first path is highlighted in red, the second in blue, green circles represent chosen points, and brown numbers inside vertices — current time at stopwatch. Purple arrows represent direction in which points will move.
In 0.(3) seconds points will be located in following way (before stopwatch reset):
<image>
After stopwatch reset:
<image>
In 1.0 second after the start of moving:
<image>
In 1.(3) seconds after the start of moving (after stopwatch reset):
<image>
Finally, in 2 seconds after the start of moving points return to their initial positions.
<image>
This process will continue infinitely.
Submitted Solution:
```
n = int(input())
for i in range(n - 1):
a, b = map(int,input().split())
print(2)
print("1 1 1 2 0.6666666666")
print("1 2 2 3 0.6666666666")
``` | instruction | 0 | 47,597 | 13 | 95,194 |
No | output | 1 | 47,597 | 13 | 95,195 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
The second semester starts at the University of Pavlopolis. After vacation in Vičkopolis Noora needs to return to Pavlopolis and continue her study.
Sometimes (or quite often) there are teachers who do not like you. Incidentally Noora also has one such teacher. His name is Yury Dmitrievich and he teaches graph theory. Yury Dmitrievich doesn't like Noora, so he always gives the girl the most difficult tasks. So it happened this time.
The teacher gives Noora a tree with n vertices. Vertices are numbered with integers from 1 to n. The length of all the edges of this tree is 1. Noora chooses a set of simple paths that pairwise don't intersect in edges. However each vertex should belong to at least one of the selected path.
For each of the selected paths, the following is done:
1. We choose exactly one edge (u, v) that belongs to the path.
2. On the selected edge (u, v) there is a point at some selected distance x from the vertex u and at distance 1 - x from vertex v. But the distance x chosen by Noora arbitrarily, i. e. it can be different for different edges.
3. One of the vertices u or v is selected. The point will start moving to the selected vertex.
Let us explain how the point moves by example. Suppose that the path consists of two edges (v1, v2) and (v2, v3), the point initially stands on the edge (v1, v2) and begins its movement to the vertex v1. Then the point will reach v1, then "turn around", because the end of the path was reached, further it will move in another direction to vertex v2, then to vertex v3, then "turn around" again, then move to v2 and so on. The speed of the points is 1 edge per second. For example, for 0.5 second the point moves to the length of the half of an edge.
A stopwatch is placed at each vertex of the tree. The time that the stopwatches indicate at start time is 0 seconds. Then at the starting moment of time, all points simultaneously start moving from the selected positions to selected directions along the selected paths, and stopwatches are simultaneously started. When one of the points reaches the vertex v, the stopwatch at the vertex v is automatically reset, i.e. it starts counting the time from zero.
Denote by resv the maximal time that the stopwatch at the vertex v will show if the point movement continues infinitely. Noora is asked to select paths and points on them so that res1 is as minimal as possible. If there are several solutions to do this, it is necessary to minimize res2, then res3, res4, ..., resn.
Help Noora complete the teacher's task.
For the better understanding of the statement, see the explanation for the example.
Input
The first line contains single integer n (2 ≤ n ≤ 100) — number of vertices in the given tree.
Each of next n - 1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v) — vertices connected by an edge.
Guaranteed that input defines a valid tree.
Output
In the first line print single integer paths — number of paths you want to choose.
In the next paths lines print path's descriptions:
1. Single integer len — number of edges in the current path.
2. len integers — indices of the edges in the path. The edges are numbered from 1 to n - 1 in order they are given in input.
3. Two integers u and v — means that you put point on the edge between vertices u and v (obviously the edge should belong to the path) and a point will start moving to the vertex v. Note that order of printing of the edge's ends is important. For example if you print "1 2" (without quotes), then point will start moving to vertex 2; but if you print "2 1" (without quotes), then point will start moving to vertex 1.
4. Single real number x (0 ≤ x ≤ 1) — distance between point and vertex u (the same vertex that you print first in the third paragraph).
Scoring
Judge system will generate array res using the output data provided by the participant. Also system will generate array resOptimal by the jury answer. Your answer will be accepted if only for each i (1 ≤ i ≤ n) the following is satisfied: <image>.
Example
Input
3
1 2
2 3
Output
2
1 1 1 2 0.6666666666
1 2 2 3 0.6666666666
Note
Consider an example.
In starting moment of time points are located as following:
<image>
The first path is highlighted in red, the second in blue, green circles represent chosen points, and brown numbers inside vertices — current time at stopwatch. Purple arrows represent direction in which points will move.
In 0.(3) seconds points will be located in following way (before stopwatch reset):
<image>
After stopwatch reset:
<image>
In 1.0 second after the start of moving:
<image>
In 1.(3) seconds after the start of moving (after stopwatch reset):
<image>
Finally, in 2 seconds after the start of moving points return to their initial positions.
<image>
This process will continue infinitely.
Submitted Solution:
```
def fact(n):
if(n==1):
return n
else:
return n*fact(n-1)
def gcd(a,b):
if(b==0):
return a
else:
return gcd(b,a%b)
a,b=fact(4),fact(3)
#print(a,b)
print(gcd(a,b))
``` | instruction | 0 | 47,598 | 13 | 95,196 |
No | output | 1 | 47,598 | 13 | 95,197 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,736 | 13 | 95,472 |
"Correct Solution:
```
N=int(input())
E=[[] for _ in range(N)]
for _ in range(N-1):
a,b=map(lambda x:int(x)-1, input().split())
E[a].append(b)
E[b].append(a)
C=list(map(int, input().split()))
C.sort(reverse=True)
ans=[0]*(N)
stack=[0]
ans[0]=C[0]
k=1
while stack:
n=stack.pop()
for to in E[n]:
if ans[to]!=0: continue
ans[to]=C[k]
k+=1
stack.append(to)
print(sum(C[1:]))
print(' '.join(map(str,ans)))
``` | output | 1 | 47,736 | 13 | 95,473 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,737 | 13 | 95,474 |
"Correct Solution:
```
N=int(input())
G=[[] for i in range(N+1)]
for i in range(N-1):
a,b=map(int,input().split())
G[a].append(b)
G[b].append(a)
C=list(map(int,input().split()))
C.sort(reverse=True)
S=sum(C[1:])
num=[0 for i in range(N+1)]
un_used=[True for i in range(N+1)]
q=[]
q.append(1)
un_used[1]=False
while q:
node = q.pop(0)
num[node] = C.pop(0)
for i in range(len(G[node])):
if un_used[G[node][i]]:
un_used[G[node][i]]=False
q.append(G[node][i])
print(S)
print(" ".join(map(str,num[1:])))
``` | output | 1 | 47,737 | 13 | 95,475 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,738 | 13 | 95,476 |
"Correct Solution:
```
from collections import deque
N=int(input())
G=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
a-=1;b-=1
G[a].append(b)
G[b].append(a)
j=0
c=sorted([int(i) for i in input().split()])
M=sum(c)-max(c)
d=[-1 for i in range(N)]
q=deque([j])
while(len(q)>0):
r=q.popleft()
d[r]=c.pop()
for p in G[r]:
if d[p]==-1:
q.appendleft(p)
print(M)
print(" ".join([str(i) for i in d]))
``` | output | 1 | 47,738 | 13 | 95,477 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,739 | 13 | 95,478 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10000000)
n = int(input())
G = [[] for _ in range(n)]
for i in range(n-1):
a,b = map(int,input().split())
G[a-1].append(b-1)
G[b-1].append(a-1)
c = list(map(int,input().split()))
c.sort()
node = [0]*n
used = [False]*n
def dfs(cur,point):
used[cur] = True
for nx in G[cur]:
if used[nx]: continue
t = c.pop()
node[nx] = t
point += min(node[cur],node[nx])
point = dfs(nx,point)
return point
node[0] = c.pop()
# print(dfs(0,-1,0))
print(dfs(0,0))
print(*node)
``` | output | 1 | 47,739 | 13 | 95,479 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,740 | 13 | 95,480 |
"Correct Solution:
```
from collections import defaultdict, deque
N = int(input())
X = defaultdict(list)
for i in range(N - 1):
ai, bi = map(lambda s: int(s) - 1, input().split())
X[ai].append(bi)
X[bi].append(ai)
c = list(map(int, input().split()))
c.sort(reverse=True)
print(sum(c[1:]))
d = [0] * N
q = deque([0])
i = 0
while len(q) > 0:
v = q.popleft()
d[v] = c[i]
i += 1
for x in X[v]:
if d[x] != 0:
continue
q.append(x)
print(' '.join(list(map(str, d))))
``` | output | 1 | 47,740 | 13 | 95,481 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,741 | 13 | 95,482 |
"Correct Solution:
```
n = int(input())
adj_list = [[] for _ in range(n)]
for i in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
adj_list[a].append(b)
adj_list[b].append(a)
c = list(map(int, input().split()))
c.sort(reverse=True)
idx = 0
from collections import deque
dq = deque()
dq.append(0)
ans = [-1] * n
while len(dq) > 0:
node = dq.popleft()
ans[node] = c[idx]
idx += 1
for next_node in adj_list[node]:
if ans[next_node] < 0:
dq.append(next_node)
print(sum(c[1:]))
print(*ans)
``` | output | 1 | 47,741 | 13 | 95,483 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,742 | 13 | 95,484 |
"Correct Solution:
```
N = int(input())
L = [list(map(int,input().split())) for k in range(N-1)]
c = sorted(list(map(int,input().split())))
a = sum(c) - c[-1]
T = [[] for k in range(N)]
for e in L:
T[e[0]-1].append(e[1]-1)
T[e[1]-1].append(e[0]-1)
kyori = [-1 for k in range(N)]
que = [L[0][0]]
kyori[L[0][0]] = c.pop()
while len(que) > 0:
now = que.pop()
for tsugi in T[now]:
if kyori[tsugi] == -1:
kyori[tsugi] = c.pop()
que.append(tsugi)
print(a)
print(*kyori, sep=" ")
``` | output | 1 | 47,742 | 13 | 95,485 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53 | instruction | 0 | 47,743 | 13 | 95,486 |
"Correct Solution:
```
N=int(input())
from collections import defaultdict
branch=defaultdict(set)
for i in range(N-1):
a,b=map(int,input().split())
a-=1
b-=1
branch[a]|={b}
branch[b]|={a}
C=list(map(int,input().split()))
C.sort()
ans=[0]*N
used={0}
check={0}
M=sum(C[:-1])
while len(check)>0:
now=check.pop()
ans[now]=C.pop()
for nex in branch[now]:
if nex not in used:
check|={nex}
used|={nex}
print(M)
print(" ".join([str(x) for x in ans]))
``` | output | 1 | 47,743 | 13 | 95,487 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
from collections import deque
N = int(input())
adj = [[] for _ in range(N)]
for _ in range(N - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
adj[a].append(b)
adj[b].append(a)
c = list(map(int, input().split()))
c.sort(reverse=True)
score = sum(c) - max(c)
num = [-1] * N
que = deque()
que.append(0)
i = 0
while que:
v = que.popleft()
if num[v] != -1:
continue
num[v] = c[i]
i += 1
for nv in adj[v]:
que.append(nv)
print(score)
print(*num)
``` | instruction | 0 | 47,744 | 13 | 95,488 |
Yes | output | 1 | 47,744 | 13 | 95,489 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
N = int(input())
que = []
edges = {i:[] for i in range(1,N+1)}
visited = {i:False for i in range(1,N+1)}
ans = {i:None for i in range(1,N+1)}
while True:
s = list(map(int,input().split()))
if len(s) > 2:
break
edges[s[0]].append(s[1])
edges[s[1]].append(s[0])
s = sorted(s)
ans1 = sum(s[:-1])
que.append(1)
while que:
temp = que.pop(0)
if visited[temp]:
continue
visited[temp] = True
ans[temp] = s.pop()
que += edges[temp]
s = ""
for key in ans:
if key>1:
s+= " "
s += str(ans[key])
print(ans1)
print(s)
``` | instruction | 0 | 47,745 | 13 | 95,490 |
Yes | output | 1 | 47,745 | 13 | 95,491 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
from collections import deque
N=int(input())
A=[0 for i in range(N-1)]
B=[0 for i in range(N-1)]
G=[[] for i in range(N)]
for i in range(N-1):
a,b=map(int,input().split())
a-=1;b-=1
A[i],B[i]=a,b
G[a].append(b)
G[b].append(a)
j=0
for i in range(N):
if len(G[i])>len(G[j]):
j=i
c=sorted([int(i) for i in input().split()])
d=[-1 for i in range(N)]
q=deque([j])
while(len(q)>0):
r=q.popleft()
d[r]=c.pop()
for p in G[r]:
if d[p]==-1:
q.append(p)
M=0
for i in range(N-1):
M+=min(d[A[i]],d[B[i]])
print(M)
print(" ".join([str(i) for i in d]))
``` | instruction | 0 | 47,746 | 13 | 95,492 |
Yes | output | 1 | 47,746 | 13 | 95,493 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
import sys
sys.setrecursionlimit(10**5*5)
n=int(input())
ab=[[]for _ in range(n)]
for _ in range(n-1):
a,b=map(int,input().split())
ab[a-1].append(b-1)
ab[b-1].append(a-1)
c=list(map(int,input().split()))
c.sort()
print(sum(c)-c[-1])
ans=[-1]*n
cnt=0
node=[]
visited=[0]*n
ans=[-1]*n
def dfs(x):
global cnt
ans[x]=c[-cnt-1]
visited[x]=1
for next in ab[x]:
if visited[next]==0:
cnt+=1
dfs(next)
dfs(0)
print(*ans)
``` | instruction | 0 | 47,747 | 13 | 95,494 |
Yes | output | 1 | 47,747 | 13 | 95,495 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
import sys
from collections import *
import heapq
import math
import bisect
from itertools import permutations,accumulate,combinations,product
from fractions import gcd
def input():
return sys.stdin.readline()[:-1]
mod=10**9+7
n=int(input())
ab=[list(map(int,input().split())) for i in range(n-1)]
c=list(map(int,input().split()))
c.sort()
lst=[[i+1] for i in range(n)]
nodelst=[0]*n
ans=0
for i in range(n-1):
a,b=ab[i]
lst[a-1].append(b)
lst[b-1].append(a)
# print(lst)
# lst.sort(key=lambda x: len(x))
lst2=sorted(lst, key=lambda x: len(x))
# # print(lst)
# for i in range(n):
# nodelst[lst[i][0]-1]=c[i]
d=deque()
for i in range(n):
if len(lst2[i])==2:
d.append(lst2[i][0])
else:
break
# print(lst)
# print(lst2)
# print(d)
cnt=0
while d:
tmp=d.popleft()-1
if nodelst[tmp]==0:
nodelst[tmp]=c[cnt]
cnt+=1
d+=lst[tmp][1:]
else:
pass
print(sum(c)-c[-1])
print(*nodelst)
``` | instruction | 0 | 47,748 | 13 | 95,496 |
No | output | 1 | 47,748 | 13 | 95,497 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
import sys
sys.setrecursionlimit(10000)
def add_node_2_tree_dic(tree_dic, x, y):
if x not in tree_dic:
tree_dic[x] = [y]
else:
tree_dic[x].append(y)
# 深さ優先探索で行けそう
N = int(input())
tree_dic = {}
for _ in range(N-1):
a, b = map(int, input().split())
add_node_2_tree_dic(tree_dic, a, b)
add_node_2_tree_dic(tree_dic, b, a)
c_lst = list(map(int, input().split()))
c_lst.sort()
ans_lst = [0]*N
def search_next_node_and_add_side_wate(tree_dic, ans, current_node, c_lst, ans_lst):
if len(tree_dic) == 0: # これなしでいい?
return ans
for next_node in tree_dic[current_node]: # ここでエラーになる理由をJupyterでテストしつつ理解する
# if next_node not in tree_dic[current_node]:# これなしでいい?
# print("second time")
# continue # 深さ優先探索の過程ですでに通ったノードをもう一度通ろうとしたとき
# else:
c = c_lst.pop()
ans += c
ans_lst[next_node - 1] = c
tree_dic[current_node].remove(next_node) # 今回通った枝を取り払う
tree_dic[next_node].remove(current_node)
if len(tree_dic[current_node]) == 0:
del tree_dic[current_node]# 探索し終えたノードの削除
if len(tree_dic[next_node]) == 0:
del tree_dic[next_node]# 探索し終えたノードの削除
# print()
else: # 次のノードにつながっている辺があるとき
ans = search_next_node_and_add_side_wate(tree_dic, ans, next_node, c_lst, ans_lst)
return ans
ans = 0
current_node = 1
ans_lst[0] = c_lst.pop()
ans = search_next_node_and_add_side_wate(tree_dic, ans, current_node, c_lst, ans_lst)
ans_str = ""
for i in range(N):
ans_str += str(ans_lst[i])
if i != N - 1:
ans_str += " "
print(ans)
print(ans_str)
``` | instruction | 0 | 47,749 | 13 | 95,498 |
No | output | 1 | 47,749 | 13 | 95,499 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
n=int(input())
g=[[] for i in range(n)]
ro=[0]*n
for i in range(n-1):
a,b=map(int,input().split())
ro[a-1]+=1
ro[b-1]+=1
g[a-1].append(b-1)
g[b-1].append(a-1)
c=list(map(int,input().split()))
c.sort(reverse=True)
m=max(ro)
mi=ro.index(m)
q=[mi]
ans=[0]*n
v=[0]*n
v[mi]=1
ans[mi]=c.pop()
while len(q)>0:
s=q.pop()
for i in g[s]:
if v[i]==0:
v[i]=1
ans[i]=c.pop()
q.append(i)
print(sum(ans)-max(ans))
print(*ans)
``` | instruction | 0 | 47,750 | 13 | 95,500 |
No | output | 1 | 47,750 | 13 | 95,501 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with N vertices 1,2,\ldots,N, and positive integers c_1,c_2,\ldots,c_N. The i-th edge in the tree (1 \leq i \leq N-1) connects Vertex a_i and Vertex b_i.
We will write a positive integer on each vertex in T and calculate our score as follows:
* On each edge, write the smaller of the integers written on the two endpoints.
* Let our score be the sum of the integers written on all the edges.
Find the maximum possible score when we write each of c_1,c_2,\ldots,c_N on one vertex in T, and show one way to achieve it. If an integer occurs multiple times in c_1,c_2,\ldots,c_N, we must use it that number of times.
Constraints
* 1 \leq N \leq 10000
* 1 \leq a_i,b_i \leq N
* 1 \leq c_i \leq 10^5
* The given graph is a tree.
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
c_1 \ldots c_N
Output
Use the following format:
M
d_1 \ldots d_N
where M is the maximum possible score, and d_i is the integer to write on Vertex i. d_1,d_2,\ldots,d_N must be a permutation of c_1,c_2,\ldots,c_N. If there are multiple ways to achieve the maximum score, any of them will be accepted.
Examples
Input
5
1 2
2 3
3 4
4 5
1 2 3 4 5
Output
10
1 2 3 4 5
Input
5
1 2
1 3
1 4
1 5
3141 59 26 53 59
Output
197
59 26 3141 59 53
Submitted Solution:
```
from collections import deque
N = int(input())
G = {i:[] for i in range(1,N+1)}
for _ in range(N-1):
a,b = map(int,input().split())
G[a].append(b)
G[b].append(a)
C = sorted(list(map(int,input().split())))
hist = [0 for _ in range(N+1)]
que = deque([1])
hist[1] = 1
cur = 0
while que:
i = que.popleft()
if len(G[i])==1:
A[i] = C[cur]
cur += 1
hist[i] = 2
flag = 2
for j in G[i]:
if hist[j]==0:
que.append(j)
hist[j] = 1
flag = 1
if flag==2 and hist[i]==1:
A[i] = C[cur]
cur += 1
hist[i] = 2
elif hist[i]==1:
que.append(i)
cnt = 0
hist = {(i,j):0 for i in range(1,N+1) for j in G[i]}
for i in range(1,N+1):
for j in G[i]:
if hist[(i,j)]==0:
cnt += min(A[i],A[j])
hist[(i,j)] = 1
hist[(j,i)] = 1
print(cnt)
``` | instruction | 0 | 47,751 | 13 | 95,502 |
No | output | 1 | 47,751 | 13 | 95,503 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,952 | 13 | 95,904 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n, s = list(map(int, input().split()))
a = [0] * n
listy = 0
for i in range(n - 1):
c, d = list(map(int, input().split()))
a[c-1] += 1
a[d-1] += 1
if a[c-1] == 1:
listy += 1
if a[c-1] == 2:
listy -= 1
if a[d-1] == 1:
listy += 1
if a[d-1] == 2:
listy -= 1
if n <= 3:
print(s)
else:
print(float(s) * 2 / float(listy))
``` | output | 1 | 47,952 | 13 | 95,905 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,953 | 13 | 95,906 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 00:01:16 2020
@author: Dell
"""
n,s=list(map(int,input().split()))
from collections import defaultdict
d=defaultdict(list)
for i in range(n-1):
h,m=list(map(int,input().split()))
d[h].append(m)
d[m].append(h)
c=0
for i in d:
if len(d[i])==1:
c+=1
print(2*s/c)
``` | output | 1 | 47,953 | 13 | 95,907 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,954 | 13 | 95,908 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n,s=map(int, input().split())
g=[[] for i in range(n+1)]
ind=[0]*n
for i in range(n-1):
u,v=map(int, input().split())
ind[u-1]+=1
ind[v-1]+=1
#g[u-1].append(v-1)
#g[v-1].append(u-1)
ans=0
for i in range(n):
if ind[i]==1:
ans+=1
print(f"{(2*s/ans):.10f}")
``` | output | 1 | 47,954 | 13 | 95,909 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,955 | 13 | 95,910 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n, s = map(int, input().split())
g = [[] for i in range(n+1)]
for i in range(n-1):
u, v = map(int, input().split())
g[u].append(v)
g[v].append(u)
l = 0
for i in range(1, n+1):
if len(g[i]) == 1:
l += 1
print(2*s/l)
``` | output | 1 | 47,955 | 13 | 95,911 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,956 | 13 | 95,912 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
#Code by Sounak, IIESTS
#------------------------------warmup----------------------------
import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
import threading
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
#-------------------game starts now-----------------------------------------------------
n,s=map(int,input().split())
a=[0]*n
for i in range (n-1):
x,y=map(int,input().split())
a[x-1]+=1
a[y-1]+=1
l=0
for i in a:
if i==1:
l+=1
print(2*s/l)
``` | output | 1 | 47,956 | 13 | 95,913 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,957 | 13 | 95,914 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
n,k=map(int,input().split())
q=[0]*n
for i in range(n-1):
a,b=map(int,input().split())
q[a-1]+=1
q[b-1]+=1
c=0
for i in range(n):
if q[i]==1:
c+=1
print(2*k/c)
``` | output | 1 | 47,957 | 13 | 95,915 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,958 | 13 | 95,916 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
# https://codeforces.com/contest/1085/problem/D
n, s = map(int, input().split())
g = {}
for _ in range(n-1):
u, v = map(int, input().split())
if u not in g:
g[u] = []
if v not in g:
g[v] = []
g[u].append(v)
g[v].append(u)
num_leaf = 0
for k in g:
if len(g[k]) == 1:
num_leaf += 1
print(s / num_leaf * 2)
#6 1
#2 1
#2 3
#2 5
#5 4
#5 6
``` | output | 1 | 47,958 | 13 | 95,917 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image> | instruction | 0 | 47,959 | 13 | 95,918 |
Tags: constructive algorithms, implementation, trees
Correct Solution:
```
def main():
n, s = map(int, input().split())
g = [0 for _ in range(n)]
for _ in range(n - 1):
a, b = map(int, input().split())
a -= 1
b -= 1
g[a] += 1
g[b] += 1
m = 0
for x in g:
if x == 1:
m += 1
print(2 * s / m)
main()
``` | output | 1 | 47,959 | 13 | 95,919 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n,s=map(int,input().split())
t=[0]*n
for i in range(n-1):
a,b=map(int,input().split())
t[a-1]+=1
t[b-1]+=1
print(s*2/t.count(1))
``` | instruction | 0 | 47,960 | 13 | 95,920 |
Yes | output | 1 | 47,960 | 13 | 95,921 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
a, s = list(map(int, input().split()))
graph = [[] for _ in range(a)]
for _ in range(a - 1):
x, y = list(map(int, input().split()))
graph[x-1].append(y-1)
graph[y-1].append(x-1)
k = 0
for i in graph:
if len(i) == 1:
k += 1
print((s*2) / k)
``` | instruction | 0 | 47,961 | 13 | 95,922 |
Yes | output | 1 | 47,961 | 13 | 95,923 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n, k = list(map(int,input().split()))
arr = [0]*n
for i in range(n-1):
a,b = list(map(int,input().split()))
a-=1
b-=1
arr[a]+=1
arr[b]+=1
c = 0
for i in range(n):
if arr[i] == 1:
c+=1
print((2*k)/c)
``` | instruction | 0 | 47,962 | 13 | 95,924 |
Yes | output | 1 | 47,962 | 13 | 95,925 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n,s=[int(x) for x in input().split(' ')]
d,ans={},0
for i in range(n-1):
a,b=[int(x) for x in input().split(' ')]
if a in d.keys():
d[a]+=1
else:
d[a]=1
if b in d.keys():
d[b]+=1
else:
d[b]=1
for v in d.values():
if v==1:
ans+=1
print(2*s/ans)
``` | instruction | 0 | 47,963 | 13 | 95,926 |
Yes | output | 1 | 47,963 | 13 | 95,927 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
koor = dict()
a = input()
q = int(a.split()[0])
w = int(a.split()[1])
for i in range(q - 1):
a = input()
z = int(a.split()[0])
x = int(a.split()[1])
if z not in koor.keys():
koor[z] = 1
else:
koor[z] += 1
if x not in koor.keys():
koor[x] = 1
else:
koor[x] += 1
tt = list()
for i in koor.values():
tt.append(i)
print((w * 2) / max(tt))
``` | instruction | 0 | 47,964 | 13 | 95,928 |
No | output | 1 | 47,964 | 13 | 95,929 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
def find(x):
s = 0
for i in tree[x]:
if i in tree:
s += find(i)
else:
s += 1
return s
n, s = map(int, input().split())
tree = {1: []}
pivots = {1}
for i in range(n - 1):
a, b = map(int, input().split())
if a in pivots:
if a not in tree:
tree[a] = []
tree[a].append(b)
pivots.add(b)
else:
if b not in tree:
tree[b] = []
tree[b].append(a)
pivots.add(a)
l = find(1)
if len(tree[1]) == 1:
l += 1
print(2 * s / l)
``` | instruction | 0 | 47,965 | 13 | 95,930 |
No | output | 1 | 47,965 | 13 | 95,931 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
a, s = list(map(int, input().split()))
graph = [[] for _ in range(a)]
for _ in range(a - 1):
x, y = list(map(int, input().split()))
graph[x-1].append(y-1)
graph[y-1].append(x-1)
k = 0
for i in graph:
if len(i) == 1:
k += 1
print(k)
print((s*2) / k)
``` | instruction | 0 | 47,966 | 13 | 95,932 |
No | output | 1 | 47,966 | 13 | 95,933 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected graph without cycles) and an integer s.
Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.
Let's define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.
Find the minimum possible diameter that Vanya can get.
Input
The first line contains two integer numbers n and s (2 ≤ n ≤ 10^5, 1 ≤ s ≤ 10^9) — the number of vertices in the tree and the sum of edge weights.
Each of the following n−1 lines contains two space-separated integer numbers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the indexes of vertices connected by an edge. The edges are undirected.
It is guaranteed that the given edges form a tree.
Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.
Your answer will be considered correct if its absolute or relative error does not exceed 10^{-6}.
Formally, let your answer be a, and the jury's answer be b. Your answer is considered correct if \frac {|a-b|} {max(1, b)} ≤ 10^{-6}.
Examples
Input
4 3
1 2
1 3
1 4
Output
2.000000000000000000
Input
6 1
2 1
2 3
2 5
5 4
5 6
Output
0.500000000000000000
Input
5 5
1 2
2 3
3 4
3 5
Output
3.333333333333333333
Note
In the first example it is necessary to put weights like this:
<image>
It is easy to see that the diameter of this tree is 2. It can be proved that it is the minimum possible diameter.
In the second example it is necessary to put weights like this:
<image>
Submitted Solution:
```
n,s = map(int,input().split())
c = [[] for i in range(n)]
for i in range(n - 1):
a, b = map(int,input().split())
c[a-1].append(b)
c[b-1].append(a)
d = set()
k = 0
for i in range(n):
if len(c[i]) == 1:
d.add(i)
if not (c[i][0] - 1) in d:
k += 1
print(round(s * 2 / k,10))
``` | instruction | 0 | 47,967 | 13 | 95,934 |
No | output | 1 | 47,967 | 13 | 95,935 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles.
We chose a hidden node x. In order to find this node, you can ask queries of two types:
* d u (1 ≤ u ≤ n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them.
* s u (1 ≤ u ≤ n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict!
Node a is called an ancestor of node b if a ≠ b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself.
Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
Input
The first line contains the integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
To print the answer, print "! x" (without quotes).
Interaction
To ask a question, print it in one of the formats above:
* d u (1 ≤ u ≤ n), or
* s u (1 ≤ u ≤ n).
After each question, you should read the answer: either the distance or the second vertex on the path, as mentioned in the legend.
If we answer with -1 instead of a valid answer, that means you exceeded the number of queries, made an invalid query, or violated the condition in the second type of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.
After printing a query, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* See the documentation for other languages.
Hacks:
The first line should contain two integers n and x (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ x ≤ n).
Each of the next n-1 lines should contain two integers u and v (1 ≤ u,v ≤ n) that mean there is an edge between nodes u and v. The edges must form a tree.
Example
Input
5
1 2
1 3
3 4
3 5
3
5
Output
d 2
s 3
! 5
Note
In the first example, the hidden node is node 5.
<image>
We first ask about the distance between node x and node 2. The answer is 3, so node x is either 4 or 5. We then ask about the second node in the path from node 3 to node x. Note here that node 3 is an ancestor of node 5. We receive node 5 as the answer. Finally, we report that the hidden node is node 5.
Submitted Solution:
```
def updateParents(edges,parents):
stack = [1]
visited = set()
while stack:
curr = stack.pop()
if curr not in visited:
visited.add(curr)
for kid in edges[curr]:
if kid not in visited:
parents[kid-1] = curr
stack.append(kid)
def query(curr,typ):
if typ == 'd':
print('d '+str(curr),flush = True)
return int(input())
print('s '+str(curr),flush = True)
return int(input())
def solve(edges,parents):
curr = 1
dist = query(curr,'d')
if dist == 0:
print('! 1',flush = True)
return
total = 0
while total < 35:
if dist == 1:
ans = query(curr,'s')
print('! '+str(ans),flush = True)
return
while total < 35 and dist != 1:
curr = query(curr,'s')
dist -= 1
while len(edges[curr]) == 2 and dist > 0:
for kid in edges[curr]:
if kid != parents[curr-1]:
curr = kid
break
dist -= 1
total += 1
#print(dist,curr)
if dist == 0:
print('! '+str(curr),flush = True)
return
def main():
n = int(input())
edges = {}
for i in range(1,n+1):
edges[i] = []
for i in range(n-1):
a,b = map(int,input().split())
edges[a].append(b)
edges[b].append(a)
parents = [0]*n
updateParents(edges,parents)
#print(edges,parents)
solve(edges,parents)
main()
``` | instruction | 0 | 48,006 | 13 | 96,012 |
No | output | 1 | 48,006 | 13 | 96,013 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles.
We chose a hidden node x. In order to find this node, you can ask queries of two types:
* d u (1 ≤ u ≤ n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them.
* s u (1 ≤ u ≤ n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict!
Node a is called an ancestor of node b if a ≠ b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself.
Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
Input
The first line contains the integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
To print the answer, print "! x" (without quotes).
Interaction
To ask a question, print it in one of the formats above:
* d u (1 ≤ u ≤ n), or
* s u (1 ≤ u ≤ n).
After each question, you should read the answer: either the distance or the second vertex on the path, as mentioned in the legend.
If we answer with -1 instead of a valid answer, that means you exceeded the number of queries, made an invalid query, or violated the condition in the second type of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.
After printing a query, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* See the documentation for other languages.
Hacks:
The first line should contain two integers n and x (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ x ≤ n).
Each of the next n-1 lines should contain two integers u and v (1 ≤ u,v ≤ n) that mean there is an edge between nodes u and v. The edges must form a tree.
Example
Input
5
1 2
1 3
3 4
3 5
3
5
Output
d 2
s 3
! 5
Note
In the first example, the hidden node is node 5.
<image>
We first ask about the distance between node x and node 2. The answer is 3, so node x is either 4 or 5. We then ask about the second node in the path from node 3 to node x. Note here that node 3 is an ancestor of node 5. We receive node 5 as the answer. Finally, we report that the hidden node is node 5.
Submitted Solution:
```
import os, sys, shutil, glob, re
import time, calendar
from datetime import datetime, timezone
import hashlib, zipfile, zlib
from math import *
from operator import itemgetter
from functools import wraps, cmp_to_key, reduce, lru_cache
from itertools import count, combinations, permutations
from collections import namedtuple, defaultdict, Counter, deque
from queue import Queue
from bisect import bisect_left, bisect_right
class CustomException(Exception): pass
if os.getenv('SJDEAK'):
# sys.stdin = open(os.path.expanduser('./in.txt'))
# sys.stdout = open(os.path.expanduser('./out.txt'), 'w')
debug = print
else:
debug = lambda *args, **kwargs: None
def sendInteractiveCommand(cmd):
print(cmd)
sys.stdout.flush()
return input()
def findHidden(now, distToHidden):
if distToHidden == 0:
return now
if len(graph[now]) == 1:
return findHidden(graph[now][0], distToHidden-1)
else:
child = int(sendInteractiveCommand(f's {now}'))
return findHidden(child, distToHidden-1)
if __name__ == '__main__':
N = int(input())
graph = defaultdict(list)
for i in range(N-1):
u,v = sorted(list(map(int, input().split())))
graph[u].append(v)
ans = findHidden(1, int(sendInteractiveCommand(f'd 1')))
print('! {}'.format(ans))
``` | instruction | 0 | 48,007 | 13 | 96,014 |
No | output | 1 | 48,007 | 13 | 96,015 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
This is an interactive problem.
You're given a tree consisting of n nodes, rooted at node 1. A tree is a connected graph with no cycles.
We chose a hidden node x. In order to find this node, you can ask queries of two types:
* d u (1 ≤ u ≤ n). We will answer with the distance between nodes u and x. The distance between two nodes is the number of edges in the shortest path between them.
* s u (1 ≤ u ≤ n). We will answer with the second node on the path from u to x. However, there's a plot twist. If u is not an ancestor of x, you'll receive "Wrong answer" verdict!
Node a is called an ancestor of node b if a ≠ b and the shortest path from node 1 to node b passes through node a. Note that in this problem a node is not an ancestor of itself.
Can you find x in no more than 36 queries? The hidden node is fixed in each test beforehand and does not depend on your queries.
Input
The first line contains the integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree.
Output
To print the answer, print "! x" (without quotes).
Interaction
To ask a question, print it in one of the formats above:
* d u (1 ≤ u ≤ n), or
* s u (1 ≤ u ≤ n).
After each question, you should read the answer: either the distance or the second vertex on the path, as mentioned in the legend.
If we answer with -1 instead of a valid answer, that means you exceeded the number of queries, made an invalid query, or violated the condition in the second type of queries. Exit immediately after receiving -1 and you will see Wrong answer verdict. Otherwise, you can get an arbitrary verdict because your solution will continue to read from a closed stream.
After printing a query, do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use:
* fflush(stdout) or cout.flush() in C++;
* System.out.flush() in Java;
* flush(output) in Pascal;
* stdout.flush() in Python;
* See the documentation for other languages.
Hacks:
The first line should contain two integers n and x (2 ≤ n ≤ 2 ⋅ 10^5, 1 ≤ x ≤ n).
Each of the next n-1 lines should contain two integers u and v (1 ≤ u,v ≤ n) that mean there is an edge between nodes u and v. The edges must form a tree.
Example
Input
5
1 2
1 3
3 4
3 5
3
5
Output
d 2
s 3
! 5
Note
In the first example, the hidden node is node 5.
<image>
We first ask about the distance between node x and node 2. The answer is 3, so node x is either 4 or 5. We then ask about the second node in the path from node 3 to node x. Note here that node 3 is an ancestor of node 5. We receive node 5 as the answer. Finally, we report that the hidden node is node 5.
Submitted Solution:
```
from collections import deque
from sys import stdout
def bfs_algorithm(start_vertex):
global graph
distances = [None] * (n + 1)
distances[start_vertex] = 0
queue = deque([start_vertex])
while queue:
pop_vertex = queue.popleft()
for neighbour in graph[pop_vertex]:
if distances[neighbour] is None:
distances[neighbour] = distances[pop_vertex] + 1
queue.append(neighbour)
return distances
n = int(input())
pairs = []
for i in range(n - 1):
pairs.append([int(i) for i in input().split()])
pairs.append([0, 0])
graph = {}
for pair in pairs:
if pair[0] in graph:
graph[pair[0]].add(pair[1])
else:
graph[pair[0]] = {pair[1]}
if pair[1] in graph:
graph[pair[1]].add(pair[0])
else:
graph[pair[1]] = {pair[0]}
print('d 1', end='\n')
stdout.flush()
answer = int(input())
distances = bfs_algorithm(1)
vertexes = [i for i in range(n + 1) if distances[i] == answer - 1]
for vertex in vertexes:
print('d ' + str(vertex), end='\n')
stdout.flush()
answer = int(input())
if answer == 1:
print('s ' + str(vertex), end='\n')
stdout.flush()
answer = int(input())
if answer == -1:
exit()
print('! ' + str(answer))
``` | instruction | 0 | 48,008 | 13 | 96,016 |
No | output | 1 | 48,008 | 13 | 96,017 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.