message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
from collections import deque
m, k = list(map(int, input().split()))
G = [set() for _ in range(m + 1)]
q, nq = deque(), deque()
for _ in range(m - 1):
u, v = list(map(int, input().split()))
G[u].add(v)
G[v].add(u)
for u in range(1, m + 1):
if len(G[u]) == 1:
q.append(u)
step = 0
removed = 0
ok = True
while removed < m - 1:
each = {}
for u in q:
nxt = G[u].pop()
G[nxt].remove(u)
each[nxt] = each.get(nxt, 0) + 1
removed += 1
if len(G[nxt]) == 0:
break
if len(G[nxt]) == 1:
nq.append(nxt)
if any(v < 3 for k,v in each.items()):
ok = False
break
q, nq = nq, deque()
step += 1
if ok and step == k and removed == m - 1:
print('Yes')
else:
print('No')
``` | instruction | 0 | 90,132 | 13 | 180,264 |
Yes | output | 1 | 90,132 | 13 | 180,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
from sys import stdin
from collections import deque
n, k = map(int, stdin.readline().split())
graph = [[] for _ in range(n)]
leaf = -1
for _ in range(n-1):
a,b = map(int,stdin.readline().split())
graph[a - 1].append(b - 1)
graph[b - 1].append(a - 1)
def bfs(G, s):
# la cola comienza con el vertice desde el cual hacemos bfs
Q = deque()
Q.append(s)
# al inicio todas las distancias comienzan en infinito, por las
# restricciones del problema ningun camino va a ser de ese tamanno
infinite = 10 ** 6
d = [infinite]*n
parent = [-1]*n
valid = True
# la distancia del vertice raiz es 0
d[s] = 0
while Q:
# visitamos u
u = Q.popleft()
not_visited_count = 0
# visitamos cada adyacente de u
for v in G[u]:
# si no lo hemos visitado, le ponemos distancia y
# lo agregamos a la cola para visitar sus adyacentes
if d[v] == infinite:
d[v] = d[u] + 1
parent[v] = u
Q.append(v)
not_visited_count += 1
if not_visited_count < 3 and d[u] != k:
valid = False
# retornamos el array d, que es el de las distancias del
# nodo s al resto de los nodos del grafo
return d, parent, valid
leaf = -1
for i,v in enumerate(graph):
if len(v) == 1:
leaf = i
break
d, parent, _ = bfs(graph,leaf)
center = -1
farthest_leaf = -1
diameter = 2*k
for i,level in enumerate(d):
if level == diameter:
farthest_leaf = i
break
if len(graph[farthest_leaf]) != 1 or farthest_leaf == -1:
print("NO")
exit()
for _ in range(k):
center = parent[farthest_leaf]
farthest_leaf = center
if center == -1:
print("NO")
exit()
_, _, valid = bfs(graph,center)
if valid:
print("YES")
else:
print("NO")
``` | instruction | 0 | 90,133 | 13 | 180,266 |
Yes | output | 1 | 90,133 | 13 | 180,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
WQ=input().split()
n1=int(WQ[0])
k=int(WQ[1])
L1=[]
for i in range(n1):
L1.append([])
for i in range(n1-1):
X=input().split()
x1=int(X[0])-1
x2=int(X[1])-1
L1[x1].append(x2)
L1[x2].append(x1)
t=True
tres=0
for i in range(n1):
l=len(L1[i])
if l==1:
pass
elif l==3:
tres+=1
elif l>3:
pass
else:
t=False
break
if t:
if tres>1:
print("No")
else:
print("Yes")
else:
print("No")
``` | instruction | 0 | 90,134 | 13 | 180,268 |
No | output | 1 | 90,134 | 13 | 180,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
WQ=input().split()
n1=int(WQ[0])
k=int(WQ[1])
L1=[]
for i in range(n1):
L1.append([])
for i in range(n1-1):
X=input().split()
x1=int(X[0])-1
x2=int(X[1])-1
L1[x1].append(x2)
L1[x2].append(x1)
t=True
tres=0
for i in range(n1):
l=len(L1[i])
if l==1:
pass
elif l==3:
tres+=1
elif l>3:
pass
else:
t=False
if t:
if tres>1:
print("No")
else:
print("Yes")
else:
print("No")
``` | instruction | 0 | 90,135 | 13 | 180,270 |
No | output | 1 | 90,135 | 13 | 180,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
# region fastio
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# ------------------------------
def RL(): return map(int, sys.stdin.readline().rstrip().split())
def RLL(): return list(map(int, sys.stdin.readline().rstrip().split()))
def N(): return int(input())
def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0
def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0
def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2)
def toord(c): return ord(c)-ord('a')
def lcm(a, b): return a*b//lcm(a, b)
mod = 998244353
INF = float('inf')
from math import factorial, sqrt, ceil, floor, gcd
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
# ------------------------------
# f = open('./input.txt')
# sys.stdin = f
def main():
n, k = RL()
ind = [0]*(n+1)
gp = [[] for _ in range(n+1)]
for _ in range(n-1):
f, t = RL()
ind[f]+=1
ind[t]+=1
gp[f].append(t)
gp[t].append(f)
orind = ind.copy()
if not any(len(gp[i]) >= 3 for i in range(n+1)):
print('No')
sys.exit()
q = []
for i in range(1, n+1):
if ind[i]==1:
q.append(i)
tag = False
num = 0
rec = []
ct = -1
while q:
nq = []
num+=1
while q:
nd = q.pop()
for nex in gp[nd]:
ind[nex]-=1
if ind[nex]==1:
rec.append(nex)
nq.append(nex)
q = nq
if len(q)==1 and ind[q[0]]==0:
ct = q[0]
for i in rec:
if (i!=ct and orind[i]<4) or orind[i]<3:
tag = True
if tag or num!=k+1 or ct==-1:
print('No')
else:
print('Yes')
if __name__ == "__main__":
main()
``` | instruction | 0 | 90,136 | 13 | 180,272 |
No | output | 1 | 90,136 | 13 | 180,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Someone give a strange birthday present to Ivan. It is hedgehog — connected undirected graph in which one vertex has degree at least 3 (we will call it center) and all other vertices has degree 1. Ivan thought that hedgehog is too boring and decided to make himself k-multihedgehog.
Let us define k-multihedgehog as follows:
* 1-multihedgehog is hedgehog: it has one vertex of degree at least 3 and some vertices of degree 1.
* For all k ≥ 2, k-multihedgehog is (k-1)-multihedgehog in which the following changes has been made for each vertex v with degree 1: let u be its only neighbor; remove vertex v, create a new hedgehog with center at vertex w and connect vertices u and w with an edge. New hedgehogs can differ from each other and the initial gift.
Thereby k-multihedgehog is a tree. Ivan made k-multihedgehog but he is not sure that he did not make any mistakes. That is why he asked you to check if his tree is indeed k-multihedgehog.
Input
First line of input contains 2 integers n, k (1 ≤ n ≤ 10^{5}, 1 ≤ k ≤ 10^{9}) — number of vertices and hedgehog parameter.
Next n-1 lines contains two integers u v (1 ≤ u, v ≤ n; u ≠ v) — indices of vertices connected by edge.
It is guaranteed that given graph is a tree.
Output
Print "Yes" (without quotes), if given graph is k-multihedgehog, and "No" (without quotes) otherwise.
Examples
Input
14 2
1 4
2 4
3 4
4 13
10 5
11 5
12 5
14 5
5 13
6 7
8 6
13 6
9 6
Output
Yes
Input
3 1
1 3
2 3
Output
No
Note
2-multihedgehog from the first example looks like this:
<image>
Its center is vertex 13. Hedgehogs created on last step are: [4 (center), 1, 2, 3], [6 (center), 7, 8, 9], [5 (center), 10, 11, 12, 13].
Tree from second example is not a hedgehog because degree of center should be at least 3.
Submitted Solution:
```
# ---------------------------iye ha aam zindegi---------------------------------------------
import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
mod = 10 ** 9 + 7
mod1 = 998244353
# ------------------------------warmup----------------------------
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192
sys.setrecursionlimit(300000)
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
input = lambda: sys.stdin.readline().rstrip("\r\n")
# -------------------game starts now----------------------------------------------------import math
class TreeNode:
def __init__(self, k, v):
self.key = k
self.value = v
self.left = None
self.right = None
self.parent = None
self.height = 1
self.num_left = 1
self.num_total = 1
class AvlTree:
def __init__(self):
self._tree = None
def add(self, k, v):
if not self._tree:
self._tree = TreeNode(k, v)
return
node = self._add(k, v)
if node:
self._rebalance(node)
def _add(self, k, v):
node = self._tree
while node:
if k < node.key:
if node.left:
node = node.left
else:
node.left = TreeNode(k, v)
node.left.parent = node
return node.left
elif node.key < k:
if node.right:
node = node.right
else:
node.right = TreeNode(k, v)
node.right.parent = node
return node.right
else:
node.value = v
return
@staticmethod
def get_height(x):
return x.height if x else 0
@staticmethod
def get_num_total(x):
return x.num_total if x else 0
def _rebalance(self, node):
n = node
while n:
lh = self.get_height(n.left)
rh = self.get_height(n.right)
n.height = max(lh, rh) + 1
balance_factor = lh - rh
n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
n.num_left = 1 + self.get_num_total(n.left)
if balance_factor > 1:
if self.get_height(n.left.left) < self.get_height(n.left.right):
self._rotate_left(n.left)
self._rotate_right(n)
elif balance_factor < -1:
if self.get_height(n.right.right) < self.get_height(n.right.left):
self._rotate_right(n.right)
self._rotate_left(n)
else:
n = n.parent
def _remove_one(self, node):
"""
Side effect!!! Changes node. Node should have exactly one child
"""
replacement = node.left or node.right
if node.parent:
if AvlTree._is_left(node):
node.parent.left = replacement
else:
node.parent.right = replacement
replacement.parent = node.parent
node.parent = None
else:
self._tree = replacement
replacement.parent = None
node.left = None
node.right = None
node.parent = None
self._rebalance(replacement)
def _remove_leaf(self, node):
if node.parent:
if AvlTree._is_left(node):
node.parent.left = None
else:
node.parent.right = None
self._rebalance(node.parent)
else:
self._tree = None
node.parent = None
node.left = None
node.right = None
def remove(self, k):
node = self._get_node(k)
if not node:
return
if AvlTree._is_leaf(node):
self._remove_leaf(node)
return
if node.left and node.right:
nxt = AvlTree._get_next(node)
node.key = nxt.key
node.value = nxt.value
if self._is_leaf(nxt):
self._remove_leaf(nxt)
else:
self._remove_one(nxt)
self._rebalance(node)
else:
self._remove_one(node)
def get(self, k):
node = self._get_node(k)
return node.value if node else -1
def _get_node(self, k):
if not self._tree:
return None
node = self._tree
while node:
if k < node.key:
node = node.left
elif node.key < k:
node = node.right
else:
return node
return None
def get_at(self, pos):
x = pos + 1
node = self._tree
while node:
if x < node.num_left:
node = node.left
elif node.num_left < x:
x -= node.num_left
node = node.right
else:
return (node.key, node.value)
raise IndexError("Out of ranges")
@staticmethod
def _is_left(node):
return node.parent.left and node.parent.left == node
@staticmethod
def _is_leaf(node):
return node.left is None and node.right is None
def _rotate_right(self, node):
if not node.parent:
self._tree = node.left
node.left.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.left
node.left.parent = node.parent
else:
node.parent.right = node.left
node.left.parent = node.parent
bk = node.left.right
node.left.right = node
node.parent = node.left
node.left = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
def _rotate_left(self, node):
if not node.parent:
self._tree = node.right
node.right.parent = None
elif AvlTree._is_left(node):
node.parent.left = node.right
node.right.parent = node.parent
else:
node.parent.right = node.right
node.right.parent = node.parent
bk = node.right.left
node.right.left = node
node.parent = node.right
node.right = bk
if bk:
bk.parent = node
node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
node.num_left = 1 + self.get_num_total(node.left)
@staticmethod
def _get_next(node):
if not node.right:
return node.parent
n = node.right
while n.left:
n = n.left
return n
# -----------------------------------------------binary seacrh tree---------------------------------------
class SegmentTree1:
def __init__(self, data, default=0, func=lambda a, b: max(a, b)):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------game starts now----------------------------------------------------import math
class SegmentTree:
def __init__(self, data, default=0, func=lambda a, b: a + b):
"""initialize the segment tree with data"""
self._default = default
self._func = func
self._len = len(data)
self._size = _size = 1 << (self._len - 1).bit_length()
self.data = [default] * (2 * _size)
self.data[_size:_size + self._len] = data
for i in reversed(range(_size)):
self.data[i] = func(self.data[i + i], self.data[i + i + 1])
def __delitem__(self, idx):
self[idx] = self._default
def __getitem__(self, idx):
return self.data[idx + self._size]
def __setitem__(self, idx, value):
idx += self._size
self.data[idx] = value
idx >>= 1
while idx:
self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
idx >>= 1
def __len__(self):
return self._len
def query(self, start, stop):
if start == stop:
return self.__getitem__(start)
stop += 1
start += self._size
stop += self._size
res = self._default
while start < stop:
if start & 1:
res = self._func(res, self.data[start])
start += 1
if stop & 1:
stop -= 1
res = self._func(res, self.data[stop])
start >>= 1
stop >>= 1
return res
def __repr__(self):
return "SegmentTree({0})".format(self.data)
# -------------------------------iye ha chutiya zindegi-------------------------------------
class Factorial:
def __init__(self, MOD):
self.MOD = MOD
self.factorials = [1, 1]
self.invModulos = [0, 1]
self.invFactorial_ = [1, 1]
def calc(self, n):
if n <= -1:
print("Invalid argument to calculate n!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.factorials):
return self.factorials[n]
nextArr = [0] * (n + 1 - len(self.factorials))
initialI = len(self.factorials)
prev = self.factorials[-1]
m = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = prev * i % m
self.factorials += nextArr
return self.factorials[n]
def inv(self, n):
if n <= -1:
print("Invalid argument to calculate n^(-1)")
print("n must be non-negative value. But the argument was " + str(n))
exit()
p = self.MOD
pi = n % p
if pi < len(self.invModulos):
return self.invModulos[pi]
nextArr = [0] * (n + 1 - len(self.invModulos))
initialI = len(self.invModulos)
for i in range(initialI, min(p, n + 1)):
next = -self.invModulos[p % i] * (p // i) % p
self.invModulos.append(next)
return self.invModulos[pi]
def invFactorial(self, n):
if n <= -1:
print("Invalid argument to calculate (n^(-1))!")
print("n must be non-negative value. But the argument was " + str(n))
exit()
if n < len(self.invFactorial_):
return self.invFactorial_[n]
self.inv(n) # To make sure already calculated n^-1
nextArr = [0] * (n + 1 - len(self.invFactorial_))
initialI = len(self.invFactorial_)
prev = self.invFactorial_[-1]
p = self.MOD
for i in range(initialI, n + 1):
prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p
self.invFactorial_ += nextArr
return self.invFactorial_[n]
class Combination:
def __init__(self, MOD):
self.MOD = MOD
self.factorial = Factorial(MOD)
def ncr(self, n, k):
if k < 0 or n < k:
return 0
k = min(k, n - k)
f = self.factorial
return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD
# --------------------------------------iye ha combinations ka zindegi---------------------------------
def powm(a, n, m):
if a == 1 or n == 0:
return 1
if n % 2 == 0:
s = powm(a, n // 2, m)
return s * s % m
else:
return a * powm(a, n - 1, m) % m
# --------------------------------------iye ha power ka zindegi---------------------------------
def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
z = [x for _, x in sorted(zipped_pairs)]
return z
# --------------------------------------------------product----------------------------------------
def product(l):
por = 1
for i in range(len(l)):
por *= l[i]
return por
# --------------------------------------------------binary----------------------------------------
def binarySearchCount(arr, n, key):
left = 0
right = n - 1
count = 0
while (left <= right):
mid = int((right + left) / 2)
# Check if middle element is
# less than or equal to key
if (arr[mid] < key):
count = mid + 1
left = mid + 1
# If key is smaller, ignore right half
else:
right = mid - 1
return count
# --------------------------------------------------binary----------------------------------------
def countdig(n):
c = 0
while (n > 0):
n //= 10
c += 1
return c
def binary(x, length):
y = bin(x)[2:]
return y if len(y) >= length else "0" * (length - len(y)) + y
def countGreater(arr, n, k):
l = 0
r = n - 1
# Stores the index of the left most element
# from the array which is greater than k
leftGreater = n
# Finds number of elements greater than k
while (l <= r):
m = int(l + (r - l) / 2)
if (arr[m] >= k):
leftGreater = m
r = m - 1
# If mid element is less than
# or equal to k update l
else:
l = m + 1
# Return the count of elements
# greater than k
return (n - leftGreater)
# --------------------------------------------------binary------------------------------------
n,k=map(int,input().split())
graph=defaultdict(list)
deg=[0]*n
for i in range(n-1):
a,b=map(int,input().split())
graph[a-1].append(b-1)
graph[b-1].append(a-1)
deg[a-1]+=1
deg[b-1]+=1
for i in range(n):
if deg[i]==2:
print("No")
if n == 88573:
print(1234)
sys.exit(0)
s=set()
for i in range(n):
if deg[i]==1:
if len(s)<2:
s.add(graph[i][0])
if deg[graph[i][0]]<3:
if n == 88573:
print(4123)
print("No")
sys.exit(0)
f=0
e=set()
for i in s:
for j in graph[i]:
if deg[j]==1:
e.add(j)
break
if len(e)==2:
break
e=list(e)
dis=[0]*n
def BFS(s,des):
visited = [False] * (len(graph))
pre=[-1]*n
queue = []
queue.append(s)
visited[s] = True
while queue:
s = queue.pop(0)
for i in graph[s]:
if visited[i] == False:
visited[i]=True
pre[i]=s
dis[i]=dis[s]+1
queue.append(i)
if i==des:
return pre
return pre
def DFS(v,visited,dep):
visited[v] = True
r=0
for i in graph[v]:
if visited[i] == False:
r+=DFS(i, visited,dep+1)
if deg[v]==1 and dep!=k:
return -1
else:
return r
pre=BFS(e[0],e[1])
r=e[1]
e=[r]
er=r
for i in range(dis[e[0]]):
e.append(pre[er])
er=pre[er]
center=e[len(e)//2]
for i in range(n):
if deg[i]==3 and i!=center:
if n == 88573:
print(1235,center,deg[center],i,deg[i])
print("No")
sys.exit(0)
f=DFS(center,[False]*n,0)
if f==0:
print("Yes")
else:
if n==88573:
print(123)
print("No")
``` | instruction | 0 | 90,137 | 13 | 180,274 |
No | output | 1 | 90,137 | 13 | 180,275 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,182 | 13 | 180,364 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
class DSU:
# Disjoint Set Union (Union-Find) Data Structure
def __init__(self, nodes):
# Dictionary of parents
self.p = [i for i in range(nodes)]
# Dictionary of ranks
self.r = [0 for i in range(nodes)]
# Dictionary of sizes
self.s = [1 for i in range(nodes)]
def nonrecurive_get(self, u):
# Returns the identifier of the set that contains u, includes path compression
v = u
while self.p[v] != v:
v = self.p[v]
while self.p[u] != u:
u, self.p[u] = self.p[u], v
return u
def get(self, u):
# Recursive Returns the identifier of the set that contains u, includes path compression
if u != self.p[u]:
self.p[u] = self.get(self.p[u])
return self.p[u]
def union(self, u, v):
# Unites the sets with identifiers u and v
u = self.get(u)
v = self.get(v)
if u != v:
if self.r[u] > self.r[v]:
u, v = v, u
self.p[u] = v
if self.r[u] == self.r[v]:
self.r[v] += 1
self.s[v] += self.s[u]
def size(self, u):
u = self.get(u)
return self.s[u]
def solve():
n = int(input())
dsus = [DSU(n), DSU(n)]
for edge in range(n - 1):
x, y, c = [int(s) for s in input().split(' ')]
dsus[c].union(x - 1, y - 1)
S = 0
for v in range(n):
S += (dsus[0].size(v) * dsus[1].size(v) - 1)
return S
print(solve())
``` | output | 1 | 90,182 | 13 | 180,365 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,183 | 13 | 180,366 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
class UnionFind:
def __init__(self, N):
self.par = [i for i in range(N)]
self.rank = [1 for i in range(N)]
self.rank[0] = 0
def union(self, x, y):
if not self.is_same_set(x, y):
par_x = self.find_par(x)
par_y = self.find_par(y)
if self.rank[par_x] > self.rank[par_y]:
self.rank[par_x] += self.rank[par_y]
self.rank[par_y] = 0
self.par[par_y] = par_x
else:
self.rank[par_y] += self.rank[par_x]
self.rank[par_x] = 0
self.par[par_x] = par_y
def find_par(self, x):
if self.par[x] == x: return x
self.par[x] = self.find_par(self.par[x])
return self.par[x]
def is_same_set(self, x, y):
return self.find_par(x) == self.find_par(y)
def size(self, x):
return self.rank[self.find_par(x)]
# 2 unionfind, para 0 e para 1 formando 2 florestas
# lista de adj
# verificar todos os componentes existentes e adicionar na resposta n * (n-1)
n = int(input())
adj = [[] for i in range(n+1)]
uf0 = UnionFind(n+1)
uf1 = UnionFind(n+1)
for i in range(n-1):
x, y, c = map(int, input().split())
if c == 0:
uf0.union(x, y)
else:
uf1.union(x, y)
adj[x].append(y)
adj[y].append(x)
for i in range(n+1):
uf0.find_par(i)
uf1.find_par(i)
resp = 0
for i in set(uf0.par):
resp += uf0.rank[i] * (uf0.rank[i] - 1)
for i in set(uf1.par):
resp += uf1.rank[i] * (uf1.rank[i] - 1)
# pra cada componente do 0-uf verificar se existe esse vertice na 1-uf e ele for conectado com alguém, se sim, multiplicar (n-1)*(m-1) sendo n o componente da 0-uf e m o componente da 1-f e adicionar na resposta
for i in range(len(uf0.par)):
if uf0.rank[uf0.find_par(i)] > 1:
if uf1.rank[uf1.find_par(i)] > 1:
resp += (uf0.rank[uf0.find_par(i)] - 1) * (uf1.rank[uf1.find_par(i)] - 1)
print(resp)
``` | output | 1 | 90,183 | 13 | 180,367 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,184 | 13 | 180,368 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
class Deque:
def __init__(self):
self.buff = [0] * 400000
self.l = 0
self.r = 0
def append(self, x):
self.buff[self.r] = x
self.r = self.r + 1
def popleft(self):
old_left = self.l
self.l = self.l + 1
return self.buff[old_left]
def __bool__(self):
return self.l != self.r
q = Deque()
def bfs(source, graph, mark, num, fcount):
visited = [source]
mark[source] = True
q.append(source)
while q:
u = q.popleft()
for v, c in g[u]:
if c == num and not mark[v]:
mark[v] = True
visited.append(v)
q.append(v)
if len(visited) > 1:
for u in visited:
fcount[u] = len(visited)
n = int(input())
edges = [tuple(map(int, input().split())) for _ in range(0, n - 1)]
g = [[] for _ in range(0, n)]
cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)]
for u, v, c in edges:
g[u - 1].append((v - 1, c))
g[v - 1].append((u - 1, c))
res = 0
for link in range(0, 2):
mark = [False] * n
for u in range(0, n):
if not mark[u]:
bfs(u, g, mark, link, cnt[link])
res += cnt[link][u] * (cnt[link][u] - 1)
for i in range(0, n):
if cnt[0][i] > 0 and cnt[1][i] > 1:
res += (cnt[0][i] - 1) * (cnt[1][i] - 1)
print(int(res))
``` | output | 1 | 90,184 | 13 | 180,369 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,185 | 13 | 180,370 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
import sys;sys.setrecursionlimit(10**9)
class UnionFind:
def __init__(self,n):
self.n=[-1]*n
self.r=[0]*n
self.siz=n
def find_root(self,x):
if self.n[x]<0:
return x
else:
self.n[x]=self.find_root(self.n[x])
return self.n[x]
def unite(self,x,y):
x=self.find_root(x)
y=self.find_root(y)
if x==y:return
elif self.r[x]>self.r[y]:
self.n[x]+=self.n[y]
self.n[y]=x
else:
self.n[y]+=self.n[x]
self.n[x]=y
if self.r[x]==self.r[y]:
self.r[y]+=1
self.siz-=1
def root_same(self,x,y):
return self.find_root(x)==self.find_root(y)
def count(self,x):
return -self.n[self.find_root(x)]
def size(self):
return self.siz
n=int(input())
ouf=UnionFind(n)
zuf=UnionFind(n)
for _ in range(n-1):
a,b,c=map(int,input().split())
a-=1
b-=1
if c==0:
zuf.unite(a,b)
else:
ouf.unite(a,b)
ans=0
for i in range(n):
m=zuf.count(i)
if zuf.find_root(i)==i:ans+=m*(m-1)
mm=ouf.count(i)
if ouf.find_root(i)==i:ans+=mm*(mm-1)
ans+=(m-1)*(mm-1)
print(ans)
``` | output | 1 | 90,185 | 13 | 180,371 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,186 | 13 | 180,372 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
from collections import defaultdict
def colour(a, graph, cur, i):
top = set()
top.add(i)
while len(top):
x = top.pop()
a[x] = cur
for y in graph[x]:
if a[y] == 0:
top.add(y)
def colour_graph(a, graph, n):
cur = 0
for i in range(1, n + 1):
if a[i] or i not in graph:
continue
else:
cur += 1
colour(a, graph, cur, i)
def count(col):
ans = 0
for el in col:
if col[el] > 1:
ans += col[el]*(col[el] - 1)
return ans
n = int(input())
graph0 = defaultdict(set)
graph1 = defaultdict(set)
vertex0 = set()
a0 = [0]*(n + 1)
a1 = [0]*(n + 1)
for i in range(n - 1):
x, y, c = map(int, input().split())
if c == 0:
graph0[x].add(y)
graph0[y].add(x)
vertex0.add(x)
vertex0.add(y)
else:
graph1[x].add(y)
graph1[y].add(x)
colour_graph(a0, graph0, n)
colour_graph(a1, graph1, n)
answer = 0
col0 = defaultdict(int)
col1 = defaultdict(int)
for i in range(n + 1):
if a0[i]:
col0[a0[i]] += 1
if a1[i]:
col1[a1[i]] += 1
answer += count(col0) + count(col1)
col = defaultdict(int)
for v in vertex0:
col[a1[v]] += col0[a0[v]] - 1
for el in col:
if el:
answer += col[el]*(col1[el] - 1)
print(answer)
``` | output | 1 | 90,186 | 13 | 180,373 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,187 | 13 | 180,374 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
n = int(input())
class UnionFind(object):
def __init__(self, n): # 初始化uf数组和组数目
self.count = n
self.uf = [i for i in range(n)]
self.size = [1] * n # 每个联通分量的size
def find(self, x): # 判断节点所属于的组
while x != self.uf[x]:
self.uf[x] = self.uf[self.uf[x]]
x = self.uf[x]
return self.uf[x]
def union(self, x, y): # 连接两个节点
x_root = self.find(x)
y_root = self.find(y)
if x_root == y_root:
return
if self.size[x_root] < self.size[y_root]:
x_root, y_root = y_root, x_root
self.uf[y_root] = x_root
self.size[x_root] += self.size[y_root]
self.size[y_root] = 0
self.count -= 1
uf0 = UnionFind(n)
uf1 = UnionFind(n)
for i in range(n - 1):
a, b, c = [int(j) for j in input().split(' ')]
if c == 0:
uf0.union(a-1, b-1)
else:
uf1.union(a-1, b-1)
res = 0
from collections import *
cnt0 = Counter(uf0.find(k) for k in range(n))
cnt1 = Counter(uf1.find(k) for k in range(n))
for c0, n0 in cnt0.items():
res += n0 * (n0 - 1)
for c1, n1 in cnt1.items():
res += n1 * (n1 - 1)
for i in range(n):
n0 = cnt0[uf0.find(i)]
n1 = cnt1[uf1.find(i)]
res += (n0 - 1) * (n1 - 1)
print(res)
"""
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
"""
``` | output | 1 | 90,187 | 13 | 180,375 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,188 | 13 | 180,376 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
class UnionFind():
def __init__(self, n):
self.n = n
self.root = [-1]*(n+1)
self.rnk = [0]*(n+1)
def Find_Root(self, x):
if(self.root[x] < 0):
return x
else:
self.root[x] = self.Find_Root(self.root[x])
return self.root[x]
def Unite(self, x, y):
x = self.Find_Root(x)
y = self.Find_Root(y)
if(x == y):
return
elif(self.rnk[x] > self.rnk[y]):
self.root[x] += self.root[y]
self.root[y] = x
else:
self.root[y] += self.root[x]
self.root[x] = y
if(self.rnk[x] == self.rnk[y]):
self.rnk[y] += 1
def isSameGroup(self, x, y):
return self.Find_Root(x) == self.Find_Root(y)
def Count(self, x):
return -self.root[self.Find_Root(x)]
import sys
input = sys.stdin.readline
N = int(input())
uni0 = UnionFind(N)
uni1 = UnionFind(N)
for _ in range(N-1):
a, b, c = map(int, input().split())
if c == 0:
uni0.Unite(a-1, b-1)
else:
uni1.Unite(a-1, b-1)
g0 = {}
g1 = {}
for i in range(N):
if uni0.Count(i) != 1:
r = uni0.Find_Root(i)
if not r in g0.keys():
g0[r] = [i]
else:
g0[r].append(i)
if uni1.Count(i) != 1:
r = uni1.Find_Root(i)
if not r in g1.keys():
g1[r] = [i]
else:
g1[r].append(i)
ans = 0
for v_list in g1.values():
c = 0
for n in v_list:
if uni0.Count(n) == 1:
c += 1
l = len(v_list)
ans += c*(l-1)
for v_list in g0.values():
c = 0
for n in v_list:
if uni1.Count(n) != 1:
r = uni1.Find_Root(n)
c += len(g1[r])-1
c += len(v_list)-1
ans += len(v_list)*c
print(ans)
``` | output | 1 | 90,188 | 13 | 180,377 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image> | instruction | 0 | 90,189 | 13 | 180,378 |
Tags: dfs and similar, divide and conquer, dp, dsu, trees
Correct Solution:
```
from collections import deque
from sys import stdin
def bfs(source, graph, mark, num, fcount):
visited = [source]
q = deque()
mark[source] = True
q.append(source)
while q:
u = q.popleft()
for v in graph[u]:
if not mark[v]:
mark[v] = True
visited.append(v)
q.append(v)
for u in visited:
fcount[u] = len(visited)
n = int(stdin.readline())
g = [[[] for _ in range(0, n)] for _ in range(0, 2)]
cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)]
for line in stdin.readlines():
u, v, c = map(int, line.split())
g[c][u - 1].append(v - 1)
g[c][v - 1].append(u - 1)
res = 0
for link in range(0, 2):
mark = [False] * n
for u in range(0, n):
if not mark[u] and len(g[link][u]) > 0:
bfs(u, g[link], mark, link, cnt[link])
res += cnt[link][u] * (cnt[link][u] - 1)
for i in range(0, n):
if cnt[0][i] > 0 and cnt[1][i] > 1:
res += (cnt[0][i] - 1) * (cnt[1][i] - 1)
print(int(res))
``` | output | 1 | 90,189 | 13 | 180,379 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
from collections import deque
from sys import stdin
def bfs(source, graph, mark, fcount):
visited = [source]
q = deque()
mark[source] = True
q.append(source)
while q:
u = q.popleft()
for v in graph[u]:
if not mark[v]:
mark[v] = True
visited.append(v)
q.append(v)
for u in visited:
fcount[u] = len(visited)
def main():
n = int(stdin.readline())
g = [[[] for _ in range(0, n)] for _ in range(0, 2)]
cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)]
for line in stdin.readlines():
u, v, c = map(int, line.split())
g[c][u - 1].append(v - 1)
g[c][v - 1].append(u - 1)
res = 0
for link in range(0, 2):
mark = [False] * n
for u in range(0, n):
if not mark[u] and len(g[link][u]) > 0:
bfs(u, g[link], mark, cnt[link])
res += cnt[link][u] * (cnt[link][u] - 1)
for i in range(0, n):
if cnt[0][i] > 0 and cnt[1][i] > 1:
res += (cnt[0][i] - 1) * (cnt[1][i] - 1)
print(int(res))
main()
``` | instruction | 0 | 90,190 | 13 | 180,380 |
Yes | output | 1 | 90,190 | 13 | 180,381 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
from collections import deque
def bfs(source, graph, mark, num, fcount):
visited = [source]
q = deque()
mark[source] = True
q.append(source)
while q:
u = q.popleft()
for v, c in g[u]:
if c == num and not mark[v]:
mark[v] = True
visited.append(v)
q.append(v)
if len(visited) > 1:
for u in visited:
fcount[u] = len(visited)
n = int(input())
edges = [tuple(map(int, input().split())) for _ in range(0, n - 1)]
g = [[] for _ in range(0, n)]
cnt = [[0 for _ in range(0, n)] for _ in range(0, 2)]
for u, v, c in edges:
g[u - 1].append((v - 1, c))
g[v - 1].append((u - 1, c))
res = 0
for link in range(0, 2):
mark = [False] * n
for u in range(0, n):
if not mark[u]:
bfs(u, g, mark, link, cnt[link])
res += cnt[link][u] * (cnt[link][u] - 1)
for i in range(0, n):
if cnt[0][i] > 0 and cnt[1][i] > 1:
res += (cnt[0][i] - 1) * (cnt[1][i] - 1)
print(int(res))
``` | instruction | 0 | 90,191 | 13 | 180,382 |
Yes | output | 1 | 90,191 | 13 | 180,383 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
import sys
input = sys.stdin.readline
sys.setrecursionlimit(2*10**5)
I = lambda : list(map(int,input().split()))
n,=I()
r=[[1 for i in range(n)],[1 for i in range(n)]]
p=[[i for i in range(n)],[i for i in range(n)]]
def find(x,c):
if x!=p[c][x]:
p[c][x]=find(p[c][x],c)
return p[c][x]
def union(a,b,c):
x=find(a,c)
y=find(b,c)
mm=min(x,y)
if x!=y:
p[c][y]=p[c][x]=mm
r[c][mm]+=r[c][max(x,y)]
an=0
for i in range(n-1):
a,b,c=I()
union(a-1,b-1,c)
vis=[0]*n
cc=[]
for i in range(n):
s0=r[0][i]
s1=r[1][i]
if p[0][i]==i:
an+=(s0-1)*s0
if p[1][i]==i:
an+=(s1-1)*s1
an+=(r[1][find(i,1)]-1)*(r[0][find(i,0)]-1)
print(an)
``` | instruction | 0 | 90,192 | 13 | 180,384 |
Yes | output | 1 | 90,192 | 13 | 180,385 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
class UnionFind:
def __init__(self, N):
self.par = [i for i in range(N)]
self.rank = [1 for i in range(N)]
self.rank[0] = 0
def union(self, x, y):
if not self.is_same_set(x, y):
par_x = self.find_par(x)
par_y = self.find_par(y)
if self.rank[par_x] > self.rank[par_y]:
self.rank[par_x] += self.rank[par_y]
self.rank[par_y] = 0
self.par[par_y] = par_x
else:
self.rank[par_y] += self.rank[par_x]
self.rank[par_x] = 0
self.par[par_x] = par_y
def find_par(self, x):
if self.par[x] == x: return x
self.par[x] = self.find_par(self.par[x])
return self.par[x]
def is_same_set(self, x, y):
return self.find_par(x) == self.find_par(y)
def size(self, x):
return self.rank[self.find_par(x)]
# 2 unionfind, para 0 e para 1 formando 2 florestas
# lista de adj
# verificar todos os componentes existentes e adicionar na resposta n * (n-1)
n = int(input())
adj = [[] for i in range(n+1)]
uf0 = UnionFind(n+1)
uf1 = UnionFind(n+1)
for i in range(n-1):
x, y, c = map(int, input().split())
if c == 0:
uf0.union(x, y)
else:
uf1.union(x, y)
adj[x].append(y)
adj[y].append(x)
uf0.find_par(x)
uf1.find_par(y)
resp = 0
resp += sum(map(lambda i: uf0.rank[i] * (uf0.rank[i] - 1), set(uf0.par)))
resp += sum(map(lambda i: uf1.rank[i] * (uf1.rank[i] - 1), set(uf1.par)))
# pra cada componente do 0-uf verificar se existe esse vertice na 1-uf e ele for conectado com alguém, se sim, multiplicar (n-1)*(m-1) sendo n o componente da 0-uf e m o componente da 1-f e adicionar na resposta
#ja_visto = set()
for i in range(len(uf0.par)):
if uf0.rank[uf0.find_par(i)] > 1: #and not uf0.find_par(i) in ja_visto:
#ja_visto.add(uf0.find_par(i))
if uf1.rank[uf1.find_par(i)] > 1:
resp += (uf0.rank[uf0.find_par(i)] - 1) * (uf1.rank[uf1.find_par(i)] - 1)
print(resp)
``` | instruction | 0 | 90,193 | 13 | 180,386 |
Yes | output | 1 | 90,193 | 13 | 180,387 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
import sys
from collections import deque
from types import GeneratorType
input = lambda :sys.stdin.readline().rstrip()
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
n = int(input())
good_num = [0 for i in range(n + 1)]
mid_num = [0 for i in range(n + 1)]
tree = [[] for i in range(n + 1)]
ans = [0]
for i in range(n - 1):
a, b, c = map(int, input().split())
tree[a].append((b, c))
tree[b].append((a, c))
root = 1
@bootstrap
def dfs1(node, pa):
for ch, cl in tree[node]:
if ch != pa:
yield dfs1(ch, node)
if cl:
mid_num[node] += good_num[ch] + mid_num[ch] + 1
else:
good_num[node] += good_num[ch] + 1
yield 0
dfs1(root, root)
@bootstrap
def dfs2(node, pa, pgood, pmid):
total_sub_good = good_num[node]
total_sub_mid = mid_num[node]
temp = ans[0]
for ch, cl in tree[node]:
if ch!= pa:
ans[0] += good_num[ch] + mid_num[ch]
if cl:
ans[0] += pgood + pmid + 1
print('ch: {}, node: {}, pgood: {} , pmid: {}'.format(ch, node, pgood, pmid))
print('prev ans: {}, cur ans: {}'.format(temp, ans[0]))
input()
pass_down_mid = pgood + 1
pass_down_mid += total_sub_mid - mid_num[ch]
yield dfs2(ch, node, 0, pass_down_mid)
else:
ans[0] += pgood + 1
ans[0] += total_sub_good - good_num[ch] - 1
print('ch: {}, node: {}, pgood: {} , pmid: {}'.format(ch, node, pgood, pmid))
print('prev ans: {}, cur ans: {}'.format(temp, ans[0]))
input()
pass_down_mid = total_sub_mid - mid_num[ch]
pass_down_good = total_sub_good - good_num[ch]
pass_down_good += pgood + 1
yield dfs2(ch, node,pass_down_good, pass_down_mid)
yield 0
ans[0] = good_num[root] + mid_num[root]
dfs2(root, root, 0,0)
print(ans[0])
``` | instruction | 0 | 90,194 | 13 | 180,388 |
No | output | 1 | 90,194 | 13 | 180,389 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
def union0(a,b):
fa=find0(a)
fb=find0(b)
if size0[fa]>size0[fb]:
size0[fa]+=size0[fb]
dsu0[fb]=fa
else:
size0[fb]+=size0[fa]
dsu0[fa]=fb
def union1(a,b):
fa=find1(a)
fb=find1(b)
if size1[fa]>size1[fb]:
size1[fa]+=size1[fb]
dsu1[fb]=fa
else:
size1[fb]+=size1[fa]
dsu1[fa]=fb
def find0(x):
while dsu0[x]!=x:
dsu0[x]=dsu0[dsu0[x]]
x=dsu0[x]
return x
def find1(x):
while dsu1[x]!=x:
dsu1[x]=dsu1[dsu0[x]]
x=dsu1[x]
return x
n=int(input())
edges=[]
for i in range(n-1):
a,b,c=map(int,input().split())
edges.append([c,a-1,b-1])
size0=[1]*n
size1=[1]*n
dsu1=[i for i in range(n)]
dsu0=[i for i in range(n)]
#edges.sort()
ans=0
for i in range(n-1):
if edges[i][0]==0:
fa=find0(edges[i][1])
fb=find0(edges[i][2])
ans+=(size0[fa]*size0[fb])
union0(fa,fb)
else:
fa=find1(edges[i][1])
fb=find1(edges[i][2])
ans+=(size1[fa]*size1[fb])
union1(fa,fb)
ans+=ans
for i in range(n):
f0=find0(i)
f1=find1(i)
ans+=((size0[f0]-1)*(size1[f1]-1))
print(ans)
``` | instruction | 0 | 90,195 | 13 | 180,390 |
No | output | 1 | 90,195 | 13 | 180,391 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
from sys import stdin, stdout
n = int(stdin.readline())
g = [[] for i in range(n)]
for i in range(n-1):
a, b, c = map(int, stdin.readline().split())
a -= 1
b -= 1
g[a].append((b, c))
g[b].append((a, c))
dp = [[0, 0, 0] for i in range(n)]
# cnt(x0), cnt(y1), cnt(0y1)
def dfs(v, p):
for x in g[v]:
if x[0] != p:
dfs(x[0], v)
dp[v][x[1]] += 1 + dp[x[0]][x[1]]
dfs(0, -1)
def merge(v, p):
for x in g[v]:
if (x[0] != p):
if x[1] == 0:
dp[v][2] += (dp[x[0]][0] + 1) * (dp[v][1] - dp[x[0]][1])
dp[x[0]][2] += (dp[v][0] - dp[x[0]][0] - 1) * (dp[x[0]][1])
dp[x[0]][x[1]] = dp[v][x[1]]
merge(x[0], v)
merge(0, -1)
ans = 0
for i in dp:
ans += sum(i)
stdout.write('%d' % ans)
``` | instruction | 0 | 90,196 | 13 | 180,392 |
No | output | 1 | 90,196 | 13 | 180,393 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree (an undirected connected acyclic graph) consisting of n vertices and n - 1 edges. A number is written on each edge, each number is either 0 (let's call such edges 0-edges) or 1 (those are 1-edges).
Let's call an ordered pair of vertices (x, y) (x ≠ y) valid if, while traversing the simple path from x to y, we never go through a 0-edge after going through a 1-edge. Your task is to calculate the number of valid pairs in the tree.
Input
The first line contains one integer n (2 ≤ n ≤ 200000) — the number of vertices in the tree.
Then n - 1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers x_i, y_i and c_i (1 ≤ x_i, y_i ≤ n, 0 ≤ c_i ≤ 1, x_i ≠ y_i) — the vertices connected by this edge and the number written on it, respectively.
It is guaranteed that the given edges form a tree.
Output
Print one integer — the number of valid pairs of vertices.
Example
Input
7
2 1 1
3 2 0
4 2 1
5 2 0
6 7 1
7 2 1
Output
34
Note
The picture corresponding to the first example:
<image>
Submitted Solution:
```
m = 200000 + 42
ker1, ker2 = [x for x in range(m)], [x for x in range(m)]
cnt1, cnt2 = [1 for x in range(m)], [1 for x in range(m)]
def input_t():
return [int(x) for x in input().split()]
def kerik(x, p):
return x if p[x] == x else kerik(p[x], p)
def add(a, b, color):
if color:
x = kerik(a, ker1)
y = kerik(b, ker1)
if x != y:
ker1[x] = y
cnt1[y] += cnt1[x]
else:
x = kerik(a, ker2)
y = kerik(b, ker2)
if x != y:
ker2[x] = y
cnt2[y] += cnt2[x]
n = int(input())
for _ in range(n-1):
x, y, c = input_t()
add(x,y, c)
ans = 0
for i in range(n):
if ker1[i] == i:
ans += cnt1[i] * (cnt1[i] - 1)
if ker2[i] == i:
ans += cnt2[i] * (cnt2[i] - 1)
x, y = kerik(i, ker1), kerik(i, ker2)
ans += (cnt1[x] - 1) * (cnt2[y] - 1)
print(ans)
``` | instruction | 0 | 90,197 | 13 | 180,394 |
No | output | 1 | 90,197 | 13 | 180,395 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,198 | 13 | 180,396 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import heapq
n,m,k = map(int,input().split())
connectionList = []
for _ in range(n):
connectionList.append([])
edgeList = []
for _ in range(m):
x,y,w = map(int,input().split())
edgeList.append((x,y,w))
edgeList.sort(key = lambda x: x[2])
if k < m:
maxDist = edgeList[min(m,k) - 1][2]
else:
maxDist = sum(map(lambda x: x[2],edgeList))
colorList = {}
colorVertex = []
for i in range(n):
colorList[i] = [i]
colorVertex.append(i)
for i in range(min(m,k)):
x,y,w = edgeList[i]
connectionList[x-1].append((y-1,w))
connectionList[y-1].append((x-1,w))
if colorVertex[x-1] != colorVertex[y-1]:
if len(colorList[colorVertex[x-1]]) >= len(colorList[colorVertex[y-1]]):
prevColor = colorVertex[y-1]
for elem in colorList[colorVertex[y-1]]:
colorVertex[elem] = colorVertex[x-1]
colorList[colorVertex[x-1]].append(elem)
del colorList[prevColor]
else:
prevColor = colorVertex[x-1]
for elem in colorList[colorVertex[x-1]]:
colorVertex[elem] = colorVertex[y-1]
colorList[colorVertex[y-1]].append(elem)
del colorList[prevColor]
pathList = []
for key in colorList:
vertexList = colorList[key]
for mainVertex in vertexList:
vertexPQueue = []
isCovered = {}
distanceDic = {}
for elem in vertexList:
isCovered[elem] = False
distanceDic[elem] = maxDist
isCovered[mainVertex] = True
for elem in connectionList[mainVertex]:
heapq.heappush(vertexPQueue,(elem[1],elem[0]))
distanceDic[elem[0]] = elem[1]
while vertexPQueue:
distance, curVertex = heapq.heappop(vertexPQueue)
if isCovered[curVertex]:
continue
elif distance >= maxDist:
break
for elem in connectionList[curVertex]:
if distance + elem[1] < distanceDic[elem[0]]:
heapq.heappush(vertexPQueue,(distance + elem[1],elem[0]))
distanceDic[elem[0]] = distance + elem[1]
for key in distanceDic:
if distanceDic[key] <= maxDist and key > mainVertex:
pathList.append(distanceDic[key])
if len(pathList) > k:
pathList.sort()
pathList = pathList[0:k]
if pathList[-1] < maxDist:
maxDist = pathList[-1]
pathList.sort()
print(pathList[k-1])
``` | output | 1 | 90,198 | 13 | 180,397 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,199 | 13 | 180,398 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(m)]
EDGE.sort(key=lambda x:x[2])
EDGE=EDGE[:k]
COST_vertex=[[] for i in range(n+1)]
VERLIST=[]
for a,b,c in EDGE:
COST_vertex[a].append((b,c))
COST_vertex[b].append((a,c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST=sorted((set(VERLIST)))
import heapq
ANS=[-1<<50]*k
for start in VERLIST:
MINCOST=[1<<50]*(n+1)
checking=[(0,start)]
MINCOST[start]=0
j=0
while j<k:
if not(checking):
break
cost,checktown=heapq.heappop(checking)
if cost>=-ANS[0]:
break
if MINCOST[checktown]<cost:
continue
if cost!=0 and checktown>start:
heapq.heappop(ANS)
heapq.heappush(ANS,-cost)
j+=1
for to,co in COST_vertex[checktown]:
if MINCOST[to]>cost+co:
MINCOST[to]=cost+co
heapq.heappush(checking,(cost+co,to))
print(-ANS[0])
``` | output | 1 | 90,199 | 13 | 180,399 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,200 | 13 | 180,400 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(m)]
EDGE.sort(key=lambda x:x[2])
EDGE=EDGE[:k]
COST_vertex=[[] for i in range(n+1)]
for a,b,c in EDGE:
COST_vertex[a].append((b,c))
COST_vertex[b].append((a,c))
for i in range(min(m,k)):
x,y,c=EDGE[i]
EDGE[i]=(c,x,y)
USED_SET=set()
ANS=[-1<<50]*k
import heapq
while EDGE:
c,x,y = heapq.heappop(EDGE)
if (x,y) in USED_SET or c>=-ANS[0]:
continue
else:
heapq.heappop(ANS)
heapq.heappush(ANS,-c)
USED_SET.add((x,y))
USED_SET.add((y,x))
for to,cost in COST_vertex[x]:
if to!=y and not((y,to) in USED_SET) and c+cost<-ANS[0]:
heapq.heappush(EDGE,(c+cost,y,to))
#USED_SET.add((y,to))
#USED_SET.add((to,y))
for to,cost in COST_vertex[y]:
if to!=x and not((x,to) in USED_SET) and c+cost<-ANS[0]:
heapq.heappush(EDGE,(c+cost,x,to))
#USED_SET.add((x,to))
#USED_SET.add((to,x))
print(-ANS[0])
``` | output | 1 | 90,200 | 13 | 180,401 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,201 | 13 | 180,402 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
n,m,k = inpl()
edges = [inpl() for _ in range(m)]
edges.sort(key = lambda x:x[2])
se = set()
for a,b,_ in edges[:(min(m,k))]:
se.add(a-1)
se.add(b-1)
ls = list(se); ls.sort()
ln = len(ls)
d = {}
for i,x in enumerate(ls):
d[x] = i
g = [[] for _ in range(ln)]
def dijkstra(s):
d = [INF]*ln; d[s] = 0
seen = [False] * ln; seen[s] = True
edge = []
for x in g[s]:
heappush(edge,x)
while edge:
mi_cost, mi_to = heappop(edge)
if seen[mi_to]: continue
d[mi_to] = mi_cost
seen[mi_to] = True
for cost,to in g[mi_to]:
if seen[to]: continue
heappush(edge,(cost+mi_cost,to))
return d
for a,b,w in edges[:(min(m,k))]:
A,B = d[a-1], d[b-1]
g[A].append((w,B))
g[B].append((w,A))
dist = defaultdict(int)
for i in range(ln):
for x in dijkstra(i):
dist[x] += 1
cnt = 0
for key in sorted(dist.keys()):
if key == 0: continue
cnt += dist[key]//2
if cnt >= k:
err(key)
``` | output | 1 | 90,201 | 13 | 180,403 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,202 | 13 | 180,404 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
N, M, K = map(int, input().split())
X = []
for _ in range(M):
x, y, w = map(int, input().split())
X.append([min(x,y), max(x,y), w])
X = (sorted(X, key = lambda x: x[2])+[[0, 0, 10**20] for _ in range(K)])[:K]
D = {}
for x, y, w in X:
if x: D[x*10**6+y] = w
flg = 1
while flg:
flg = 0
for i in range(len(X)):
x1, y1, w1 = X[i]
for j in range(i+1, len(X)):
x2, y2, w2 = X[j]
if x1==x2: a, b = min(y1,y2), max(y1,y2)
elif y1==y2: a, b = min(x1,x2), max(x1,x2)
elif x1==y2: a, b = x2, y1
elif x2==y1: a, b = x1, y2
else: a, b = 0, 0
if a:
if (a*10**6+b in D and w1+w2 < D[a*10**6+b]) or (a*10**6+b not in D and w1+w2 < X[-1][2]):
if a*10**6+b in D:
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1+w2
else:
x, y, w = X.pop()
if x: D.pop(x*10**6+y)
X.append([a,b,w1+w2])
D[a*10**6+b] = w1+w2
X = sorted(X, key = lambda x: x[2])
flg = 1
break
if flg:
break
print(X[-1][2])
``` | output | 1 | 90,202 | 13 | 180,405 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,203 | 13 | 180,406 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
# i8nd5t's code modified by spider_0859
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
n,m,k = inpl()
edges = [inpl() for _ in range(m)]
edges.sort(key = lambda x:x[2])
edges = edges[:(min(m,k))]
se = set()
for a,b,_ in edges:
se.add(a-1)
se.add(b-1)
ls = list(se); ls.sort()
ln = len(ls)
d = {}
for i,x in enumerate(ls):
d[x] = i
g = [[] for _ in range(ln)]
def dijkstra(s):
d = [INF]*ln; d[s] = 0
seen = [False] * n; seen[s] = True
edge = []
for x in g[s]:
heappush(edge,x)
while edge:
mi_cost, mi_to = heappop(edge)
if seen[mi_to]: continue
d[mi_to] = mi_cost
seen[mi_to] = True
for cost,to in g[mi_to]:
if d[to]<=mi_cost+cost: continue
heappush(edge,(cost+mi_cost,to))
return d
for a,b,w in edges:
A,B = d[a-1], d[b-1]
g[A].append((w,B))
g[B].append((w,A))
dist = defaultdict(int)
for i in range(ln):
for x in dijkstra(i):
dist[x] += 1
cnt = 0
for key in sorted(dist.keys())[1:]:
cnt += dist[key]//2
if cnt >= k:
err(key)
``` | output | 1 | 90,203 | 13 | 180,407 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,204 | 13 | 180,408 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(m)]
EDGE.sort(key=lambda x:x[2])
EDGE=EDGE[:k]
COST_vertex=[[] for i in range(n+1)]
VERLIST=[]
for a,b,c in EDGE:
COST_vertex[a].append((b,c))
COST_vertex[b].append((a,c))
VERLIST.append(a)
VERLIST.append(b)
VERLIST=list(set(VERLIST))
import heapq
ANS=[-1<<50]*k
for start in VERLIST:
MINCOST=[1<<50]*(n+1)
checking=[(0,start)]
MINCOST[start]=0
j=0
while j<k:
if not(checking):
break
cost,checktown=heapq.heappop(checking)
if cost>=-ANS[0]:
break
if MINCOST[checktown]<cost:
continue
if cost!=0 and checktown>start:
heapq.heappop(ANS)
heapq.heappush(ANS,-cost)
j+=1
for to,co in COST_vertex[checktown]:
if MINCOST[to]>cost+co:
MINCOST[to]=cost+co
heapq.heappush(checking,(cost+co,to))
print(-ANS[0])
``` | output | 1 | 90,204 | 13 | 180,409 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9 | instruction | 0 | 90,205 | 13 | 180,410 |
Tags: brute force, constructive algorithms, shortest paths, sortings
Correct Solution:
```
# i8nd5t's code modified by spider_0859
import sys,math,itertools
from collections import Counter,deque,defaultdict
from bisect import bisect_left,bisect_right
from heapq import heappop,heappush,heapify
mod = 10**9+7
INF = float('inf')
def inp(): return int(sys.stdin.readline())
def inpl(): return list(map(int, sys.stdin.readline().split()))
def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split()))
def inps(): return sys.stdin.readline()
def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x])
def err(x): print(x); exit()
n,m,k = inpl()
edges = [inpl() for _ in range(m)]
edges.sort(key = lambda x:x[2])
edges = edges[:(min(m,k))]
se = set()
for a,b,_ in edges:
se.add(a-1)
se.add(b-1)
ls = list(se); ls.sort()
ln = len(ls)
d = {}
for i,x in enumerate(ls):
d[x] = i
g = [[] for _ in range(ln)]
def dijkstra(s):
d = [INF]*ln; d[s] = 0
edge = []
heappush(edge,(0,s))
while edge:
mi_cost, mi_to = heappop(edge)
if d[mi_to]<mi_cost: continue
for cost,to in g[mi_to]:
if d[to]<=mi_cost+cost: continue
d[to] = mi_cost+cost
heappush(edge,(cost+mi_cost,to))
return d
for a,b,w in edges:
A,B = d[a-1], d[b-1]
g[A].append((w,B))
g[B].append((w,A))
dist = defaultdict(int)
for i in range(ln):
for x in dijkstra(i):
dist[x] += 1
cnt = 0
for key in sorted(dist.keys())[1:]:
cnt += dist[key]//2
if cnt >= k:
err(key)
``` | output | 1 | 90,205 | 13 | 180,411 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
Submitted Solution:
```
import sys
input = sys.stdin.readline
N, M, K = map(int, input().split())
X = []
for _ in range(M):
x, y, w = map(int, input().split())
X.append([min(x,y), max(x,y), w])
X = sorted(X, key = lambda x: x[2])[:K]
X += [(0, 0, X[-1][2]) for _ in range(K - len(X))]
D = {}
for x, y, w in X:
D[x*10**6+y] = w
flg = 1
while flg:
flg = 0
for i in range(min(K, M)):
x1, y1, w1 = X[i]
for j in range(i+1, min(K, M)):
x2, y2, w2 = X[j]
if x1==x2: a, b = min(y1,y2), max(y1,y2)
elif y1==y2: a, b = min(x1,x2), max(x1,x2)
elif x1==y2: a, b = x2, y1
elif x2==y1: a, b = x1, y2
else: a, b = 0, 0
if a:
if (a*10**6+b in D and w1+w2 < D[a*10**6+b]) or (a*10**6+b not in D and w1+w2 < X[-1][2]):
if a*10**6+b in D:
D[a*10**6+b] = w1+w2
for k in range(len(X)):
if X[k][0] == a and X[k][1] == b:
X[k][2] = w1+w2
else:
x, y, w = X.pop()
X.append([a,b,w1+w2])
D[a*10**6+b] = w1+w2
X = sorted(X, key = lambda x: x[2])
flg = 1
print(X[-1][2])
``` | instruction | 0 | 90,206 | 13 | 180,412 |
No | output | 1 | 90,206 | 13 | 180,413 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
Submitted Solution:
```
def printMatrix(rows, columns, matrix):
for i in range(rows):
for j in range(columns):
print(str(matrix[i][j]) + " "*(9-len(str(matrix[i][j]))), end=' | ')
print()
def Dijkstra(N, S, matrix):
global EMPTY_PUT
BESKONECHNOST = EMPTY_PUT*N
valid = [True]*N
weight = [BESKONECHNOST]*N
weight[S] = 0
for i in range(N):
min_weight = BESKONECHNOST + 1
ID_min_weight = -1
for i in range(len(weight)):
if valid[i] and weight[i] < min_weight:
min_weight = weight[i]
ID_min_weight = i
for i in range(N):
if weight[ID_min_weight] + matrix[ID_min_weight][i] < weight[i]:
weight[i] = weight[ID_min_weight] + matrix[ID_min_weight][i]
valid[ID_min_weight] = False
return weight
import sys
input = sys.stdin.readline
EMPTY_PUT = 10**9 + 1
n, m, k= map(int, input().split())
matrix = []
for i in range(n):
matrix.append([EMPTY_PUT]*n)
for i in range(m):
v1, v2, ves = map(int, input().split())
v1 -=1
v2 -= 1
matrix[v1][v2] = min(matrix[v1][v2], ves)
matrix[v2][v1] = min(matrix[v1][v1], ves)
bb = []
for i in range(n):
b = Dijkstra(n, i, matrix)
bb += b[i+1:]
## print(b)
bb.sort()
print(bb[k-1])
##printMatrix(n, n, matrix)
``` | instruction | 0 | 90,207 | 13 | 180,414 |
No | output | 1 | 90,207 | 13 | 180,415 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
Submitted Solution:
```
import sys
input = sys.stdin.readline
n,m,k=map(int,input().split())
EDGE=[list(map(int,input().split())) for i in range(m)]
EDGE.sort(key=lambda x:x[2])
EDGE=EDGE[:k]
COST_vertex=[[] for i in range(n+1)]
for a,b,c in EDGE:
COST_vertex[a].append((b,c))
COST_vertex[b].append((a,c))
ANS=[0]
import heapq
for start in range(1,n+1):
MINCOST=[1<<50]*(n+1)
checking=[(0,start)]# start時点のcostは0.最初はこれをチェックする.
MINCOST[start]=0
for j in range(k):
if not(checking):
break
cost,checktown=heapq.heappop(checking)
if cost!=0:
ANS.append(cost)
if MINCOST[checktown]<cost:# 確定したものを再度チェックしなくて良い.
continue
for to,co in COST_vertex[checktown]:
if to<=start:
continue
if MINCOST[to]>cost+co:
MINCOST[to]=cost+co
# MINCOST候補に追加
heapq.heappush(checking,(cost+co,to))
print(ANS)
print(sorted(ANS)[k])
``` | instruction | 0 | 90,208 | 13 | 180,416 |
No | output | 1 | 90,208 | 13 | 180,417 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a connected undirected weighted graph consisting of n vertices and m edges.
You need to print the k-th smallest shortest path in this graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
More formally, if d is the matrix of shortest paths, where d_{i, j} is the length of the shortest path between vertices i and j (1 ≤ i < j ≤ n), then you need to print the k-th element in the sorted array consisting of all d_{i, j}, where 1 ≤ i < j ≤ n.
Input
The first line of the input contains three integers n, m and k (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min\Big((n(n-1))/(2), 2 ⋅ 10^5\Big), 1 ≤ k ≤ min\Big((n(n-1))/(2), 400\Big) — the number of vertices in the graph, the number of edges in the graph and the value of k, correspondingly.
Then m lines follow, each containing three integers x, y and w (1 ≤ x, y ≤ n, 1 ≤ w ≤ 10^9, x ≠ y) denoting an edge between vertices x and y of weight w.
It is guaranteed that the given graph is connected (there is a path between any pair of vertices), there are no self-loops (edges connecting the vertex with itself) and multiple edges (for each pair of vertices x and y, there is at most one edge between this pair of vertices in the graph).
Output
Print one integer — the length of the k-th smallest shortest path in the given graph (paths from the vertex to itself are not counted, paths from i to j and from j to i are counted as one).
Examples
Input
6 10 5
2 5 1
5 3 9
6 2 2
1 3 1
5 1 8
6 5 10
1 6 5
6 4 6
3 6 2
3 4 5
Output
3
Input
7 15 18
2 6 3
5 7 4
6 5 4
3 6 9
6 7 7
1 6 4
7 1 6
7 2 1
4 3 2
3 2 8
5 3 6
2 5 5
3 7 9
4 1 8
2 1 1
Output
9
Submitted Solution:
```
def printMatrix(rows, columns, matrix):
for i in range(rows):
for j in range(columns):
print(str(matrix[i][j]) + " "*(9-len(str(matrix[i][j]))), end=' | ')
print()
def Dijkstra(N, S, matrix):
global EMPTY_PUT
valid = [True]*N
weight = [EMPTY_PUT]*N
weight[S] = 0
for i in range(N):
min_weight = EMPTY_PUT + 1
ID_min_weight = -1
for i in range(len(weight)):
if valid[i] and weight[i] < min_weight:
min_weight = weight[i]
ID_min_weight = i
for i in range(N):
if weight[ID_min_weight] + matrix[ID_min_weight][i] < weight[i]:
weight[i] = weight[ID_min_weight] + matrix[ID_min_weight][i]
valid[ID_min_weight] = False
return weight
import sys
input = sys.stdin.readline
EMPTY_PUT = 10*9 + 1
n, m, k= map(int, input().split())
matrix = []
for i in range(n):
matrix.append([EMPTY_PUT]*n)
for i in range(m):
v1, v2, ves = map(int, input().split())
v1 -=1
v2 -= 1
if matrix[v1][v2] == EMPTY_PUT:
matrix[v1][v2] = ves
matrix[v2][v1] = ves
else:
matrix[v1][v2] = min(matrix[v1][v2], ves)
matrix[v2][v1] = min(matrix[v1][v1], ves)
bb = []
for i in range(n):
b = Dijkstra(n, i, matrix)
bb += b[i+1:]
## print(b)
bb.sort()
print(bb[k-1])
##printMatrix(n, n, matrix)
``` | instruction | 0 | 90,209 | 13 | 180,418 |
No | output | 1 | 90,209 | 13 | 180,419 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).
Wu is too tired after his training to solve this problem. Help him!
Input
The first line contains a single integer t (1 ≤ t ≤ 500 000) — the number of test cases in the given test set. Test case descriptions follow.
The first line of each case description contains two integers n and m (1~≤~n,~m~≤~500 000) — the number of vertices in either half of the graph, and the number of edges respectively.
The second line contains n integers c_i (1 ≤ c_i ≤ 10^{12}). The i-th number describes the integer in the vertex i of the right half of the graph.
Each of the following m lines contains a pair of integers u_i and v_i (1 ≤ u_i, v_i ≤ n), describing an edge between the vertex u_i of the left half and the vertex v_i of the right half. It is guaranteed that the graph does not contain multiple edges.
Test case descriptions are separated with empty lines. The total value of n across all test cases does not exceed 500 000, and the total value of m across all test cases does not exceed 500 000 as well.
Output
For each test case print a single integer — the required greatest common divisor.
Example
Input
3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
Output
2
1
12
Note
The greatest common divisor of a set of integers is the largest integer g such that all elements of the set are divisible by g.
In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S) for any non-empty subset is 2, thus the greatest common divisor of these values if also equal to 2.
In the second sample case the subset \{1\} in the left half is connected to vertices \{1, 2\} of the right half, with the sum of numbers equal to 2, and the subset \{1, 2\} in the left half is connected to vertices \{1, 2, 3\} of the right half, with the sum of numbers equal to 3. Thus, f(\{1\}) = 2, f(\{1, 2\}) = 3, which means that the greatest common divisor of all values of f(S) is 1.
Submitted Solution:
```
import io
import os
from math import gcd
from collections import deque, defaultdict, Counter
def solve(N, M, C, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
for u in range(N):
graph[u].sort()
g = 0
for u in range(N):
tot = 0
for v in graph[u]:
tot += C[v]
g = gcd(g, tot)
assign = [None for i in range(N)]
for u in range(N):
tot = 0
for v in graph[u]:
if assign[v] is None:
assign[v] = u
tot += C[v]
g = gcd(g, tot)
assign = [None for i in range(N)]
for u in range(N - 1, -1, -1):
tot = 0
for v in graph[u]:
if assign[v] is None:
assign[v] = u
tot += C[v]
g = gcd(g, tot)
return g
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
N, M = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(M)]
burn = input()
ans = solve(N, M, C, edges)
print(ans)
``` | instruction | 0 | 90,286 | 13 | 180,572 |
No | output | 1 | 90,286 | 13 | 180,573 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).
Wu is too tired after his training to solve this problem. Help him!
Input
The first line contains a single integer t (1 ≤ t ≤ 500 000) — the number of test cases in the given test set. Test case descriptions follow.
The first line of each case description contains two integers n and m (1~≤~n,~m~≤~500 000) — the number of vertices in either half of the graph, and the number of edges respectively.
The second line contains n integers c_i (1 ≤ c_i ≤ 10^{12}). The i-th number describes the integer in the vertex i of the right half of the graph.
Each of the following m lines contains a pair of integers u_i and v_i (1 ≤ u_i, v_i ≤ n), describing an edge between the vertex u_i of the left half and the vertex v_i of the right half. It is guaranteed that the graph does not contain multiple edges.
Test case descriptions are separated with empty lines. The total value of n across all test cases does not exceed 500 000, and the total value of m across all test cases does not exceed 500 000 as well.
Output
For each test case print a single integer — the required greatest common divisor.
Example
Input
3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
Output
2
1
12
Note
The greatest common divisor of a set of integers is the largest integer g such that all elements of the set are divisible by g.
In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S) for any non-empty subset is 2, thus the greatest common divisor of these values if also equal to 2.
In the second sample case the subset \{1\} in the left half is connected to vertices \{1, 2\} of the right half, with the sum of numbers equal to 2, and the subset \{1, 2\} in the left half is connected to vertices \{1, 2, 3\} of the right half, with the sum of numbers equal to 3. Thus, f(\{1\}) = 2, f(\{1, 2\}) = 3, which means that the greatest common divisor of all values of f(S) is 1.
Submitted Solution:
```
import io
import os
from math import gcd
from collections import deque, defaultdict, Counter
def solve(N, M, C, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
assign = [None for i in range(N)]
sums = [0 for i in range(N)]
sums2 = [0 for i in range(N)]
for u in range(N):
for v in graph[u]:
if assign[v] is None:
assign[v] = u
sums[u] += C[v]
sums2[u] += C[v]
g = 0
for v in sums:
g = gcd(g, v)
for v in sums2:
g = gcd(g, v)
return g
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
T = int(input())
for t in range(T):
N, M = [int(x) for x in input().split()]
C = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(M)]
burn = input()
ans = solve(N, M, C, edges)
print(ans)
``` | instruction | 0 | 90,287 | 13 | 180,574 |
No | output | 1 | 90,287 | 13 | 180,575 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).
Wu is too tired after his training to solve this problem. Help him!
Input
The first line contains a single integer t (1 ≤ t ≤ 500 000) — the number of test cases in the given test set. Test case descriptions follow.
The first line of each case description contains two integers n and m (1~≤~n,~m~≤~500 000) — the number of vertices in either half of the graph, and the number of edges respectively.
The second line contains n integers c_i (1 ≤ c_i ≤ 10^{12}). The i-th number describes the integer in the vertex i of the right half of the graph.
Each of the following m lines contains a pair of integers u_i and v_i (1 ≤ u_i, v_i ≤ n), describing an edge between the vertex u_i of the left half and the vertex v_i of the right half. It is guaranteed that the graph does not contain multiple edges.
Test case descriptions are separated with empty lines. The total value of n across all test cases does not exceed 500 000, and the total value of m across all test cases does not exceed 500 000 as well.
Output
For each test case print a single integer — the required greatest common divisor.
Example
Input
3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
Output
2
1
12
Note
The greatest common divisor of a set of integers is the largest integer g such that all elements of the set are divisible by g.
In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S) for any non-empty subset is 2, thus the greatest common divisor of these values if also equal to 2.
In the second sample case the subset \{1\} in the left half is connected to vertices \{1, 2\} of the right half, with the sum of numbers equal to 2, and the subset \{1, 2\} in the left half is connected to vertices \{1, 2, 3\} of the right half, with the sum of numbers equal to 3. Thus, f(\{1\}) = 2, f(\{1, 2\}) = 3, which means that the greatest common divisor of all values of f(S) is 1.
Submitted Solution:
```
import io
import os
from math import gcd
from collections import deque, defaultdict, Counter
def pack(L):
[a, b] = L
return (a << 20) + b
def unpack(i):
a = i >> 20
b = i & ((1 << 20) - 1)
return a, b
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
out = []
T = int(input())
for t in range(T):
N, M = list(map(int, input().split()))
C = list(map(int, input().split()))
edges = [pack(map(int, input().split())) for i in range(M)]
edges.sort()
assign = {}
sums = defaultdict(int)
# sums2 = defaultdict(int)
for uv in edges:
u, v = unpack(uv)
if v not in assign:
assign[v] = u
sums[u] += C[v - 1]
# sums2[u] += C[v - 1]
g = 0
for v in sums.values():
g = gcd(g, v)
# for v in sums2.values():
# g = gcd(g, v)
out.append(str(g))
burn = input()
print("\n".join(out))
``` | instruction | 0 | 90,288 | 13 | 180,576 |
No | output | 1 | 90,288 | 13 | 180,577 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Wu got hungry after an intense training session, and came to a nearby store to buy his favourite instant noodles. After Wu paid for his purchase, the cashier gave him an interesting task.
You are given a bipartite graph with positive integers in all vertices of the right half. For a subset S of vertices of the left half we define N(S) as the set of all vertices of the right half adjacent to at least one vertex in S, and f(S) as the sum of all numbers in vertices of N(S). Find the greatest common divisor of f(S) for all possible non-empty subsets S (assume that GCD of empty set is 0).
Wu is too tired after his training to solve this problem. Help him!
Input
The first line contains a single integer t (1 ≤ t ≤ 500 000) — the number of test cases in the given test set. Test case descriptions follow.
The first line of each case description contains two integers n and m (1~≤~n,~m~≤~500 000) — the number of vertices in either half of the graph, and the number of edges respectively.
The second line contains n integers c_i (1 ≤ c_i ≤ 10^{12}). The i-th number describes the integer in the vertex i of the right half of the graph.
Each of the following m lines contains a pair of integers u_i and v_i (1 ≤ u_i, v_i ≤ n), describing an edge between the vertex u_i of the left half and the vertex v_i of the right half. It is guaranteed that the graph does not contain multiple edges.
Test case descriptions are separated with empty lines. The total value of n across all test cases does not exceed 500 000, and the total value of m across all test cases does not exceed 500 000 as well.
Output
For each test case print a single integer — the required greatest common divisor.
Example
Input
3
2 4
1 1
1 1
1 2
2 1
2 2
3 4
1 1 1
1 1
1 2
2 2
2 3
4 7
36 31 96 29
1 2
1 3
1 4
2 2
2 4
3 1
4 3
Output
2
1
12
Note
The greatest common divisor of a set of integers is the largest integer g such that all elements of the set are divisible by g.
In the first sample case vertices of the left half and vertices of the right half are pairwise connected, and f(S) for any non-empty subset is 2, thus the greatest common divisor of these values if also equal to 2.
In the second sample case the subset \{1\} in the left half is connected to vertices \{1, 2\} of the right half, with the sum of numbers equal to 2, and the subset \{1, 2\} in the left half is connected to vertices \{1, 2, 3\} of the right half, with the sum of numbers equal to 3. Thus, f(\{1\}) = 2, f(\{1, 2\}) = 3, which means that the greatest common divisor of all values of f(S) is 1.
Submitted Solution:
```
import sys
input = sys.stdin.readline
from collections import Counter
from math import gcd
t=int(input())
for tests in range(t):
n,m=map(int,input().split())
C=list(map(int,input().split()))
X=[[] for i in range(n+1)]
for k in range(m):
x,y=map(int,input().split())
X[y].append(x)
#print(X)
A=Counter()
for i in range(n):
A[tuple(sorted(X[i+1]))]+=C[i]
#print(A)
ANS=0
for g in A.values():
ANS=gcd(ANS,g)
print(ANS)
_=input()
``` | instruction | 0 | 90,289 | 13 | 180,578 |
No | output | 1 | 90,289 | 13 | 180,579 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,532 | 13 | 181,064 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 有向木のDFS帰りがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][:-1]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# counts = {}
def add(sub_root, val):
stack = [sub_root]
while stack:
v = stack.pop()
vals = st[colors[v]]
st[colors[v]] = (vals[0] + val, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + val
for chi_v in di_tree[v]:
stack.append(chi_v)
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 1:
add(chi_v, 1)
vals = st[colors[v]]
st[colors[v]] = (vals[0] + 1, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + 1
ans[v] = st.all_fold()[1]
if keeps[v] == 1:
add(v, -1)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
ans = [0] * n
dsu_on_tree(tree, 0)
print(*ans)
``` | output | 1 | 90,532 | 13 | 181,065 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,533 | 13 | 181,066 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
# dsu on tree
# logistics: if the problem asked to compute some value of a subtree
# naive method would be for each node, compute the query value which would be O(n^2) because of doing dfs for each node
# we want to reuse some information of subtree so that we do not need to recompute it
# we can use concept of heavy-light decomposition which we divide the value into light nodes and heavy node
# complexity proof:
from collections import defaultdict as df
from types import GeneratorType
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
timer = 0
@bootstrap
def dfs(v, p):
global timer
tin[v] = timer
ver[timer] = v
timer += 1
for child in tree[v]:
if child != p:
yield dfs(child, v)
size[v] += size[child]
size[v] += 1
tout[v] = timer
timer += 1
yield 0
def operation(mx, v, x):
ans[cnt[color[v]]] -= color[v]
cnt[color[v]] += x
ans[cnt[color[v]]] += color[v]
mx = max(mx, cnt[color[v]])
return mx
@bootstrap
def dfs1(v, pa, keep):
mx = 0;mx_child = -1; big_child = -1
for child in tree[v]:
if child != pa and size[child] > mx_child:
mx_child = size[child]
big_child = child
for child in tree[v]:
if child != pa and child != big_child:
yield dfs1(child, v, 0)
if big_child != -1:
temp = yield dfs1(big_child, v, 1)
mx = max(temp, mx)
for child in tree[v]:
if child != pa and child != big_child:
for p in range(tin[child], tout[child]):
# add operation
#cnt[dist[ver[p]]] += 1
mx = operation(mx, ver[p], 1)
#add itself
mx = operation(mx,v,1)
#print(v,mx)
res[v - 1] = ans[mx]
#put answer above
if not keep:
for p in range(tin[v], tout[v]):
# cancel operation
#cnt[dist[ver[p]]] -= 1
mx = operation(mx, ver[p], -1)
yield mx
if __name__ == '__main__':
n = int(input().strip())
#arr = list(map(int, input().split()))
color = [0] + list(map(int, input().split()))
tree = df(list)
for i in range(1,n):
u,v = map(int, input().split())
tree[u].append(v)
tree[v].append(u)
#tree[arr[i - 1]].append(i + 1)
#maxn = 100000
cnt = [0 for i in range(n + 1)]
size = [0 for i in range(n + 1)]
ver = [0 for i in range((n + 1) << 1)]
tin = [0 for i in range(n + 1)]
tout = [0 for i in range(n + 1)]
ans = [0 for i in range(n + 1)]
res = [0 for i in range(n)]
#dist = [0 for i in range(n + 1)]
# query = int(input().strip())
# queries = df(list)
# res = df(int)
# for i in range(query):
# u, d = map(int, input().split())
# queries[u].append((d,i))
dfs(1, 1)
dfs1(1,1,1)
#res[0] = ans
print(' '.join(str(i) for i in res))
``` | output | 1 | 90,533 | 13 | 181,067 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,534 | 13 | 181,068 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 有向木のDFS行きがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][:-1]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# 加算もしくは減算の実行
# counts = {}
def add(sub_root, val):
stack = [sub_root]
while stack:
v = stack.pop()
vals = st[colors[v]]
st[colors[v]] = (vals[0] + val, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + val
for chi_v in di_tree[v]:
stack.append(chi_v)
# 有向木のDFS帰りがけ順で処理
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 1:
add(chi_v, 1)
# ここでクエリを実行する
vals = st[colors[v]]
st[colors[v]] = (vals[0] + 1, vals[1])
# counts[colors[v]] = counts.get(colors[v], 0) + 1
ans[v] = st.all_fold()[1]
if keeps[v] == 1:
add(v, -1)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
ans = [0] * n
dsu_on_tree(tree, 0)
print(*ans)
``` | output | 1 | 90,534 | 13 | 181,069 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,535 | 13 | 181,070 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
input = sys.stdin.buffer.readline
class SegmentTree:
def __init__(self, n, op, e):
self.n = n
self.op = op
self.e = e
self.size = 2 ** ((n - 1).bit_length())
self.node = [self.e] * (2 * self.size)
def __getitem__(self, i):
return self.node[i + self.size]
def __setitem__(self, i, val):
i += self.size
self.node[i] = val
while i > 1:
i >>= 1
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def build(self, array):
for i, val in enumerate(array, self.size):
self.node[i] = val
for i in range(self.size - 1, 0, -1):
self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])
def all_fold(self):
return self.node[1]
def fold(self, l, r):
l, r = l + self.size, r + self.size
vl, vr = self.e, self.e
while l < r:
if l & 1:
vl = self.op(vl, self.node[l])
l += 1
if r & 1:
r -= 1
vr = self.op(self.node[r], vr)
l, r = l >> 1, r >> 1
return self.op(vl, vr)
def topological_sorted(tree, root=None):
n = len(tree)
par = [-1] * n
tp_order = []
for v in range(n):
if par[v] != -1 or (root is not None and v != root):
continue
stack = [v]
while stack:
v = stack.pop()
tp_order.append(v)
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
par[nxt_v] = v
stack.append(nxt_v)
return tp_order, par
def dsu_on_tree(tree, root, add, sub, query):
n = len(tree)
tp_order, par = topological_sorted(tree, root)
# 1.有向木の構築
di_tree = [[] for i in range(n)]
for v in range(n):
for nxt_v in tree[v]:
if nxt_v == par[v]:
continue
di_tree[v].append(nxt_v)
# 2.部分木サイズの計算
sub_size = [1] * n
for v in tp_order[::-1]:
for nxt_v in di_tree[v]:
sub_size[v] += sub_size[nxt_v]
# 3.有向木のDFS行きがけ順の構築
di_tree = [sorted(tr, key=lambda v: sub_size[v]) for tr in di_tree]
keeps = [0] * n
for v in range(n):
di_tree[v] = di_tree[v][:-1][::-1] + di_tree[v][-1:]
for chi_v in di_tree[v][-1:]:
keeps[chi_v] = 1
tp_order, _ = topological_sorted(di_tree, root)
# 部分木からの加算もしくは減算
def calc(sub_root, is_add):
stack = [sub_root]
while stack:
v = stack.pop()
add(v) if is_add else sub(v)
for chi_v in di_tree[v]:
stack.append(chi_v)
# 4.有向木のDFS帰りがけ順で頂点vの部分木クエリを処理
for v in tp_order[::-1]:
for chi_v in di_tree[v]:
if keeps[chi_v] == 0:
calc(chi_v, 1)
add(v)
# ここでクエリを実行する
query(v)
if keeps[v] == 0:
calc(v, 0)
n = int(input())
colors = list(map(int, input().split()))
edges = [list(map(int, input().split())) for i in range(n - 1)]
tree = [[] for i in range(n)]
for u, v in edges:
u -= 1
v -= 1
tree[u].append(v)
tree[v].append(u)
def op(x, y):
# x = (max, sum_val)
if x[0] == y[0]:
return x[0], x[1] + y[1]
elif x[0] > y[0]:
return x
elif x[0] < y[0]:
return y
e = (0, 0)
st = SegmentTree(10 ** 5 + 10, op, e)
st.build([(0, i) for i in range(10 ** 5 + 10)])
def add(v):
max_, sum_ = st[colors[v]]
st[colors[v]] = (max_ + 1, sum_)
def sub(v):
max_, sum_ = st[colors[v]]
st[colors[v]] = (max_ - 1, sum_)
ans = [0] * n
def query(v):
max_, sum_ = st.all_fold()
ans[v] = sum_
dsu_on_tree(tree, 0, add, sub, query)
print(*ans)
``` | output | 1 | 90,535 | 13 | 181,071 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,536 | 13 | 181,072 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
from collections import defaultdict
class SumDefaultdict(defaultdict):
def __init__(self, *args, **kwargs) -> None:
super().__init__(int, *args, **kwargs)
self.mx = max(self.values())
self.mx_sum = sum(c for c, v in self.items() if v == self.mx)
def sumadd(self, map):
for bb, val in map.items():
if val > 0:
self[bb] += val
if self[bb] > self.mx:
self.mx = self[bb]
self.mx_sum = bb
elif self[bb] == self.mx:
self.mx_sum += bb
def go():
n = int(input())
c = list(map(int, input().split()))
edges = [[] for _ in range(n)]
for _ in range(n - 1):
a, b = map(lambda x: int(x) - 1, input().split())
edges[a].append(b)
edges[b].append(a)
depth = [0] + [None] * (n - 1)
parent = [None] * n
que = [0]
index = 0
while index < len(que):
curr = que[index]
for b in edges[curr]:
if depth[b] is None:
depth[b] = depth[curr] + 1
parent[b] = curr
que.append(b)
index += 1
order = sorted(((depth[i], i) for i in range(n)), reverse=True)
cols = [SumDefaultdict({c[i]: 1}) for i in range(n)]
answer = [0] * n
for d, i in order:
children = sorted([cols[b] for b in edges[i] if depth[b] > d], key=len, reverse=True)
if children:
for j in range(1, len(children)):
children[0].sumadd(children[j])
children[0].sumadd({c[i]: 1})
cols[i] = children[0]
# max_val = max(cols[i].values())
answer[i] = cols[i].mx_sum
print(' '.join(map(str, answer)))
go()
``` | output | 1 | 90,536 | 13 | 181,073 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,537 | 13 | 181,074 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import sys
from collections import Counter
n = int(input())
color = list(map(int, input().split()))
adj = [[] for _ in range(n)]
for _ in range(n-1):
u, v = map(int, sys.stdin.readline().split())
u -= 1
v -= 1
adj[u].append(v)
adj[v].append(u)
count = [Counter() for _ in range(n)]
max_cnt = [0]*n
dp = [0]*n
stack = [0]
par = [-1]*n
order = []
while stack:
v = stack.pop()
order.append(v)
for d in adj[v]:
if d != par[v]:
stack.append(d)
par[d] = v
for v in reversed(order):
child = [i for i in adj[v] if i != par[v]]
child.sort(key=lambda v: -len(count[v]))
if child:
dp[v] = dp[child[0]]
max_cnt[v] = max_cnt[child[0]]
count[v] = count[child[0]]
for d in child[1:]:
for k, val in count[d].items():
count[v][k] += val
if count[v][k] > max_cnt[v]:
dp[v] = k
max_cnt[v] = count[v][k]
elif count[v][k] == max_cnt[v]:
dp[v] += k
count[v][color[v]] += 1
if count[v][color[v]] > max_cnt[v]:
dp[v] = color[v]
max_cnt[v] = count[v][color[v]]
elif count[v][color[v]] == max_cnt[v]:
dp[v] += color[v]
if par[v] != -1:
stack.append(par[v])
print(*dp)
``` | output | 1 | 90,537 | 13 | 181,075 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,538 | 13 | 181,076 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
def main():
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
color = list(map(int, input().split()))
color.insert(0, 0)
adj = [[] for _ in range(N+1)]
for _ in range(N-1):
a, b = map(int, input().split())
adj[a].append(b)
adj[b].append(a)
que = deque()
que.append(1)
seen = [-1] * (N+1)
seen[1] = 0
par = [0] * (N+1)
child = [[] for _ in range(N+1)]
seq = []
while que:
v = que.popleft()
seq.append(v)
for u in adj[v]:
if seen[u] == -1:
seen[u] = seen[v] + 1
par[u] = v
child[v].append(u)
que.append(u)
seq.reverse()
cnt = [{color[i]: 1} for i in range(N+1)]
cnt_size = [1] * (N+1)
dom_num = [1] * (N+1)
ans = [color[i] for i in range(N+1)]
for v in seq:
big = cnt[v]
size_big = cnt_size[v]
for u in child[v]:
small = cnt[u]
size_small = cnt_size[u]
if size_big < size_small:
small, big = big, small
dom_num[v] = dom_num[u]
ans[v] = ans[u]
size_big += size_small
for c in small:
if c not in big:
big[c] = small[c]
else:
big[c] += small[c]
cnt_size[v] += small[c]
if big[c] > dom_num[v]:
dom_num[v] = big[c]
ans[v] = c
elif big[c] == dom_num[v]:
ans[v] += c
cnt_size[v] = size_big
cnt[v] = big
print(*ans[1:])
#print(child)
#print(cnt)
#print(cnt_size)
if __name__ == '__main__':
main()
``` | output | 1 | 90,538 | 13 | 181,077 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3 | instruction | 0 | 90,539 | 13 | 181,078 |
Tags: data structures, dfs and similar, dsu, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
_str = str
BUFSIZE = 8192
def str(x=b''):
return x if type(x) is bytes else _str(x).encode()
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 inp():
return sys.stdin.readline().rstrip()
def mpint():
return map(int, inp().split(' '))
def itg():
return int(inp())
# ############################## import
# from ACgenerator.Y_Testing import get_code
def tree_bfs(tree, flat=True, start=0) -> list:
stack = [start]
result = []
while stack:
new_stack = []
if flat:
result.extend(stack)
else:
result.append(stack)
for node in stack:
new_stack.extend(tree[node])
stack = new_stack
return result
def to_tree(graph, root=0):
"""
graph: [{child, ...}, ...] (undirected)
:return directed graph that parent -> children
"""
stack = [[root]]
while stack:
if not stack[-1]:
del stack[-1]
continue
parent = stack[-1].pop()
for child in graph[parent]:
graph[child].discard(parent)
stack.append(list(graph[parent]))
def tree_postorder(tree, flat=True, root=0):
""" children -> parent """
return tree_bfs(tree, flat, root)[::-1]
# ############################## main
from collections import defaultdict
class Counter:
def __init__(self, c):
self.ans = c
self.c_t = defaultdict(lambda: 0)
self.mx = self.c_t[c] = 1
self.t_c = defaultdict(set)
self.t_c[1] = {c}
def merge(self, other):
for c, t in other.c_t.items():
self.add(c, t)
def add(self, c, t):
old_t = self.c_t[c]
self.c_t[c] = new_t = old_t + t
self.t_c[old_t].discard(c)
self.t_c[new_t].add(c)
if new_t == self.mx:
self.ans += c
elif new_t > self.mx:
self.mx = new_t
self.ans = c
def __len__(self):
return len(self.c_t)
def __repr__(self):
return _str(self.ans)
def solve():
n = itg()
ans = list(map(Counter, mpint()))
tree = [set() for _ in range(n)]
for _ in range(n - 1):
a, b = mpint()
a -= 1
b -= 1
tree[a].add(b)
tree[b].add(a)
to_tree(tree)
for parent in tree_postorder(tree):
for child in tree[parent]:
child_ans = ans[child].ans
if len(ans[parent]) < len(ans[child]):
ans[parent], ans[child] = ans[child], ans[parent]
ans[parent].merge(ans[child])
ans[child] = child_ans
return ans
def main():
# solve()
print(*solve())
# for _ in range(itg()):
# print(solve())
# print("YES" if solve() else "NO")
# print("yes" if solve() else "no")
DEBUG = 0
URL = 'https://codeforces.com/contest/600/problem/E'
if __name__ == '__main__':
if DEBUG == 1:
import requests # ImportError: cannot import name 'md5' from 'sys' (unknown location)
from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
runner = TestCaseRunner(main, URL)
inp = runner.input_stream
print = runner.output_stream
runner.checking()
elif DEBUG == 2:
main()
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
main()
# Please check!
``` | output | 1 | 90,539 | 13 | 181,079 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
import collections
import random
input = sys.stdin.readline
d = collections.defaultdict(list)
n = int(input())
col = [int(i) for i in input().split() ]
for _ in range(n-1):
a, b = map(int, input().split() )
d[a-1].append(b-1)
d[b-1].append(a-1)
def dfs(parent, node, que, cnt, m):
makenew = False
for i in d[node]:
if i == parent: continue
if makenew:
q1, c1 = {}, {}
dfs(node, i, q1, c1, [0])
for key in c1: #key = color
if key in cnt:
que[cnt[key]] -= key
cnt[key] += c1[key]
else:
cnt[key] = c1[key]
if cnt[key] not in que:
que[cnt[key]] = 0
que[cnt[key]] += key
if m[0] < cnt[key]:
m[0] = cnt[key]
continue
dfs(node, i, que, cnt, m)
makenew = True
# leaves finish here:
if len(que) == 0:
que[1] = col[node]
cnt[col[node]] = 1
m[0] = 1
return
# nodes accumulating:
if col[node] in cnt:
que[cnt[col[node]]] -= col[node]
cnt[col[node]] += 1
if cnt[col[node]] not in que:
que[cnt[col[node]]] = 0
que[cnt[col[node]]] += col[node]
if m[0] < cnt[col[node]]:
m[0] = cnt[col[node]]
else:
cnt[col[node]] = 1
if 1 not in que:
que[1] = 0
que[1] += col[node]
col[node] = que[ m[0] ]
return
try:
dfs(-1, 0, {}, {}, [0])
except RuntimeError as e:
print(e)
print( " ".join(list(map(str, col ))))
``` | instruction | 0 | 90,540 | 13 | 181,080 |
No | output | 1 | 90,540 | 13 | 181,081 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
#600E
cin = lambda:map(int,input().split())
n=int(input())
color=list(cin())
D=dict()
for i in range(n-1):
a,b=cin()
if a not in D:
D[a]={b}
else:
D[a].add(b)
colorres=[0]*n
def myadd(x, y):
return list(map(lambda a, b: a + b, x, y))
def maxsum(l):
maxc=max(l)
res=0
for i in range(n+1):
if l[i]==maxc:
res+=i
return(res)
def myf(v):
if v not in D:
colorres[v-1]=color[v-1]
l=[0]*(n+1)
l[color[v-1]]=1
return l
else:
l=[0]*(n+1)
l[color[v-1]]+=1
for vc in D[v]:
l=myadd(l,myf(vc))
colorres[v-1]=maxsum(l)
return(l)
myf(1)
print(' '.join(map(str, colorres )))
``` | instruction | 0 | 90,541 | 13 | 181,082 |
No | output | 1 | 90,541 | 13 | 181,083 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline
n = int(input())
vertexes = list(map(int, input().split()))
tree_map = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a in tree_map:
tree_map[a].append(b)
else:
tree_map[a] = [b]
freq = [-1 for i in range(n)]
result = [-1 for i in range(n)]
def sum_dict(a, b):
for key in a:
if key in b:
b[key] += a[key]
else:
b[key] = a[key]
return b
def solve(node):
if result[node - 1] != -1:
return freq[node - 1]
if node in tree_map:
frequency = {vertexes[node - 1]: 1}
for next_node in tree_map[node]:
f = solve(next_node)
frequency = sum_dict(f, frequency)
n = max(frequency.values())
s = 0
for i in frequency:
if frequency[i] == n:
s += i
result[node - 1] = s
freq[node - 1] = frequency
return frequency
else:
freq[node - 1] = {vertexes[node - 1]: 1}
result[node - 1] = vertexes[node - 1]
return freq[node - 1]
solve(1)
for i, n in enumerate(result):
if n == -1:
result[i] = vertexes[i]
print(*result)
``` | instruction | 0 | 90,542 | 13 | 181,084 |
No | output | 1 | 90,542 | 13 | 181,085 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a rooted tree with root in vertex 1. Each vertex is coloured in some colour.
Let's call colour c dominating in the subtree of vertex v if there are no other colours that appear in the subtree of vertex v more times than colour c. So it's possible that two or more colours will be dominating in the subtree of some vertex.
The subtree of vertex v is the vertex v and all other vertices that contains vertex v in each path to the root.
For each vertex v find the sum of all dominating colours in the subtree of vertex v.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the number of vertices in the tree.
The second line contains n integers ci (1 ≤ ci ≤ n), ci — the colour of the i-th vertex.
Each of the next n - 1 lines contains two integers xj, yj (1 ≤ xj, yj ≤ n) — the edge of the tree. The first vertex is the root of the tree.
Output
Print n integers — the sums of dominating colours for each vertex.
Examples
Input
4
1 2 3 4
1 2
2 3
2 4
Output
10 9 3 4
Input
15
1 2 3 1 2 3 3 1 1 3 2 2 1 2 3
1 2
1 3
1 4
1 14
1 15
2 5
2 6
2 7
3 8
3 9
3 10
4 11
4 12
4 13
Output
6 5 4 3 2 3 3 1 1 3 2 2 1 2 3
Submitted Solution:
```
import sys
sys.setrecursionlimit(100000)
input = sys.stdin.readline
n = int(input())
vertexes = list(map(int, input().split()))
tree_map = {}
for i in range(n - 1):
a, b = map(int, input().split())
if a in tree_map:
tree_map[a].append(b)
else:
tree_map[a] = [b]
freq = [-1 for i in range(n)]
result = [-1 for i in range(n)]
def sum_dict(a, b):
for key in a:
if key in b:
b[key] += a[key]
else:
b[key] = a[key]
return b
def solve(node):
if result[node - 1] != -1:
return freq[node - 1]
if node in tree_map:
frequency = {vertexes[node - 1]: 1}
for next_node in tree_map[node]:
f = solve(next_node)
frequency = sum_dict(f, frequency)
n = max(frequency.values())
s = 0
for i in frequency:
if frequency[i] == n:
s += i
result[node - 1] = s
freq[node - 1] = frequency
return frequency
else:
freq[node - 1] = {vertexes[node - 1]: 1}
result[node - 1] = vertexes[node - 1]
return freq[node - 1]
solve(1)
if n == 4 or n == 15:
print(*result)
else:
print(tree_map[1])
``` | instruction | 0 | 90,543 | 13 | 181,086 |
No | output | 1 | 90,543 | 13 | 181,087 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.