message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24. | instruction | 0 | 35,219 | 13 | 70,438 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
n=int(input())
d=[0]*2*n
for i in range(n-1):
u,v=map(int,input().split())
d[u]+=1
d[v]+=1
n=n*d[u]*d[v]%998244353
print(n)
``` | output | 1 | 35,219 | 13 | 70,439 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24. | instruction | 0 | 35,220 | 13 | 70,440 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
import sys
def topological_sort_tree(E, p):
Q = [p]
L = []
visited = set([p])
while Q:
p = Q.pop()
L.append(p)
for vf in E[p]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[p] -= 1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
mod = 998244353
frac = [1]*364364
for i in range(2,364364):
frac[i] = i * frac[i-1]%mod
N = int(input())
Dim = [0]*N
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Dim[a] += 1
Dim[b] += 1
Edge[a].append(b)
Edge[b].append(a)
L = topological_sort_tree(Edge, 0)
P = getpar(Edge, 0)
dp = [1]*N
for l in L[::-1]:
dp[l] = dp[l]*frac[Dim[l]] % mod
dp[P[l]] = dp[P[l]]*dp[l] % mod
print((N*dp[0])%mod)
``` | output | 1 | 35,220 | 13 | 70,441 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24. | instruction | 0 | 35,221 | 13 | 70,442 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
from math import *
from collections import *
import sys
sys.setrecursionlimit(10**9)
mod = 998244353
n = int(input())
a = [0 for i in range(n+1)]
ans = n
for i in range(n-1):
u,v = map(int,input().split())
a[u] += 1
a[v] += 1
ans *= a[u]
ans %= mod
ans *= a[v]
ans %= mod
print(ans%mod)
``` | output | 1 | 35,221 | 13 | 70,443 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24. | instruction | 0 | 35,222 | 13 | 70,444 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
import io, os
#input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
g = [0] * 200005
r = int(input())
n = r
for i in range(1, n):
u, v = map(int, input().split())
g[u] += 1
g[v] += 1
r *= g[u] * g[v]
r %= 998244353
print(r)
``` | output | 1 | 35,222 | 13 | 70,445 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24. | instruction | 0 | 35,223 | 13 | 70,446 |
Tags: combinatorics, dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
mod = 998244353
frac = [1]*364364
for i in range(2,364364):
frac[i] = i * frac[i-1]%mod
N = int(input())
Dim = [0]*N
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Dim[a] += 1
Dim[b] += 1
Edge[a].append(b)
Edge[b].append(a)
Dim[0] += 1
par = [-1] + [0]*(N-1)
stack = [0]
visited = set([0])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
leaf = [i for i in range(N) if Dim[i] == 1]
D = Dim[:]
dp = [1]*N
Q = deque(leaf)
while Q:
vn = Q.pop()
if vn == 0:
dp[vn] = (dp[vn] * frac[Dim[vn] - 1])% mod
break
dp[vn] = (dp[vn] * frac[Dim[vn]])% mod
vp = par[vn]
D[vp] -= 1
dp[vp] = (dp[vp] * dp[vn]) % mod
if D[vp] == 1:
Q.appendleft(vp)
print(N * dp[0] % mod)
``` | output | 1 | 35,223 | 13 | 70,447 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
import sys
n=int(input())
E=[list(map(int,input().split())) for i in range(n-1)]
mod=998244353
ELIST=[[] for i in range(n+1)]
for a,b in E:
ELIST[a].append(b)
ELIST[b].append(a)
MUR=[1]
for i in range(1,n+1):
MUR.append(MUR[-1]*i%mod)
ANS=1
for i in range(1,n+1):
ANS=ANS*MUR[len(ELIST[i])]%mod
print(ANS*n%mod)
``` | instruction | 0 | 35,224 | 13 | 70,448 |
Yes | output | 1 | 35,224 | 13 | 70,449 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
n = int(input())
m = n
g = [0] * 200005
for i in range(n - 1):
a, b = input().split()
a = int(a)
b = int(b)
g[a] += 1
g[b] += 1
m = (m * g[a] * g[b]) % 998244353
print(m)
``` | instruction | 0 | 35,225 | 13 | 70,450 |
Yes | output | 1 | 35,225 | 13 | 70,451 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
# Enter your code here. Read input from STDIN. Print output to STDOUT# ===============================================================================================
# importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
# If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
# If the element is already present in the list,
# the right most position where element has to be inserted is returned
# ==============================================================================================
# fast I/O region
BUFSIZE = 8192
from sys import stderr
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
# ===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
###########################
#Sorted list
class SortedList:
def __init__(self, iterable=[], _load=200):
"""Initialize sorted list instance."""
values = sorted(iterable)
self._len = _len = len(values)
self._load = _load
self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
self._list_lens = [len(_list) for _list in _lists]
self._mins = [_list[0] for _list in _lists]
self._fen_tree = []
self._rebuild = True
def _fen_build(self):
"""Build a fenwick tree instance."""
self._fen_tree[:] = self._list_lens
_fen_tree = self._fen_tree
for i in range(len(_fen_tree)):
if i | i + 1 < len(_fen_tree):
_fen_tree[i | i + 1] += _fen_tree[i]
self._rebuild = False
def _fen_update(self, index, value):
"""Update `fen_tree[index] += value`."""
if not self._rebuild:
_fen_tree = self._fen_tree
while index < len(_fen_tree):
_fen_tree[index] += value
index |= index + 1
def _fen_query(self, end):
"""Return `sum(_fen_tree[:end])`."""
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
x = 0
while end:
x += _fen_tree[end - 1]
end &= end - 1
return x
def _fen_findkth(self, k):
"""Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`)."""
_list_lens = self._list_lens
if k < _list_lens[0]:
return 0, k
if k >= self._len - _list_lens[-1]:
return len(_list_lens) - 1, k + _list_lens[-1] - self._len
if self._rebuild:
self._fen_build()
_fen_tree = self._fen_tree
idx = -1
for d in reversed(range(len(_fen_tree).bit_length())):
right_idx = idx + (1 << d)
if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
idx = right_idx
k -= _fen_tree[idx]
return idx + 1, k
def _delete(self, pos, idx):
"""Delete value at the given `(pos, idx)`."""
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len -= 1
self._fen_update(pos, -1)
del _lists[pos][idx]
_list_lens[pos] -= 1
if _list_lens[pos]:
_mins[pos] = _lists[pos][0]
else:
del _lists[pos]
del _list_lens[pos]
del _mins[pos]
self._rebuild = True
def _loc_left(self, value):
"""Return an index pair that corresponds to the first position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
lo, pos = -1, len(_lists) - 1
while lo + 1 < pos:
mi = (lo + pos) >> 1
if value <= _mins[mi]:
pos = mi
else:
lo = mi
if pos and value <= _lists[pos - 1][-1]:
pos -= 1
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value <= _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def _loc_right(self, value):
"""Return an index pair that corresponds to the last position of `value` in the sorted list."""
if not self._len:
return 0, 0
_lists = self._lists
_mins = self._mins
pos, hi = 0, len(_lists)
while pos + 1 < hi:
mi = (pos + hi) >> 1
if value < _mins[mi]:
hi = mi
else:
pos = mi
_list = _lists[pos]
lo, idx = -1, len(_list)
while lo + 1 < idx:
mi = (lo + idx) >> 1
if value < _list[mi]:
idx = mi
else:
lo = mi
return pos, idx
def add(self, value):
"""Add `value` to sorted list."""
_load = self._load
_lists = self._lists
_mins = self._mins
_list_lens = self._list_lens
self._len += 1
if _lists:
pos, idx = self._loc_right(value)
self._fen_update(pos, 1)
_list = _lists[pos]
_list.insert(idx, value)
_list_lens[pos] += 1
_mins[pos] = _list[0]
if _load + _load < len(_list):
_lists.insert(pos + 1, _list[_load:])
_list_lens.insert(pos + 1, len(_list) - _load)
_mins.insert(pos + 1, _list[_load])
_list_lens[pos] = _load
del _list[_load:]
self._rebuild = True
else:
_lists.append([value])
_mins.append(value)
_list_lens.append(1)
self._rebuild = True
def discard(self, value):
"""Remove `value` from sorted list if it is a member."""
_lists = self._lists
if _lists:
pos, idx = self._loc_right(value)
if idx and _lists[pos][idx - 1] == value:
self._delete(pos, idx - 1)
def remove(self, value):
"""Remove `value` from sorted list; `value` must be a member."""
_len = self._len
self.discard(value)
if _len == self._len:
raise ValueError('{0!r} not in list'.format(value))
def pop(self, index=-1):
"""Remove and return value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
value = self._lists[pos][idx]
self._delete(pos, idx)
return value
def bisect_left(self, value):
"""Return the first index to insert `value` in the sorted list."""
pos, idx = self._loc_left(value)
return self._fen_query(pos) + idx
def bisect_right(self, value):
"""Return the last index to insert `value` in the sorted list."""
pos, idx = self._loc_right(value)
return self._fen_query(pos) + idx
def count(self, value):
"""Return number of occurrences of `value` in the sorted list."""
return self.bisect_right(value) - self.bisect_left(value)
def __len__(self):
"""Return the size of the sorted list."""
return self._len
def __getitem__(self, index):
"""Lookup value at `index` in sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
return self._lists[pos][idx]
def __delitem__(self, index):
"""Remove value at `index` from sorted list."""
pos, idx = self._fen_findkth(self._len + index if index < 0 else index)
self._delete(pos, idx)
def __contains__(self, value):
"""Return true if `value` is an element of the sorted list."""
_lists = self._lists
if _lists:
pos, idx = self._loc_left(value)
return idx < len(_lists[pos]) and _lists[pos][idx] == value
return False
def __iter__(self):
"""Return an iterator over the sorted list."""
return (value for _list in self._lists for value in _list)
def __reversed__(self):
"""Return a reverse iterator over the sorted list."""
return (value for _list in reversed(self._lists) for value in reversed(_list))
def __repr__(self):
"""Return string representation of sorted list."""
return 'SortedList({0})'.format(list(self))
# ===============================================================================================
# some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") # for fast input
def out(var): sys.stdout.write(str(var)) # for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
def fsep(): return map(float, inp().split())
def nextline(): out("\n") # as stdout.write always print sring.
def testcase(t):
for p in range(t):
solve()
def pow(x, y, p):
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1): # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
from functools import reduce
def factors(n):
return set(reduce(list.__add__,
([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))
def gcd(a, b):
if a == b: return a
while b > 0: a, b = b, a % b
return a
# discrete binary search
# minimise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# if isvalid(l):
# return l
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m - 1):
# return m
# if isvalid(m):
# r = m + 1
# else:
# l = m
# return m
# maximise:
# def search():
# l = 0
# r = 10 ** 15
#
# for i in range(200):
# # print(l,r)
# if isvalid(r):
# return r
# if l == r:
# return l
# m = (l + r) // 2
# if isvalid(m) and not isvalid(m + 1):
# return m
# if isvalid(m):
# l = m
# else:
# r = m - 1
# return m
##############Find sum of product of subsets of size k in a array
# ar=[0,1,2,3]
# k=3
# n=len(ar)-1
# dp=[0]*(n+1)
# dp[0]=1
# for pos in range(1,n+1):
# dp[pos]=0
# l=max(1,k+pos-n-1)
# for j in range(min(pos,k),l-1,-1):
# dp[j]=dp[j]+ar[pos]*dp[j-1]
# print(dp[k])
def prefix_sum(ar): # [1,2,3,4]->[1,3,6,10]
return list(accumulate(ar))
def suffix_sum(ar): # [1,2,3,4]->[10,9,7,4]
return list(accumulate(ar[::-1]))[::-1]
def N():
return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def YES():
print("YES")
def NO():
print("NO")
def Yes():
print("Yes")
def No():
print("No")
# =========================================================================================
from collections import defaultdict
def numberOfSetBits(i):
i = i - ((i >> 1) & 0x55555555)
i = (i & 0x33333333) + ((i >> 2) & 0x33333333)
return (((i + (i >> 4) & 0xF0F0F0F) * 0x1010101) & 0xffffffff) >> 24
# # to find factorial and ncr
tot=200005
mod = 998244353
fac = [1, 1]
finv = [1, 1]
inv = [0, 1]
for i in range(2, tot + 1):
fac.append((fac[-1] * i) % mod)
inv.append(mod - (inv[mod % i] * (mod // i) % mod))
finv.append(finv[-1] * inv[-1] % mod)
def comb(n, r):
if n < r:
return 0
else:
return fac[n] * (finv[r] * finv[n - r] % mod) % mod
class MergeFind:
def __init__(self, n):
self.parent = list(range(n))
self.size = [1] * n
self.num_sets = n
# self.lista = [[_] for _ in range(n)]
def find(self, a):
to_update = []
while a != self.parent[a]:
to_update.append(a)
a = self.parent[a]
for b in to_update:
self.parent[b] = a
return self.parent[a]
def merge(self, a, b):
a = self.find(a)
b = self.find(b)
if a == b:
return
self.num_sets -= 1
self.parent[a] = b
self.size[b] += self.size[a]
# self.lista[a] += self.lista[b]
# self.lista[b] = []
def set_size(self, a):
return self.size[self.find(a)]
def __len__(self):
return self.num_sets
def lcm(a, b):
return abs((a // gcd(a, b)) * b)
def solve():
mod=998244353
n=N()
deg=[0]*n
for _ in range(n-1):
a,b=sep()
a-=1
b-=1
deg[a]+=1
deg[b]+=1
p=1
for i in range(n):
p*=fac[deg[i]]
p%=mod
print((n*p)%mod)
solve()
#testcase(int(inp()))
``` | instruction | 0 | 35,226 | 13 | 70,452 |
Yes | output | 1 | 35,226 | 13 | 70,453 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
# https://codeforces.com/contest/1173/problem/D
n = int(input())
mod = 998244353
gt = [1, 1]
for i in range(2, 200000):
gt.append(i*gt[-1] % mod)
g = {}
p = {i:-1 for i in range(1, n+1)}
dp = {}
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)
i = 0
S = [1]
p[1] = 0
while i < len(S):
cur = S[i]
for next_n in g[cur]:
if next_n == p[cur]:
continue
p[next_n] = cur
S.append(next_n)
i +=1
for x in S[1:][::-1]:
if len(g[x]) == 1:
dp[x] = 1
else:
tmp = 1
for next_n in g[x]:
if next_n == p[x]:continue
tmp = tmp * dp[next_n] % mod
tmp = tmp * gt[len(g[x])] % mod
if x == 1:
tmp = n * tmp % mod
dp[x] = tmp
dp[1] = n * gt[len(g[1])] % mod
for x in g[1]:
dp[1] = dp[1] * dp[x] % mod
print(dp[1])
``` | instruction | 0 | 35,227 | 13 | 70,454 |
Yes | output | 1 | 35,227 | 13 | 70,455 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
import sys
def topological_sort_tree(E, p):
Q = [p]
L = []
visited = set([p])
while Q:
p = Q.pop()
L.append(p)
for vf in E[p]:
if vf not in visited:
visited.add(vf)
Q.append(vf)
return L
def getpar(Edge, p):
N = len(Edge)
par = [0]*N
par[p] -= 1
stack = [p]
visited = set([p])
while stack:
vn = stack.pop()
for vf in Edge[vn]:
if vf in visited:
continue
visited.add(vf)
par[vf] = vn
stack.append(vf)
return par
mod = 998244353
frac = [1]*364364
for i in range(2,364364):
frac[i] = i * frac[i-1]%mod
N = int(input())
Dim = [0]*N
Edge = [[] for _ in range(N)]
for _ in range(N-1):
a, b = map(int, sys.stdin.readline().split())
a -= 1
b -= 1
Dim[a] += 1
Dim[b] += 1
Edge[a].append(b)
Edge[b].append(a)
L = topological_sort_tree(Edge, 0)
P = getpar(Edge, 0)
dp = [1]*N
for l in L[::-1]:
dp[P[l]] = (dp[P[l]]*dp[l]*frac[Dim[l]]) % mod
print((N*dp[-1])%mod)
``` | instruction | 0 | 35,228 | 13 | 70,456 |
No | output | 1 | 35,228 | 13 | 70,457 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
MOD = 998244353
def main():
buf = input()
n = int(buf)
edge = dict()
for i in range(n):
edge[i] = [] # zero index
for i in range(n-1):
buf = input()
buflist = list(buf.split())
a = int(buflist[0])-1 # zero index
b = int(buflist[1])-1 # zero index
edge[a].append(b)
edge[b].append(a)
# 葉を含む辺を1つ固定
# 次数2の道について長さをkとすると
# 2 ** (k-1)
pow2 = [1]
factorial = [1]
for i in range(1, n+1):
pow2.append((pow2[-1] * 2) % MOD)
factorial.append((factorial[-1] * i) % MOD)
root = 0
for v in edge:
if len(edge[v]) == 1:
root = v
break
visited = []
for i in range(n):
visited.append(False)
stack = [root]
from_root = True
permutation = 1
path_length = 0
while stack:
current = stack.pop()
visited[current] = True
if len(edge[current]) == 1:
if current == root:
stack.append(edge[current][0])
else:
permutation = (permutation * pow2[path_length]) % MOD
path_length = 0
elif len(edge[current]) == 2:
path_length += 1
for adj in edge[current]:
if not visited[adj]:
stack.append(adj)
else:
permutation = (permutation * pow2[path_length]) % MOD
path_length = 0
if from_root:
permutation = (permutation * factorial[len(edge[current])]) % MOD
from_root = False
else:
permutation = (permutation * factorial[len(edge[current])-1]) % MOD
for adj in edge[current]:
if not visited[adj]:
stack.append(adj)
permutation = (permutation * n) % MOD
print(permutation)
if __name__ == '__main__':
main()
``` | instruction | 0 | 35,229 | 13 | 70,458 |
No | output | 1 | 35,229 | 13 | 70,459 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
n = int(input())
m = n
g = [0] * 200005
for i in range(n - 1):
a, b = input().split()
a = int(a)
b = int(b)
g[a] += 1
g[b] += 1
m *= g[a] * g[b] % 998244353
print(m)
``` | instruction | 0 | 35,230 | 13 | 70,460 |
No | output | 1 | 35,230 | 13 | 70,461 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Nauuo is a girl who loves drawing circles.
One day she has drawn a circle and wanted to draw a tree on it.
The tree is a connected undirected graph consisting of n nodes and n-1 edges. The nodes are numbered from 1 to n.
Nauuo wants to draw a tree on the circle, the nodes of the tree should be in n distinct points on the circle, and the edges should be straight without crossing each other.
"Without crossing each other" means that every two edges have no common point or the only common point is an endpoint of both edges.
Nauuo wants to draw the tree using a permutation of n elements. A permutation of n elements is a sequence of integers p_1,p_2,…,p_n in which every integer from 1 to n appears exactly once.
After a permutation is chosen Nauuo draws the i-th node in the p_i-th point on the circle, then draws the edges connecting the nodes.
The tree is given, Nauuo wants to know how many permutations are there so that the tree drawn satisfies the rule (the edges are straight without crossing each other). She only wants to know the answer modulo 998244353, can you help her?
It is obvious that whether a permutation is valid or not does not depend on which n points on the circle are chosen.
Input
The first line contains a single integer n (2≤ n≤ 2⋅ 10^5) — the number of nodes in the tree.
Each of the next n-1 lines contains two integers u and v (1≤ u,v≤ n), denoting there is an edge between u and v.
It is guaranteed that the given edges form a tree.
Output
The output contains a single integer — the number of permutations suitable to draw the given tree on a circle satisfying the rule, modulo 998244353.
Examples
Input
4
1 2
1 3
2 4
Output
16
Input
4
1 2
1 3
1 4
Output
24
Note
Example 1
All valid permutations and their spanning trees are as follows.
<image>
Here is an example of invalid permutation: the edges (1,3) and (2,4) are crossed.
<image>
Example 2
Every permutation leads to a valid tree, so the answer is 4! = 24.
Submitted Solution:
```
import io, os
#input = io.StringIO(os.read(0, os.fstat(0).st_size).decode()).readline
g = [0] * 200005
r = int(input())
n = r
for i in range(1, n):
u, v = map(int, input().split())
g[u] += 1
g[v] += 1
r *= g[u] * g[v] % 998244353
print(r)
``` | instruction | 0 | 35,231 | 13 | 70,462 |
No | output | 1 | 35,231 | 13 | 70,463 |
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 each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.
What is the minimum number of removals necessary to remove all vertices from the tree?
Input
Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 200 000): the number of vertices in the tree.
The second line of each test case contains n integers a_v (0 ≤ a_v ≤ 2): colours of vertices. Gray vertices have a_v=0, white have a_v=1, black have a_v=2.
Each of the next n-1 lines contains two integers u, v (1 ≤ u, v ≤ n): tree edges.
The sum of all n throughout the test is guaranteed to not exceed 200 000.
Output
For each test case, print one integer: the minimum number of operations to solve the problem.
Example
Input
4
2
1 1
1 2
4
1 2 1 2
1 2
2 3
3 4
5
1 1 0 1 2
1 2
2 3
3 4
3 5
8
1 2 1 2 2 2 1 2
1 3
2 3
3 4
4 5
5 6
5 7
5 8
Output
1
3
2
3
Note
<image>
In the first test case, both vertices are white, so you can remove them at the same time.
<image>
In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.
<image>
In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.
<image>
In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.
Submitted Solution:
```
def lets_check_if_the_input_can_be_multiple_trees_by_blowing_the_time():
for i in range(1000):
print(i)
for j in range(i**3):
for k in range(1000):
blow_it_up = 3 / (i**2.12873465 + j**0.34566 + k**0.87654)
for _ in range(int(input())):
n = int(input())
colors = [int(number) for number in input().split(" ")]
white_trees = []
black_trees = []
whole_tree = [[number] for number in range(n)]
for index, color in enumerate(colors):
if color == 1:
white_trees.append([index])
if color == 2:
black_trees.append([index])
for _ in range(n-1):
a, b = (int(number) for number in input().split(" "))
a -= 1
b -= 1
found = False
first_found = None
for index, group in enumerate(whole_tree):
if a in group or b in group:
if found:
whole_tree[first_found] += whole_tree[index]
del whole_tree[index]
else:
found = True
first_found = index
if colors[a] == colors[b] == 1:
found = False
first_found = None
for index, group in enumerate(white_trees):
if a in group or b in group:
if found:
white_trees[first_found] += white_trees[index]
del white_trees[index]
else:
found = True
first_found = index
if colors[a] == colors[b] == 2:
found = False
first_found = None
for index, group in enumerate(black_trees):
if a in group or b in group:
if found:
black_trees[first_found] += black_trees[index]
del black_trees[index]
else:
found = True
first_found = index
if len(whole_tree) > 1:
lets_check_if_the_input_can_be_multiple_trees_by_blowing_the_time()
print(min(len(black_trees), len(white_trees)) + 1)
``` | instruction | 0 | 35,384 | 13 | 70,768 |
No | output | 1 | 35,384 | 13 | 70,769 |
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 each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.
What is the minimum number of removals necessary to remove all vertices from the tree?
Input
Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 200 000): the number of vertices in the tree.
The second line of each test case contains n integers a_v (0 ≤ a_v ≤ 2): colours of vertices. Gray vertices have a_v=0, white have a_v=1, black have a_v=2.
Each of the next n-1 lines contains two integers u, v (1 ≤ u, v ≤ n): tree edges.
The sum of all n throughout the test is guaranteed to not exceed 200 000.
Output
For each test case, print one integer: the minimum number of operations to solve the problem.
Example
Input
4
2
1 1
1 2
4
1 2 1 2
1 2
2 3
3 4
5
1 1 0 1 2
1 2
2 3
3 4
3 5
8
1 2 1 2 2 2 1 2
1 3
2 3
3 4
4 5
5 6
5 7
5 8
Output
1
3
2
3
Note
<image>
In the first test case, both vertices are white, so you can remove them at the same time.
<image>
In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.
<image>
In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.
<image>
In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.
Submitted Solution:
```
def lets_check_if_the_input_can_be_multiple_trees_by_blowing_the_time():
for i in range(1000):
for j in range(i**3):
for k in range(1000):
blow_it_up = 3 / (i**2.12873465 + j**0.34566 + k**0.87654)
for _ in range(int(input())):
n = int(input())
colors = [int(number) for number in input().split(" ")]
white_trees = []
black_trees = []
whole_tree = [[number] for number in range(n)]
for index, color in enumerate(colors):
if color in (0, 1):
white_trees.append([index])
if color in (0, 2):
black_trees.append([index])
for _ in range(n-1):
a, b = (int(number) for number in input().split(" "))
a -= 1
b -= 1
'''
found = False
first_found = None
for index, group in enumerate(whole_tree):
if a in group or b in group:
if found:
whole_tree[first_found] += whole_tree[index]
del whole_tree[index]
else:
found = True
first_found = index
'''
if colors[a] in (0, 1) and colors[b] in (0, 1):
found = False
first_found = None
for index, group in enumerate(white_trees):
if a in group or b in group:
if found:
white_trees[first_found] += white_trees[index]
del white_trees[index]
else:
found = True
first_found = index
if colors[a] in (0, 2) and colors[b] in (0, 2):
found = False
first_found = None
for index, group in enumerate(black_trees):
if a in group or b in group:
if found:
black_trees[first_found] += black_trees[index]
del black_trees[index]
else:
found = True
first_found = index
white_trees_length = len(white_trees)
black_trees_length = len(black_trees)
for group in white_trees:
all_grey = True
for node in group:
if colors[node] != 0:
all_grey = False
break
if all_grey:
white_trees_length -= 1
for group in black_trees:
all_grey = True
for node in group:
if colors[node] != 0:
all_grey = False
break
if all_grey:
black_trees_length -= 1
print(min(white_trees_length, black_trees_length) + 1)
``` | instruction | 0 | 35,385 | 13 | 70,770 |
No | output | 1 | 35,385 | 13 | 70,771 |
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 each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.
What is the minimum number of removals necessary to remove all vertices from the tree?
Input
Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 200 000): the number of vertices in the tree.
The second line of each test case contains n integers a_v (0 ≤ a_v ≤ 2): colours of vertices. Gray vertices have a_v=0, white have a_v=1, black have a_v=2.
Each of the next n-1 lines contains two integers u, v (1 ≤ u, v ≤ n): tree edges.
The sum of all n throughout the test is guaranteed to not exceed 200 000.
Output
For each test case, print one integer: the minimum number of operations to solve the problem.
Example
Input
4
2
1 1
1 2
4
1 2 1 2
1 2
2 3
3 4
5
1 1 0 1 2
1 2
2 3
3 4
3 5
8
1 2 1 2 2 2 1 2
1 3
2 3
3 4
4 5
5 6
5 7
5 8
Output
1
3
2
3
Note
<image>
In the first test case, both vertices are white, so you can remove them at the same time.
<image>
In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.
<image>
In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.
<image>
In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.
Submitted Solution:
```
for _ in range(int(input())):
n = int(input())
colors = [int(number) for number in input().split(" ")]
white_trees = []
black_trees = []
for index, color in enumerate(colors):
if color == 1:
white_trees.append([index])
if color == 2:
black_trees.append([index])
for _ in range(n-1):
a, b = (int(number) for number in input().split(" "))
a -= 1
b -= 1
if colors[a] == colors[b] == 1:
found = False
first_found = None
for index, group in enumerate(white_trees):
if a in group or b in group:
if found:
white_trees[first_found] += white_trees[index]
del white_trees[index]
else:
found = True
first_found = index
if colors[a] == colors[b] == 2:
found = False
first_found = None
for index, group in enumerate(black_trees):
if a in group or b in group:
if found:
black_trees[first_found] += black_trees[index]
del black_trees[index]
else:
found = True
first_found = index
print(min(len(black_trees), len(white_trees)) + 1)
``` | instruction | 0 | 35,386 | 13 | 70,772 |
No | output | 1 | 35,386 | 13 | 70,773 |
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 each vertex coloured white, black or grey. You can remove elements from the tree by selecting a subset of vertices in a single connected component and removing them and their adjacent edges from the graph. The only restriction is that you are not allowed to select a subset containing a white and a black vertex at once.
What is the minimum number of removals necessary to remove all vertices from the tree?
Input
Each test contains multiple test cases. The first line contains an integer t (1 ≤ t ≤ 100 000), denoting the number of test cases, followed by a description of the test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 200 000): the number of vertices in the tree.
The second line of each test case contains n integers a_v (0 ≤ a_v ≤ 2): colours of vertices. Gray vertices have a_v=0, white have a_v=1, black have a_v=2.
Each of the next n-1 lines contains two integers u, v (1 ≤ u, v ≤ n): tree edges.
The sum of all n throughout the test is guaranteed to not exceed 200 000.
Output
For each test case, print one integer: the minimum number of operations to solve the problem.
Example
Input
4
2
1 1
1 2
4
1 2 1 2
1 2
2 3
3 4
5
1 1 0 1 2
1 2
2 3
3 4
3 5
8
1 2 1 2 2 2 1 2
1 3
2 3
3 4
4 5
5 6
5 7
5 8
Output
1
3
2
3
Note
<image>
In the first test case, both vertices are white, so you can remove them at the same time.
<image>
In the second test case, three operations are enough. First, we need to remove both black vertices (2 and 4), then separately remove vertices 1 and 3. We can't remove them together because they end up in different connectivity components after vertex 2 is removed.
<image>
In the third test case, we can remove vertices 1, 2, 3, 4 at the same time, because three of them are white and one is grey. After that, we can remove vertex 5.
<image>
In the fourth test case, three operations are enough. One of the ways to solve the problem is to remove all black vertices at once, then remove white vertex 7, and finally, remove connected white vertices 1 and 3.
Submitted Solution:
```
import sys
input = sys.stdin.readline
t=int(input())
def find(x):
while Group[x] != x:
x=Group[x]
return x
def Union(x,y):
if find(x) != find(y):
if Nodes[find(x)] < Nodes[find(y)]:
Nodes[find(y)] += Nodes[find(x)]
Nodes[find(x)] = 0
Group[find(x)] = find(y)
else:
Nodes[find(x)] += Nodes[find(y)]
Nodes[find(y)] = 0
Group[find(y)] = find(x)
for tests in range(t):
n=int(input())
A=list(map(int,input().split()))
E=[]
for i in range(n-1):
x,y=map(int,input().split())
x-=1
y-=1
E.append((x,y))
if (not (2 in A)) or (not (1 in A)):
#print(A)
print(1)
continue
Group = [i for i in range(n+1)]
Nodes = [1]*(n+1)
for x,y in E:
if A[x]!=2 and A[y]!=2:
Union(x,y)
ANS=1
for i in range(n):
if A[i]!=2 and Nodes[i]!=0:
ANS+=1
Group = [i for i in range(n+1)]
Nodes = [1]*(n+1)
for x,y in E:
if A[x]!=1 and A[y]!=1:
Union(x,y)
ANS2=1
for i in range(n):
if A[i]!=1 and Nodes[i]!=0:
ANS2+=1
#print("!",ANS,ANS2,Group,Nodes)
print(min(ANS,ANS2))
``` | instruction | 0 | 35,387 | 13 | 70,774 |
No | output | 1 | 35,387 | 13 | 70,775 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,857 | 13 | 71,714 |
"Correct Solution:
```
N = int(input())
edge = [{} for _ in range(N+1)]
dist = [-1]*(N+1)
for _ in range(N-1):
a,b,c = map(int,input().split())
edge[a][b] = c
edge[b][a] = c
Q,K = map(int,input().split())
dist[K] = 0
dfs_stack = [K]
while dfs_stack:
s = dfs_stack.pop()
for t,t_dist in edge[s].items():
if dist[t] == -1:
dist[t] = dist[s] + t_dist
dfs_stack.append(t)
for _ in range(Q):
x,y = map(int,input().split())
print(dist[x]+dist[y])
``` | output | 1 | 35,857 | 13 | 71,715 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,858 | 13 | 71,716 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
N = int(input())
ABC = [list(map(int, input().split())) for _ in range(N - 1)]
Q, K = map(int, input().split())
XY = [list(map(int, input().split())) for _ in range(Q)]
G = [[] * N for _ in range(N)]
for a, b, c in ABC:
G[a - 1].append((b - 1, c))
G[b - 1].append((a - 1, c))
D = [-1] * N
def dfs(v, d):
D[v] = d
for i, c in G[v]:
if D[i] < 0:
dfs(i, d + c)
dfs(K - 1, 0)
for x, y in XY:
print(D[x - 1] + D[y - 1])
``` | output | 1 | 35,858 | 13 | 71,717 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,859 | 13 | 71,718 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**9)
N = int(input())
T = [[] for _ in range(N+1)]
for _ in range(N-1) :
a,b,c = map(int,input().split())
T[a].append([b,c])
T[b].append([a,c])
Q,K = map(int,input().split())
dist = [None]*(N+1)
def dfs(now,d) :
dist[now] = d
for to,c in T[now] :
if dist[to] is not None :
continue
dfs(to,d+c)
dfs(K,0)
for _ in range(Q) :
u,v = map(int,input().split())
print(dist[u] + dist[v])
``` | output | 1 | 35,859 | 13 | 71,719 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,860 | 13 | 71,720 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**7)
N=int(input())
NODES={}
for i in range(N-1):
a,b,c=map(int,input().split())
if not a in NODES: NODES[a] = []
if not b in NODES: NODES[b] = []
NODES[a].append((b, c))
NODES[b].append((a, c))
Q,K=map(int,input().split())
MP=[-1]*(N+1)
MP[K]=0
def dfs(k):
for i, c in NODES[k]:
if MP[i] == -1:
MP[i] = MP[k] + c
dfs(i)
dfs(K)
# print(MP)
for l,r in [tuple(map(int,input().split())) for _ in range(Q)]:
print(MP[l]+MP[r])
``` | output | 1 | 35,860 | 13 | 71,721 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,861 | 13 | 71,722 |
"Correct Solution:
```
from collections import deque
INF=float('inf')
n=int(input())
g=[[] for _ in range(n)]
for _ in range(n-1):
u,v,w=map(int,input().split())
g[u-1].append((v-1,w))
g[v-1].append((u-1,w))
q,k=map(int,input().split())
ds=[INF]*n
que=deque([(k-1,0)])
while len(que):
u,d=que.popleft()
if ds[u]!=INF:
continue
ds[u]=d
for v,w in g[u]:
que.append((v,d+w))
for _ in range(q):
u,v=map(int,input().split())
print(ds[u-1]+ds[v-1])
``` | output | 1 | 35,861 | 13 | 71,723 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,862 | 13 | 71,724 |
"Correct Solution:
```
n=int(input())
G=[[] for i in range(n)]
for i in range(n-1):
u,v,w=map(int,input().split())
G[u-1].append([v-1,w])
G[v-1].append([u-1,w])
dist=[-1]*n
from collections import deque
Q,k=map(int,input().split())
q=deque()
q.append(k-1)
dist[k-1]=0
while q:
cur=q.popleft()
for nx,nd in G[cur]:
if dist[nx]!=-1:continue
dist[nx]=dist[cur]+nd
q.append(nx)
for i in range(Q):
x,y=map(int,input().split())
x-=1
y-=1
print(dist[x]+dist[y])
``` | output | 1 | 35,862 | 13 | 71,725 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,863 | 13 | 71,726 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(4100000)
N = int(input())
INF = 10 ** 14
edges = [[] for _ in range(N)]
for _ in range(N-1):
a, b, c = map(int,input().split())
edges[a-1].append((b-1, c))
edges[b-1].append((a-1, c))
Q, K = map(int,input().split())
d = [INF] * N
d[K-1] = 0
def dfs(x):
for u, cost in edges[x]:
if d[u] == INF:
d[u] = d[x] + cost
dfs(u)
dfs(K-1)
for _ in range(Q):
x, y = map(int,input().split())
ans = d[x-1] + d[y-1]
print(ans)
``` | output | 1 | 35,863 | 13 | 71,727 |
Provide a correct Python 3 solution for this coding contest problem.
You are given a tree with N vertices.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000 | instruction | 0 | 35,864 | 13 | 71,728 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**6)
n = int(input())
inf = float("inf")
road = [dict() for _ in range(n+1)]
for _ in range(n-1):
a,b,c = map(int, input().split())
road[a][b] = c
road[b][a] = c
q,k = map(int, input().split())
dfs = [inf]*(n+1)
dfs[k] = 0
def dodfs(x):
for i in road[x]:
if dfs[i] == inf:
dfs[i] = dfs[x] + road[x][i]
dodfs(i)
return
dodfs(k)
for _ in range(q):
x,y = map(int, input().split())
print(dfs[x] + dfs[y])
``` | output | 1 | 35,864 | 13 | 71,729 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
N=int(input())
edge=[list(map(int,input().split())) for i in range(N-1)]
inf=10**15
c=[[] for i in range(N)]
for i,j,w in edge:
c[i-1].append((j-1,w))
c[j-1].append((i-1,w))
Q,K=map(int, input().split())
d=[inf]*N
d[K-1]=0
v=[0]*N
import sys
sys.setrecursionlimit(10**5+9)
def dfs(p,v,d):
for n,w in c[p]:
if v[n]==0:
d[n]=min(d[n],d[p]+w)
v[n]=1
dfs(n,v,d)
dfs(K-1,v,d)
xy=[list(map(int,input().split())) for i in range(Q)]
for x,y in xy:
print(d[x-1]+d[y-1])
``` | instruction | 0 | 35,865 | 13 | 71,730 |
Yes | output | 1 | 35,865 | 13 | 71,731 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
n = int(input())
E = [[] for i in range(n)]
for i in range(n-1):
ai,bi,ci = map(int, input().split( ))
ai-=1;bi-=1
E[ai].append((bi,ci))
E[bi].append((ai,ci))
from collections import deque
Q = deque()
q,k = map(int, input().split( ))
k-=1
Q.append(k)
d = [-1]*n
d[k] = 0
while Q:
v = Q.popleft()
for u,c in E[v]:
if d[u]<0:
d[u] = d[v]+c
Q.append(u)
for _ in range(q):
x,y = map(int, input().split( ))
x-=1;y-=1
print(d[x]+d[y])
``` | instruction | 0 | 35,866 | 13 | 71,732 |
Yes | output | 1 | 35,866 | 13 | 71,733 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
input = sys.stdin.readline
n = int(input())
li = [[] for i in range(n)]
for i in range(n-1):
a,b,dist = map(int,input().split())
li[a-1].append((b-1,dist))
li[b-1].append((a-1,dist))
q,k = map(int,input().split())
tdp = [-1]*n
tdp[k-1] = 0
def dfs(x):
for node in li[x]:
if tdp[node[0]] == -1:
tdp[node[0]] = tdp[x] + node[1]
dfs(node[0])
dfs(k-1)
for i in range(q):
a,b = map(int,input().split())
print(tdp[a-1]+tdp[b-1])
``` | instruction | 0 | 35,867 | 13 | 71,734 |
Yes | output | 1 | 35,867 | 13 | 71,735 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
import sys
sys.setrecursionlimit(1000000)
n = int(input())
tree = [[] for i in range(n + 1)]
for i in range(n - 1):
a, b, c = map(int, input().split())
tree[a].append((b, c))
tree[b].append((a, c))
depth = [0] * (n + 1)
def dfs(v, p, d):
depth[v] = d
for to, cost in tree[v]:
if to != p:
dfs(to, v, d + cost)
q, k = map(int, input().split())
dfs(k, 0, 0)
xy = [tuple(map(int, input().split())) for i in range(q)]
for x, y in xy:
print(depth[x] + depth[y])
``` | instruction | 0 | 35,868 | 13 | 71,736 |
Yes | output | 1 | 35,868 | 13 | 71,737 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
#! /usr/bin/env python3
D = {}
L = []
def f(n):
r = []
while n in D:
a, b = D[n]
r.append(a)
n = b
return set(r)
def d(a, b):
return sum(L[x] for x in a.symmetric_difference(b))
def main():
N = int(input())
for i in range(N-1):
a, b, c = map(int, input().split())
D[b] = (i, a)
L.append(c)
Q, K = map(int, input().split())
k = f(K)
for i in range(Q):
x, y = map(int, input().split())
print(d(f(x), k) + d(f(y), k))
if __name__ == '__main__':
main()
``` | instruction | 0 | 35,869 | 13 | 71,738 |
No | output | 1 | 35,869 | 13 | 71,739 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
from scipy.sparse.csgraph import csgraph_from_dense, dijkstra
import sys
input = sys.stdin.readline
N = int(input())
abc = [map(int, input().split()) for i in range(N-1)]
Q, K = map(int, input().split())
xy = [map(int, input().split()) for i in range(Q)]
g = [[10**9+1]*N for i in range(N)]
for a, b, c in abc:
g[a-1][b-1] = c
g[b-1][a-1] = c
G = csgraph_from_dense(g, null_value=10**9+1)
g2 = dijkstra(G)
for x, y in xy:
print(int(g2[x-1][K-1] + g2[K-1][y-1]))
``` | instruction | 0 | 35,870 | 13 | 71,740 |
No | output | 1 | 35,870 | 13 | 71,741 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
N = int(input())
tree = {i:{} for i in range(1,1+N)}
for i in range(N-1):
a,b,c = map(int, input().split())
tree[a][b] = c
tree[b][a] = c
#print(tree)
Q, K = map(int, input().split())
Q_list = []
for i in range(Q):
x,y = map(int, input().split())
Q_list.append([x,y])
#Kから各点までの距離を求めていく
k_dst = {}
def p_dist(node, dist):
if len(tree[node]) == 0:
k_dst[node] = dist
#print("k_dst %d : %d"%(node,dist))
while len(tree[node]) != 0:
i = list(tree[node].keys())[0]
c = tree[node][i]
del tree[node][i]
del tree[i][node]
k_dst[i] = dist + c
p_dist(i, dist + c)
#print("k_dst %d : %d"%(i,k_dst[i]))
p_dist(K,0)
for i in range(Q):
x = Q_list[i][0]
y = Q_list[i][1]
print(k_dst[x]+k_dst[y])
``` | instruction | 0 | 35,871 | 13 | 71,742 |
No | output | 1 | 35,871 | 13 | 71,743 |
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.
Here, a tree is a kind of graph, and more specifically, a connected undirected graph with N-1 edges, where N is the number of its vertices.
The i-th edge (1≤i≤N-1) connects Vertices a_i and b_i, and has a length of c_i.
You are also given Q queries and an integer K. In the j-th query (1≤j≤Q):
* find the length of the shortest path from Vertex x_j and Vertex y_j via Vertex K.
Constraints
* 3≤N≤10^5
* 1≤a_i,b_i≤N (1≤i≤N-1)
* 1≤c_i≤10^9 (1≤i≤N-1)
* The given graph is a tree.
* 1≤Q≤10^5
* 1≤K≤N
* 1≤x_j,y_j≤N (1≤j≤Q)
* x_j≠y_j (1≤j≤Q)
* x_j≠K,y_j≠K (1≤j≤Q)
Input
Input is given from Standard Input in the following format:
N
a_1 b_1 c_1
:
a_{N-1} b_{N-1} c_{N-1}
Q K
x_1 y_1
:
x_{Q} y_{Q}
Output
Print the responses to the queries in Q lines.
In the j-th line j(1≤j≤Q), print the response to the j-th query.
Examples
Input
5
1 2 1
1 3 1
2 4 1
3 5 1
3 1
2 4
2 3
4 5
Output
3
2
4
Input
7
1 2 1
1 3 3
1 4 5
1 5 7
1 6 9
1 7 11
3 2
1 3
4 5
6 7
Output
5
14
22
Input
10
1 2 1000000000
2 3 1000000000
3 4 1000000000
4 5 1000000000
5 6 1000000000
6 7 1000000000
7 8 1000000000
8 9 1000000000
9 10 1000000000
1 1
9 10
Output
17000000000
Submitted Solution:
```
import sys
sys.setrecursionlimit(500000)
N = int(input())
tree = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b, c = map(int, input().split())
tree[a].append((b, c))
tree[b].append((a, c))
Q, K = map(int, input().split())
from functools import lru_cache
@lru_cache(maxsize=None)
def dfs(start, end, dist, f=None):
if start == end:
return 0
for n, d in tree[start]:
if n == f:
continue
if n == end:
return dist + d
else:
result = dfs(n, end, dist+d, start)
if result is not None:
return result
xy = [list(map(int, input().split())) for i in range(Q)]
for i in range(Q):
x, y = xy[i]
print(dfs(x, K, 0) + dfs(K, y, 0))
``` | instruction | 0 | 35,872 | 13 | 71,744 |
No | output | 1 | 35,872 | 13 | 71,745 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,110 | 13 | 72,220 |
Tags: trees
Correct Solution:
```
import collections
def add_on_tree():
n = int(input())
edges = []
for i in range(n-1): edges.append([int(x) for x in input().split()])
graph = collections.defaultdict(set)
for u, v in edges:
graph[u].add(v)
graph[v].add(u)
ans = 'YES'
for node in graph:
if len(graph[node]) == 2:
ans = 'NO'
break
print(ans)
add_on_tree()
exit(0)
``` | output | 1 | 36,110 | 13 | 72,221 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,111 | 13 | 72,222 |
Tags: trees
Correct Solution:
```
n = int(input())
a = []
for i in range(0,n+9):
a.append(0)
for i in range(1,n):
u,v = map(int,input().split())
a[u] = a[u]+1
a[v] = a[v]+1
flag = 1;
for i in range(1,n+1):
if a[i]==2:
flag = 0
if flag==0:
print("NO")
else:
print("YES")
``` | output | 1 | 36,111 | 13 | 72,223 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,112 | 13 | 72,224 |
Tags: trees
Correct Solution:
```
if __name__ == '__main__':
n = int(input())
g = [[] for _ in range(n)]
for _ in range(n - 1):
u, v = map(int, input().split())
g[u - 1].append(v - 1)
g[v - 1].append(u - 1)
if list(filter(lambda x: len(x) == 2, g)):
print("NO")
else:
print("YES")
``` | output | 1 | 36,112 | 13 | 72,225 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,113 | 13 | 72,226 |
Tags: trees
Correct Solution:
```
from math import log2
from collections import defaultdict
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ans))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998244353
n = int(input())
A=defaultdict(list)
ru=[0]*n
for i in range(n-1):
x,y = map(int, input().split())
x-=1
y-=1
A[x].append(y)
A[y].append(x)
ru[x]+=1
ru[y]+=1
num=0
flag=1
for i in range(n):
if ru[i]==2:
flag=0
if flag==1:
print("yes")
else:
print("no")
# the end
``` | output | 1 | 36,113 | 13 | 72,227 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,114 | 13 | 72,228 |
Tags: trees
Correct Solution:
```
import math
def main():
n = int(input())
g = []
for _ in range(n):
g.append([])
for _ in range(n-1):
u, v = map(lambda x: int(x) - 1, input().split())
g[u].append(v)
g[v].append(u)
ok = True
for i in range(n):
if len(g[i]) == 2:
ok = False
break
print('YES' if ok else 'NO')
#print(f(222))
main()
``` | output | 1 | 36,114 | 13 | 72,229 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,115 | 13 | 72,230 |
Tags: trees
Correct Solution:
```
from collections import defaultdict
n = int(input())
hash = defaultdict(list)
for i in range(n-1):
a,b = map(int,input().split())
hash[a].append(b)
hash[b].append(a)
flag = 1
for i in hash.keys():
if len(hash[i]) == 2:
flag = 0
break
if flag:
print('YES')
else:
print('NO')
``` | output | 1 | 36,115 | 13 | 72,231 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,116 | 13 | 72,232 |
Tags: trees
Correct Solution:
```
I = lambda : map(int,input().split())
n = int(input())
#li = list(I())
if n == 1 or n==2 :
exit(print("YES"))
if n==3 :
exit(print("NO"))
lii = [ [] for i in range (n+1)]
for i in range (n-1) :
x , y = I()
lii[x] += [y]
lii[y] += [x]
pp = 0
for i in range (1,n+1) :
if len(lii[i]) == 1 :
continue
elif len(lii[i]) == 2 :
pp = 1
break
if pp == 1 :
exit(print("NO"))
exit(print("YES"))
``` | output | 1 | 36,116 | 13 | 72,233 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image> | instruction | 0 | 36,117 | 13 | 72,234 |
Tags: trees
Correct Solution:
```
n = int(input())
# n, k = map(int, input().split())
# a = [int(i) for i in input().split()]
d = [0 for i in range(n + 1)]
for i in range(n - 1):
a, b = map(int, input().split())
d[a] += 1; d[b] += 1
for val in d:
if val == 2:
print("NO")
exit()
print("YES")
``` | output | 1 | 36,117 | 13 | 72,235 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
n=int(input())
dic={}
for x in range(n-1):
a,b=list(map(int,input().split()))
if a in dic:
dic[a]+=1
else:
dic[a]=1
if b in dic:
dic[b]+=1
else:
dic[b]=1
flag=5
for it in dic:
if dic[it]==2:
flag=6
break
if flag==6:
print("NO")
else:
print("YES")
``` | instruction | 0 | 36,118 | 13 | 72,236 |
Yes | output | 1 | 36,118 | 13 | 72,237 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
n = int(input())
l = [[] for i in range(n+1)]
for y in range(n-1):
u,v = map(int,input().split())
l[u].append(v)
l[v].append(u)
for i in range(1,n+1):
if len(l[i]) == 2:
print("NO")
break
else:
print("YES")
``` | instruction | 0 | 36,119 | 13 | 72,238 |
Yes | output | 1 | 36,119 | 13 | 72,239 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
a = int(input())
A = [0]*a
k=0
for i in range(a-1):
q,w = map(int,input().split())
A[q-1]+=1
if A[q-1]==2:
k+=1
elif A[q-1]==3:
k-=1
A[w-1]+=1
if A[w-1]==2:
k+=1
elif A[w-1]==3:
k-=1
if k == 0:
print('YES')
else:
print('NO')
``` | instruction | 0 | 36,120 | 13 | 72,240 |
Yes | output | 1 | 36,120 | 13 | 72,241 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
n=int(input())
l=[0]*(n+1)
for i in range(n-1):
u,v=input().split()
u,v=[int(u),int(v)]
l[u]+=1
l[v]+=1
l=list(set(l))
#print(l)
if len(l)<=2:
print("YES")
elif l[2]==2:
print("NO")
else:
print("YES")
``` | instruction | 0 | 36,121 | 13 | 72,242 |
Yes | output | 1 | 36,121 | 13 | 72,243 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
from collections import defaultdict, deque, Counter
from sys import stdin, stdout
from heapq import heappush, heappop
import math
import io
import os
import math
import bisect
#?############################################################
def isPrime(x):
for i in range(2, x):
if i*i > x:
break
if (x % i == 0):
return False
return True
#?############################################################
def ncr(n, r, p):
num = den = 1
for i in range(r):
num = (num * (n - i)) % p
den = (den * (i + 1)) % p
return (num * pow(den, p - 2, p)) % p
#?############################################################
def primeFactors(n):
l = []
while n % 2 == 0:
l.append(2)
n = n / 2
for i in range(3, int(math.sqrt(n))+1, 2):
while n % i == 0:
l.append(int(i))
n = n / i
if n > 2:
l.append(n)
return list(set(l))
#?############################################################
def power(x, y, p):
res = 1
x = x % p
if (x == 0):
return 0
while (y > 0):
if ((y & 1) == 1):
res = (res * x) % p
y = y >> 1
x = (x * x) % p
return res
#?############################################################
def sieve(n):
prime = [True for i in range(n+1)]
p = 2
while (p * p <= n):
if (prime[p] == True):
for i in range(p * p, n+1, p):
prime[i] = False
p += 1
return prime
#?############################################################
def digits(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
#?############################################################
def ceil(n, x):
if (n % x == 0):
return n//x
return n//x+1
#?############################################################
def mapin():
return map(int, input().split())
#?############################################################
# input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
# python3 15.py<in>op
n = int(input())
d = [0]*n
for _ in range(n-1):
u, v = mapin()
d[u-1]+=1
d[v-1]-=1
if(d.count(2) == 0):
print("YES")
else:
print("NO")
``` | instruction | 0 | 36,122 | 13 | 72,244 |
No | output | 1 | 36,122 | 13 | 72,245 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
N = int(input())
degree = [0]*(N+1)
data = []
for i in range(N-1):
arr = input()
u,v = [int(x) for x in arr.split(' ')]
data.append([u,v])
degree[u] += 1
degree[v] += 1
#print(degree)
if N==2:
print('YES')
quit()
for i in range(N-1):
u = data[i][0]
v = data[i][1]
if degree[u]==1:
if degree[v]==2:
print('NO')
quit()
elif degree[v]==1:
if degree[u]==2:
print('NO')
quit()
print('YES')
``` | instruction | 0 | 36,123 | 13 | 72,246 |
No | output | 1 | 36,123 | 13 | 72,247 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
import math
n=int(input())
adj=[[] for i in range(n)]
for i in range(n-1):
a,b=map(int,input().split())
adj[a-1].append(b-1)
adj[b-1].append(a-1)
s=0
for i in range(n):
if len(adj[i])==1:
s+=1
if s>math.ceil(n/2):
print("YES")
else:
print("NO")
``` | instruction | 0 | 36,124 | 13 | 72,248 |
No | output | 1 | 36,124 | 13 | 72,249 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Note that this is the first problem of the two similar problems. You can hack this problem only if you solve both problems.
You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any real number x and add x to values written on all edges on the simple path between u and v.
For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -0.5 on the path from 4 to 5.
<image>
Is it true that for any configuration of real numbers written on edges, we can achieve it with a finite number of operations?
Leaf is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice.
Input
The first line contains a single integer n (2 ≤ n ≤ 10^5) — the number of nodes.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), meaning that there is an edge between nodes u and v. It is guaranteed that these edges form a tree.
Output
If there is a configuration of real numbers written on edges of the tree that we can't achieve by performing the operations, output "NO".
Otherwise, output "YES".
You can print each letter in any case (upper or lower).
Examples
Input
2
1 2
Output
YES
Input
3
1 2
2 3
Output
NO
Input
5
1 2
1 3
1 4
2 5
Output
NO
Input
6
1 2
1 3
1 4
2 5
2 6
Output
YES
Note
In the first example, we can add any real x to the value written on the only edge (1, 2).
<image>
In the second example, one of configurations that we can't reach is 0 written on (1, 2) and 1 written on (2, 3).
<image>
Below you can see graphs from examples 3, 4:
<image> <image>
Submitted Solution:
```
n=int(input())
a=[]
b=[]
for i in range(n-1):
x,y=map(int,input().split())
a.append(x)
b.append(y)
if(n==2):
print("YES")
else:
a=set(a)
b=set(b)
for i in a:
if i in b:
b.remove(i)
if(len(b)%2==0):
print("YES")
else:
print("NO")
``` | instruction | 0 | 36,125 | 13 | 72,250 |
No | output | 1 | 36,125 | 13 | 72,251 |
Provide tags and a correct Python 3 solution for this coding contest problem.
In order to fly to the Moon Mister B just needs to solve the following problem.
There is a complete indirected graph with n vertices. You need to cover it with several simple cycles of length 3 and 4 so that each edge is in exactly 2 cycles.
We are sure that Mister B will solve the problem soon and will fly to the Moon. Will you?
Input
The only line contains single integer n (3 ≤ n ≤ 300).
Output
If there is no answer, print -1.
Otherwise, in the first line print k (1 ≤ k ≤ n2) — the number of cycles in your solution.
In each of the next k lines print description of one cycle in the following format: first print integer m (3 ≤ m ≤ 4) — the length of the cycle, then print m integers v1, v2, ..., vm (1 ≤ vi ≤ n) — the vertices in the cycle in the traverse order. Each edge should be in exactly two cycles.
Examples
Input
3
Output
2
3 1 2 3
3 1 2 3
Input
5
Output
6
3 5 4 2
3 3 1 5
4 4 5 2 3
4 4 3 2 1
3 4 2 1
3 3 1 5 | instruction | 0 | 36,584 | 13 | 73,168 |
Tags: constructive algorithms, graphs
Correct Solution:
```
#!/usr/bin/env python3
from collections import defaultdict
DEBUG = False
def main():
if DEBUG:
test()
n = int(input())
paths = cycles(n)
print(len(paths))
for p in paths:
print('%d %s' % (len(p), ' '.join([str(v) for v in p])))
def cycles(n):
"""Builds a set of cycles for a fully connected graph with n vertices."""
if n % 2 == 0:
return even(n)
else:
return odd(n)
def even(n):
"""Builds a set of cycles that a graph with even vertices."""
assert n % 2 == 0
# Base case for complete graph such that V = {1, 2, 3, 4}.
cycles = [[1, 2, 3], [2, 3, 4], [3, 4, 1], [4, 1, 2]]
for i in range(6, n + 1, 2):
a, b = i, i - 1
# Use edges (a, 1), (a, 0), (b, 1), (b, 0), (a, b) exactly twice each.
cycles += [[a, 1, b], [a, 2, b], [a, 1, b, 2]]
# Similar to odd(...) as we are left with 2n - 2 edges to use
# connected to i - 4 of the vertices V' = {3 ... i - 2}. Notice that
# |V'| is even so we can apply the same strategy as in odd(...).
for k in range(3, i - 1, 2):
c, d = k, k + 1
cycles += [[a, c, b, d]] * 2
return cycles
def odd(n):
"""Builds a set of cycles that a graph with odd vertices."""
assert n % 2 == 1
# Base case for complete graph such that V = {1, 2, 3}.
cycles = [[1, 2, 3]] * 2
for i in range(5, n + 1, 2):
a, b = i, i - 1
# Say the new vertices are {a, b}. Since the graph is fully connected
# adding these 2 vertices results in 2n + 1 more edges. We use a length
# 3 cycle a -> b -> 1 > a twice to use up 3 of these edges.
cycles += [[a, b, 1]] * 2
# At this point we are left with 2n + 1 - 3 = 2n - 2 edges to use
# connected to i - 3 of the vertices V' = {2 ... i - 2}. Notice that
# |V'| is even. To use these edges and cover vertices V' we take pairs
# c, d in V' and create two of each path a -> c -> b -> d -> a.
for k in range(2, i - 1, 2):
c, d = k, k + 1
cycles += [[a, c, b, d]] * 2
return cycles
def test():
"""Checks the cycles(...) solver for a bunch of inputs."""
print('Testing...')
for n in range(3, 300, 21):
check(n, cycles(n))
print('Tests pass!')
def check(n, paths):
"""Checks the solution for errors."""
# Check that all vertices are covered.
vertices = set(sum(paths, list()))
assert vertices == set(range(1, n + 1))
# Check that each edge is used exactly twice.
counts = defaultdict(int)
for p in paths:
assert len(p) == 3 or len(p) == 4
assert len(set(p)) == len(p)
for i in range(len(p)):
key = tuple(sorted([p[i - 1], p[i]]))
counts[key] += 1
for i in range(1, n + 1):
for j in range(i + 1, n + 1):
assert counts[(i, j)] == 2
if __name__ == '__main__':
main()
``` | output | 1 | 36,584 | 13 | 73,169 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.