message stringlengths 2 49.9k | message_type stringclasses 2 values | message_id int64 0 1 | conversation_id int64 446 108k | cluster float64 13 13 | __index_level_0__ int64 892 217k |
|---|---|---|---|---|---|
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image> | instruction | 0 | 43,129 | 13 | 86,258 |
Tags: constructive algorithms, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
import sys
input = sys.stdin.readline
from collections import deque
class Graph(object):
"""docstring for Graph"""
def __init__(self,n,d): # Number of nodes and d is True if directed
self.n = n
self.graph = [[] for i in range(n)]
self.parent = [-1 for i in range(n)]
self.directed = d
def addEdge(self,x,y):
self.graph[x].append(y)
if not self.directed:
self.graph[y].append(x)
def bfs(self, root): # NORMAL BFS
queue = [root]
queue = deque(queue)
vis = [0]*self.n
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in self.graph[element]:
if vis[i]==0:
queue.append(i)
self.parent[i] = element
vis[i] = 1
def dfs(self, root, ans): # Iterative DFS
stack=[root]
vis=[0]*self.n
stack2=[]
while len(stack)!=0: # INITIAL TRAVERSAL
element = stack.pop()
if vis[element]:
continue
vis[element] = 1
stack2.append(element)
for i in self.graph[element]:
if vis[i]==0:
self.parent[i] = element
stack.append(i)
while len(stack2)!=0: # BACKTRACING. Modify the loop according to the question
element = stack2.pop()
m = 0
for i in self.graph[element]:
if i!=self.parent[element]:
m += ans[i]
ans[element] = m
return ans
def shortestpath(self, source, dest): # Calculate Shortest Path between two nodes
self.bfs(source)
path = [dest]
while self.parent[path[-1]]!=-1:
path.append(parent[path[-1]])
return path[::-1]
def ifcycle(self):
queue = [0]
vis = [0]*n
queue = deque(queue)
while len(queue)!=0:
element = queue.popleft()
vis[element] = 1
for i in self.graph[element]:
if vis[i]==1 and i!=self.parent[element]:
s = i
e = element
path1 = [s]
path2 = [e]
while self.parent[s]!=-1:
s = self.parent[s]
path1.append(s)
while self.parent[e]!=-1:
e = self.parent[e]
path2.append(e)
for i in range(-1,max(-len(path1),-len(path2))-1,-1):
if path1[i]!=path2[i]:
return path1[0:i+1]+path2[i+1::-1]
if vis[i]==0:
queue.append(i)
self.parent[i] = element
vis[i] = 1
return -1
def reroot(self, root, ans):
stack = [root]
vis = [0]*n
while len(stack)!=0:
e = stack[-1]
if vis[e]:
stack.pop()
# Reverse_The_Change()
continue
vis[e] = 1
for i in graph[e]:
if not vis[e]:
stack.append(i)
if self.parent[e]==-1:
continue
# Change_The_Answers()
def dfss(self, root):
vis=[0]*self.n
color=[-1]*self.n
color[root]=0
# self.pdfs(root,vis,color)
# return
stack=[root]
while len(stack)!=0:
e=stack.pop()
if vis[e]:
continue
if color[e]==-1:
if color[self.parent[e]]:
color[e]=0
g1.append(e+1)
else:
color[e]=1
g2.append(e+1)
vis[e]=1
for i in self.graph[e]:
if not vis[i]:
stack.append(i)
self.parent[i]=e
return
n,m,k = map(int,input().split())
g = Graph(n,False)
for i in range(m):
a,b = map(int,input().split())
g.addEdge(a-1,b-1)
l = g.ifcycle()
# print (l)
if l!=-1 and len(l)<=k:
print (2)
print (len(l))
for i in range(len(l)):
l[i] += 1
print (*l)
exit()
g1,g2 = [1],[]
g.dfss(0)
if len(g1)>=(k-1)//2+1:
print (1)
print (*g1[0:(k-1)//2+1])
else:
print (1)
print (*g2[0:(k-1)//2+1])
``` | output | 1 | 43,129 | 13 | 86,259 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image> | instruction | 0 | 43,130 | 13 | 86,260 |
Tags: constructive algorithms, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
import io
import os
from collections import Counter, defaultdict, deque
import sys
sys.setrecursionlimit(10 ** 5 + 1)
from types import GeneratorType
# https://github.com/cheran-senthil/PyRival/blob/master/pyrival/misc/bootstrap.py
def bootstrap(f, stack=[]):
def wrappedfunc(*args, **kwargs):
if stack:
return f(*args, **kwargs)
else:
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
else:
stack.pop()
if not stack:
break
to = stack[-1].send(to)
return to
return wrappedfunc
def bfs(g, source):
q = deque()
dist = {}
q.append(source)
dist[source] = 0
while q:
node = q.popleft()
assert node in dist
d = dist[node]
for nbr in g[node]:
if nbr not in dist:
q.append(nbr)
dist[nbr] = d + 1
return dist
def findCycle(source, graph):
# Find a short cycle
@bootstrap
def f(path, depth):
# print(path, depth)
cycleDepth = -1
for nbr in graph[path[-1]]:
if len(path) >= 2 and nbr == path[-2]:
continue
if nbr in depth:
cycleDepth = max(cycleDepth, depth[nbr])
if cycleDepth != -1:
yield path[cycleDepth:]
return
for nbr in graph[path[-1]]:
if len(path) >= 2 and nbr == path[-2]:
continue
depth[nbr] = depth[path[-1]] + 1
path.append(nbr)
ret = yield f(path, depth)
if ret:
yield ret
return
path.pop()
del depth[nbr]
yield None
return
return f([source], {source: 0})
def solve(N, M, K, edges):
graph = [[] for i in range(N)]
for u, v in edges:
graph[u].append(v)
graph[v].append(u)
cycle = findCycle(0, graph)
independentLen = (K + 1) // 2
if cycle:
# print(cycle)
if len(cycle) <= K:
ans = cycle
return "2" + "\n" + str(len(ans)) + "\n" + " ".join(str(x + 1) for x in ans)
else:
ans = []
for i in range(independentLen):
ans.append(cycle[i * 2])
return "1" + "\n" + " ".join(str(x + 1) for x in ans)
else:
# No cycle means tree
dist = bfs(graph, 0)
evenCount = 0
oddCount = 0
for v, d in dist.items():
if d % 2 == 0:
evenCount += 1
else:
oddCount += 1
mod = 0
if evenCount >= independentLen:
mod = 0
elif oddCount >= independentLen:
mod = 1
else:
return -1
ans = []
for v, d in dist.items():
if d % 2 == mod:
ans.append(v)
if len(ans) == independentLen:
break
return "1" + "\n" + " ".join(str(x + 1) for x in ans)
if __name__ == "__main__":
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
N, M, K = [int(x) for x in input().split()]
edges = [[int(x) - 1 for x in input().split()] for i in range(M)]
ans = solve(N, M, K, edges)
print(ans)
``` | output | 1 | 43,130 | 13 | 86,261 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image> | instruction | 0 | 43,131 | 13 | 86,262 |
Tags: constructive algorithms, dfs and similar, graphs, greedy, implementation, trees
Correct Solution:
```
import math
import sys
from collections import deque
from typing import Deque, Dict, List, Optional, Set, Tuple
def data():
return sys.stdin.buffer.readline().strip()
def mdata():
return list(map(int, data().split()))
def outl(res):
sys.stdout.write(' '.join(map(str, res)) + '\n')
def out(var):
sys.stdout.write(str(var)+'\n')
def input_lst():
return mdata()
def print_out(res):
outl(res)
class GraphNode:
def __init__(self, id: int):
self.id = id
self.sublings: Deque[GraphNode] = deque()
class Graph:
def __init__(self, n: int):
self.n = n
self.nodes = [GraphNode(x) for x in range(n)]
def add_edge(self, u: int, v: int):
self.nodes[u].sublings.append(self.nodes[v])
self.nodes[v].sublings.append(self.nodes[u])
class GraphTraverse:
def __init__(self, graph: Graph):
self.graph = graph
self.watched_nodes: Set[GraphNode] = set()
self.nodes_color: Dict[GraphNode, bool] = {}
self.parent_nodes: Dict[GraphNode, GraphNode] = {}
self.circle_nodes: Optional[Tuple[GraphNode, GraphNode]] = None
def runBFS(self):
root_node = self.graph.nodes[0]
current_nodes = [root_node]
self.nodes_color[None] = True
self.watched_nodes.add(root_node)
self.parent_nodes[root_node] = None
next_nodes = set()
while len(current_nodes):
node = current_nodes.pop()
for child_node in node.sublings:
if child_node == self.parent_nodes[node]:
continue
if child_node in self.watched_nodes:
self.circle_nodes = (node, child_node)
break
self.parent_nodes[child_node] = node
next_nodes.add(child_node)
if self.circle_nodes is not None:
break
self.nodes_color[node] = not self.nodes_color[self.parent_nodes[node]]
self.watched_nodes.add(node)
if len(current_nodes) == 0:
current_nodes = list(next_nodes)
next_nodes = set()
del self.nodes_color[None]
def calc_circle(self):
if self.circle_nodes is None:
return
watched_nodes = set()
current_node = self.circle_nodes[0]
while current_node is not None:
watched_nodes.add(current_node)
current_node = self.parent_nodes[current_node]
current_node = self.circle_nodes[1]
union_node = None
while current_node is not None:
if current_node in watched_nodes:
union_node = current_node
break
watched_nodes.add(current_node)
current_node = self.parent_nodes[current_node]
circle_nodes_order = deque()
current_node = self.circle_nodes[0]
while current_node is not None:
circle_nodes_order.append(current_node)
if current_node == union_node:
break
current_node = self.parent_nodes[current_node]
circle_nodes_order2 = deque()
current_node = self.circle_nodes[1]
while current_node != union_node:
circle_nodes_order2.append(current_node)
current_node = self.parent_nodes[current_node]
circle_nodes_order2.reverse()
circle_nodes_order += circle_nodes_order2
return circle_nodes_order
def main():
(n, m, k) = input_lst()
graph = Graph(n)
for i in range(m):
(u, v) = input_lst()
u-=1
v-=1
graph.add_edge(u, v)
traverse = GraphTraverse(graph)
traverse.runBFS()
# print(traverse.nodes_color)
# print(traverse.circle_nodes)
if traverse.circle_nodes is not None:
circle_nodes_order = traverse.calc_circle()
if len(circle_nodes_order) <= k:
res = [x.id+1 for x in circle_nodes_order];
print_out([2])
print_out([len(res)])
print_out(res)
return
nodes_count = int(k // 2 + k % 2)
black_nodes = [k for k, v in traverse.nodes_color.items() if not v]
red_nodes = [k for k, v in traverse.nodes_color.items() if v]
if len(black_nodes) >= nodes_count:
res = [x.id+1 for x in black_nodes[:nodes_count]];
else:
res = [x.id+1 for x in red_nodes[:nodes_count]];
print_out([1])
print_out(res)
#print(n, m, a, b)
#sys.stdout.flush()
if __name__ == '__main__':
main()
``` | output | 1 | 43,131 | 13 | 86,263 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import math
import collections
from collections import defaultdict
import sys
import io, os
input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
def bfs(root):
stack=[root]
par={}
par[root]=0
while stack:
vertex=stack.pop()
dist[vertex]=dist[par[vertex]]+1
for neighbour in graph[vertex]:
if neighbour==par[vertex]:
continue
if dist[neighbour]==0:
par[neighbour]=vertex
stack.append(neighbour)
else:
return(True,restore(par,vertex,neighbour))
return(False,dist)
def restore(par,neigh,vertex):
res=[]
while neigh!=vertex:
res.append(neigh)
neigh=par[neigh]
res.append(neigh)
return(res)
n,m,k=map(int,input().split())
dist=[0]*(n+1)
graph=defaultdict(list)
for i in range(m):
u,v=map(int,input().split())
if u<=k and v<=k:
graph[u].append(v)
graph[v].append(u)
for i in range(1,k+1):
if dist[i]:
continue
b,arr=bfs(i)
if b==True:
break
if b==True:
print(2)
print(len(arr))
print(*arr)
else:
print(1)
odd,even=[],[]
for i in range(1,k+1):
if arr[i]&1:
odd.append(i)
else:
even.append(i)
if len(odd)>len(even):
odd,even=even,odd
for i in range((k+1)//2):
print(even[i],end=' ')
``` | instruction | 0 | 43,132 | 13 | 86,264 |
Yes | output | 1 | 43,132 | 13 | 86,265 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import math
import sys
input = sys.stdin.readline
from collections import *
def li():return [int(i) for i in input().rstrip('\n').split()]
def st():return input().rstrip('\n')
def val():return int(input().rstrip('\n'))
def li2():return [i for i in input().rstrip('\n')]
def li3():return [int(i) for i in input().rstrip('\n')]
def dfs():
global req
dep = [0]* (n + 1)
par = [0] * (n + 1)
st = [5]
st2 = []
while st:
u = st.pop()
if dep[u]:
continue
st2.append(u)
dep[u] = dep[par[u]] + 1
for v in g2[u]:
if not dep[v]:
par[v] = u
st.append(v)
elif dep[u] - dep[v] + 1>= req:
cyc = []
while u != par[v]:
cyc.append(u)
u = par[u]
return (None, cyc)
g = defaultdict(set)
g2 = defaultdict(set)
n,m = li()
for i in range(m):
a,b = li()
g[a].add(b)
g[b].add(a)
g2[a].add(b)
g2[b].add(a)
for i in g2:
g2[i] = set(sorted(list(g2[i])))
currset = set()
ma = math.ceil(n**0.5)
req = ma
for i in sorted(g,key = lambda x:len(g[x])):
if i in g:
currset.add(i)
for k in list(g[i]):
if k in g:g.pop(k)
g.pop(i)
if len(currset) == ma:break
if len(currset) >= ma:
print(1)
print(*list(currset)[:ma])
exit()
print(2)
_,cycles = dfs()
print(len(cycles))
print(*cycles)
``` | instruction | 0 | 43,133 | 13 | 86,266 |
Yes | output | 1 | 43,133 | 13 | 86,267 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
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()
# ------------------------------
def RL(): return map(int, sys.stdin.readline().split())
def RLL(): return list(map(int, sys.stdin.readline().split()))
def N(): return int(input())
def print_list(l):
print(' '.join(map(str,l)))
# import heapq as hq
# import bisect as bs
# from collections import deque as dq
# from collections import defaultdict as dc
# from math import ceil,floor,sqrt
# from collections import Counter
data = [map(int, line.split()) for line in sys.stdin.readlines()]
# data = [RLL()]
# for _ in range(data[0][1]):
# data.append(RL())
n,m,k = data[0]
dic = [[] for _ in range(n+1)]
for i in range(1,m+1):
u,v = data[i]
dic[u].append(v)
dic[v].append(u)
now = [1]
father = [-1]*(n+1)
p = [0]*(n+1)
iscycle = False
while now:
node = now.pop()
for child in dic[node]:
if child!=father[node]:
# print(child,'*')
if father[child]!=-1:
iscycle = True
odd = [child,node]
break
father[child] = node
p[child] = p[node]+1
now.append(child)
if iscycle:
break
# print(iscycle)
# print(p)
# print(father)
if iscycle:
a,b = odd[0],odd[1]
x,y = [],[]
node = a
while node>1:
x.append(node)
node = father[node]
x.append(1)
u = set(x)
node = b
while node>1:
y.append(node)
node = father[node]
if node in u:
t = p[a]-p[node]+1
x = x[:t]
break
# print(a,b,x,y)
x+=y[::-1]
if len(x)<=k:
print(2)
print(len(x))
print_list(x)
else:
print(1)
print_list(x[:k:2])
else:
print(1)
s0 = [i for i in range(1,n+1) if p[i]&1==0]
s1 = [i for i in range(1,n+1) if p[i]&1==1]
if len(s0)>len(s1):
print_list(s0[:(k+1)>>1])
else:
print_list(s1[:(k+1)>>1])
``` | instruction | 0 | 43,134 | 13 | 86,268 |
Yes | output | 1 | 43,134 | 13 | 86,269 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import sys
import math
from collections import defaultdict,deque
import heapq
def get_cycle(st,end,parent,now):
q=deque()
parent=[-1 for _ in range(n+1)]
q.append([st,0])
vis=defaultdict(int)
vis[st]=1
while q:
cur,d=q.popleft()
if d+1>=now:
return now+1
if cur==end:
#print(st,'st',end,'end',d+1,'len')
return d+1
for x in graph[cur]:
if vis[x]==0:
if [min(cur,x),max(cur,x)]!=[min(st,end),max(st,end)]:
vis[x]=1
parent[x]=cur
q.append([x,d+1])
n,m,k=map(int,sys.stdin.readline().split())
graph=defaultdict(list)
for i in range(m):
u,v=map(int,sys.stdin.readline().split())
graph[u].append(v)
graph[v].append(u)
vis=defaultdict(int)
dis=[-1 for _ in range(n+1)]
parent=[-1 for _ in range(n+1)]
q=deque()
cycle=1e10
st=-1
q.append([1,0])
dis[1]=0
parent[1]=-1
vis[1]=1
end=-1
while q:
#print(q,'q')
cur,d=q.popleft()
for x in graph[cur]:
if parent[cur]!=x and vis[x]==1:
#size = get_cycle(cur,x,graph,cycle)
cnt=0
curr,xx=cur,x
if dis[curr]>dis[xx]:
while dis[curr]>dis[xx]:
curr=parent[curr]
cnt+=1
if dis[xx]>dis[curr]:
while dis[xx]>dis[curr]:
xx=parent[xx]
cnt+=1
while xx!=curr:
xx=parent[xx]
curr=parent[curr]
cnt+=2
size=cnt+1
#print(size,'size',cur,'cur',x,'x',xx,'xx',curr,'curr')
#print(parent,'paren')
#size=d+1+dis[x]
#print(cur,'cur',x,'x',size,'size')
if size<cycle:
cycle=size
st=x
end=cur
if vis[x]==0:
q.append([x,d+1])
vis[x]=1
parent[x]=cur
dis[x]=d+1
#print(cycle,st,'st',end,'end')
#print(parent,'parent')
#print(dis,'dis')
if cycle!=1e10:
nodes=[]
parent=[-1 for _ in range(n+1)]
q.append(st)
vis=defaultdict(int)
vis[st]=1
while q:
cur=q.popleft()
if cur==end:
break
for x in graph[cur]:
if vis[x]==0:
if [min(cur,x),max(cur,x)]!=[min(st,end),max(st,end)]:
vis[x]=1
parent[x]=cur
q.append(x)
cur=end
nodes.append(end)
while cur!=st:
x=parent[cur]
#print(x,'x',cur,'cur')
nodes.append(x)
cur=x
#print(nodes,'nodes')
if cycle<=k:
print(2)
print(cycle)
print(*nodes)
else:
print(1)
ans=[]
cnt=math.ceil(k/2)
for i in range(0,cycle,2):
if i>=len(nodes):
print('Error',cycle,i,len(nodes))
print(nodes)
if cnt>0:
ans.append(nodes[i])
cnt-=1
else:
break
print(*ans)
else:
cnt=math.ceil(k/2)
q=deque()
q.append([1,True])
vis=defaultdict(int)
ans=[]
while q:
cur,add=q.pop()
for x in graph[cur]:
if vis[x]==0:
vis[x]=1
if add and cnt>0:
ans.append(x)
cnt-=1
q.append([x,not add])
if cnt==0:
print(1)
print(*ans)
else:
cnt=math.ceil(k/2)
q=deque()
q.append([graph[1][0],True])
vis=defaultdict(int)
ans=[]
while q:
cur,add=q.pop()
for x in graph[cur]:
if vis[x]==0:
vis[x]=1
if add and cnt>0:
ans.append(x)
cnt-=1
q.append([x,not add])
print(1)
print(*ans)
``` | instruction | 0 | 43,135 | 13 | 86,270 |
Yes | output | 1 | 43,135 | 13 | 86,271 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import sys
from collections import deque
input = sys.stdin.buffer.readline
n, m, k = map(int, input().split())
e = [[] for _ in range(n+1)]
for _ in range(m):
a, b = map(int, input().split())
e[a].append(b)
e[b].append(a)
def print_cycle(u, v, par):
up, vp = [], []
while u != 1: up.append(u); u = par[u]
while v != 1: vp.append(v); v = par[v]
cy = up + [1] + list(reversed(vp))
print(2)
print(len(cy))
print(*cy)
exit()
q = deque([1])
par = [0]*(n+1); par[1] = 1
dep = [0]*(n+1); dep[1] = 1
col0, col1 = [], []
while q:
u = q.popleft()
if dep[u] % 2: col0.append(u)
else: col1.append(u)
if len(col0)+len(col1) == k: break
for v in e[u]:
if v == par[u]: continue
if par[v] > 0:
if dep[u]+dep[v]-1 <= k:
print_cycle(u, v, par)
else:
par[v] = u
dep[v] = dep[u]+1
q.append(v)
res = col0 if len(col0) >= len(col1) else col1
res = [res[i] for i in range((k+1)//2)]
print(1)
print(*res)
``` | instruction | 0 | 43,136 | 13 | 86,272 |
No | output | 1 | 43,136 | 13 | 86,273 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import sys
def rs(): return sys.stdin.readline().rstrip()
def ri(): return int(sys.stdin.readline())
def ria(): return list(map(int, sys.stdin.readline().split()))
def ws(s): sys.stdout.write(s + '\n')
def wi(n): sys.stdout.write(str(n) + '\n')
def wia(a): sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
from collections import deque
def k_independent_set(n, k):
color = [-1] * n
q = deque()
q.append((0, 0))
color[0] = 0
while q:
v, c = q.popleft()
for w in g[v]:
if color[w] == -1:
color[w] = 1 - c
q.append((w, 1 - c))
c0 = [i + 1 for i in range(n) if color[i] == 0]
c1 = [i + 1 for i in range(n) if color[i] == 1]
if len(c0) >= (k+1)//2:
return 1, c0[:(k+1)//2]
else:
return 1, c1[:(k+1)//2]
def find_cycle(n):
def dfs(v):
stack = [v]
while stack:
if len(cycle) > 0:
return
v = stack[-1]
for w in g[v]:
if visited[w] and prev[v] != w:
x = v
cycle.append(w)
while x != w:
cycle.append(x)
x = prev[x]
return
if not visited[v]:
visited[v] = True
for w in g[v]:
if not visited[w]:
prev[w] = v
stack.append(w)
else:
stack.pop()
cycle = []
prev = [-1] * n
visited = [False] * n
dfs(0)
return cycle
def k_cycle(n, k):
c = find_cycle(n)
if len(c) <= k:
return 2, [i+1 for i in c]
return 1, [ci+1 for i, ci in enumerate(c) if i % 2 == 0]
def solve(n, m, k):
is_tree = m == n-1 # граф связный по условию
if is_tree:
return k_independent_set(n, k)
else:
return k_cycle(n, k)
g = []
def main():
global g
n, m, k = ria()
g = [[] for _ in range(n)]
for _ in range(m):
v, w = ria()
g[v-1].append(w-1)
g[w-1].append(v-1)
t, res = solve(n, m, k)
wi(t)
if t == 2:
wi(len(res))
wia(res)
if __name__ == '__main__':
main()
``` | instruction | 0 | 43,137 | 13 | 86,274 |
No | output | 1 | 43,137 | 13 | 86,275 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
from sys import stdin,stdout,setrecursionlimit
import threading
threading.stack_size(2**26)
setrecursionlimit(10**9)
line1 =[int(x) for x in stdin.readline().split()]
vertexes = line1[0]
edges = line1[1]
k = line1[2]
ceiling = k//2 if k % 2 == 0 else (k + 1)/2
graph = [[] for _ in range (vertexes + 1)]
parents = [-1 for _ in range(vertexes + 1)]
visited = [0 for _ in range(vertexes + 1)]
depth = [0 for _ in range(vertexes + 1)]
sets = [[] for _ in range(2)]
while edges > 0 :
line1 = [int(x) for x in stdin.readline().split()]
edges -= 1
graph[line1[0]].append(line1[1])
graph[line1[1]].append(line1[0])
def DFS_Cycle_Visit(vertex) :
visited[vertex] = 1
if depth[vertex] < k :
sets[depth[vertex] % 2].append(vertex)
for ady in graph[vertex]:
if visited[ady] == 0 :
parents[ady] = vertex
depth[ady] = depth[vertex] + 1
DFS_Cycle_Visit(ady)
else:
current_length = depth[vertex] - depth[ady] + 1
if 3 <= current_length <= k:
stdout.write("2\n")
cycle = []
i = vertex
while i != ady:
cycle.append(i)
i = parents[i]
cycle.append(ady)
stdout.write("{}\n".format(len(cycle)))
for elem in range(len(cycle)-1,-1,-1): #reversed(cycle) is also right, elem instead of cycle[elem]
stdout.write("{} ".format(cycle[elem]))
exit(0)
def DFS_Cycle() :
for vertex in range(1,len(graph)):
if visited[vertex] == 0 :
DFS_Cycle_Visit(vertex + 1)
stdout.write("1\n")
bigger_set = sets[0] if len(sets[0]) >= len(sets[1]) else sets[1]
for elem in range(0,ceiling):
stdout.write("{} ".format(bigger_set[elem]))
threading.Thread(target = DFS_Cycle).start()
``` | instruction | 0 | 43,138 | 13 | 86,276 |
No | output | 1 | 43,138 | 13 | 86,277 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Given a connected undirected graph with n vertices and an integer k, you have to either:
* either find an independent set that has exactly ⌈k/2⌉ vertices.
* or find a simple cycle of length at most k.
An independent set is a set of vertices such that no two of them are connected by an edge. A simple cycle is a cycle that doesn't contain any vertex twice.
I have a proof that for any input you can always solve at least one of these problems, but it's left as an exercise for the reader.
Input
The first line contains three integers n, m, and k (3 ≤ k ≤ n ≤ 10^5, n-1 ≤ m ≤ 2 ⋅ 10^5) — the number of vertices and edges in the graph, and the parameter k from the statement.
Each of the next m lines contains two integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between vertices u and v. It's guaranteed that the graph is connected and doesn't contain any self-loops or multiple edges.
Output
If you choose to solve the first problem, then on the first line print 1, followed by a line containing ⌈k/2⌉ distinct integers not exceeding n, the vertices in the desired independent set.
If you, however, choose to solve the second problem, then on the first line print 2, followed by a line containing one integer, c, representing the length of the found cycle, followed by a line containing c distinct integers not exceeding n, the vertices in the desired cycle, in the order they appear in the cycle.
Examples
Input
4 4 3
1 2
2 3
3 4
4 1
Output
1
1 3
Input
4 5 3
1 2
2 3
3 4
4 1
2 4
Output
2
3
2 3 4
Input
4 6 3
1 2
2 3
3 4
4 1
1 3
2 4
Output
2
3
1 2 3
Input
5 4 5
1 2
1 3
2 4
2 5
Output
1
1 4 5
Note
In the first sample:
<image>
Notice that printing the independent set \{2,4\} is also OK, but printing the cycle 1-2-3-4 isn't, because its length must be at most 3.
In the second sample:
<image>
Notice that printing the independent set \{1,3\} or printing the cycle 2-1-4 is also OK.
In the third sample:
<image>
In the fourth sample:
<image>
Submitted Solution:
```
import copy
import math
def solve():
n, m = [int(x) for x in input().strip().split(' ')]
k = math.ceil(n ** 0.5)
#print('n:{} m:{} k:{}'.format(n, m, k))
graph = {}
for _ in range(m):
v, u = [int(x) - 1 for x in input().strip().split(' ')]
if v not in graph:
graph[v] = set()
graph[v].add(u)
if u not in graph:
graph[u] = set()
graph[u].add(v)
#print(graph)
ban_node = set()
lonely_node = set()
last_len = len(graph)
while True:
nodes = list(graph.keys())
for node in nodes:
#print('node', node)
if len(graph[node]) == 1:
other_node = graph[node].pop()
#print('A remove', node, other_node)
if node not in ban_node:
lonely_node.add(node)
ban_node.add(other_node)
if len(lonely_node) >= k:
break
#print('B remove', other_node, node)
graph[other_node].remove(node)
del graph[node]
#print(graph)
elif len(graph[node]) == 0:
if node not in ban_node:
lonely_node.add(node)
if len(lonely_node) >= k:
break
if last_len == len(graph):
break
last_len = len(graph)
if len(lonely_node) >= k:
print(1)
print(' '.join([str(node + 1) for node in lonely_node][:k]))
return
graph_copy = copy.deepcopy(graph)
step_index = [-1] * n
step = []
for node in graph:
step_index[node] = len(step)
step.append(node)
break
while len(step) > 0:
node = step[-1]
if len(graph[node]) == 0:
step_index[node] = -1
step.pop()
continue
other_node = graph[node].pop()
#if len(graph[node]) == 0:
# if node not in ban_node:
# lonely_node.add(node)
# ban_node.add(other_node)
# if len(step) >= 2:
# ban_node.add(step[-2])
# if len(lonely_node) >= k:
# break
graph[other_node].remove(node)
if step_index[other_node] >= 0:
if len(step) - step_index[other_node] >= k:
print(2)
print(' '.join([str(node + 1) for node in step[step_index[other_node]:]]))
return
else:
step_index[other_node] = len(step)
step.append(other_node)
#if len(lonely_node) >= k:
# print(1)
# print(' '.join([str(node + 1) for node in lonely_node]))
# return
graph = graph_copy
degree = 1
while len(lonely_node) < k:
degree += 1
last_len = len(graph)
while True:
nodes = list(graph.keys())
for node in nodes:
if len(graph[node]) <= degree:
if node not in ban_node:
lonely_node.add(node)
if len(lonely_node) >= k:
break
for other_node in graph[node]:
ban_node.add(other_node)
for other_node in graph[node]:
graph[other_node].remove(node)
del graph[node]
if len(lonely_node) >= k:
break
if last_len == len(graph):
break
last_len = len(graph)
print(1)
print(' '.join([str(node + 1) for node in lonely_node][:k]))
if __name__ == '__main__':
solve()
``` | instruction | 0 | 43,139 | 13 | 86,278 |
No | output | 1 | 43,139 | 13 | 86,279 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,396 | 13 | 86,792 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from collections import deque
class CodeforcesTask580CSolution:
def __init__(self):
self.result = ''
self.n_m = []
self.wrong = []
self.edges = []
def read_input(self):
self.n_m = [int(x) for x in input().split(" ")]
self.wrong = [int(x) for x in input().split(" ")]
for x in range(self.n_m[0] - 1):
self.edges.append([int(y) for y in input().split(" ")])
def process_task(self):
tree = [[] for x in range(self.n_m[0])]
visited = [False for x in range(self.n_m[0])]
for edge in self.edges:
tree[edge[0] - 1].append(edge[1])
tree[edge[1] - 1].append(edge[0])
to_visit = deque([(x, (self.wrong[0] + 1) * self.wrong[x - 1]) for x in tree[0]])
leaves = 0
visited[0] = True
while to_visit:
visiting = to_visit.popleft()
# print(visiting)
if not visited[visiting[0] - 1]:
visited[visiting[0] - 1] = True
if 1 == len(tree[visiting[0] - 1]) and visiting[1] <= self.n_m[1]:
leaves += 1
elif visiting[1] <= self.n_m[1]:
to_visit.extend([(x, (visiting[1] + 1) * self.wrong[x - 1]) for x in tree[visiting[0] - 1]])
self.result = str(leaves)
def get_result(self):
return self.result
if __name__ == "__main__":
Solution = CodeforcesTask580CSolution()
Solution.read_input()
Solution.process_task()
print(Solution.get_result())
``` | output | 1 | 43,396 | 13 | 86,793 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,397 | 13 | 86,794 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
from queue import Queue
MAX = 100005
a = [0]
cat = [0] * MAX
visited = [False] * MAX
head = [None] * MAX
#head = [None for _ in range(MAX)]
class Node:
def __init__(self, v=None, next=None):
self.v = v
self.next = next
def lianjie(x, y):
head[x] = Node(y, head[x])
def isLeave(x):
p = head[x]
while (p):
if (visited[p.v] == False):
return False
p = p.next
return True
def BFS():
ans = 0
q = Queue()
visited[1] = True
q.put(1)
if (a[1] != 0):
cat[1] = 1
while (q.empty() == False):
now = q.get()
p = head[now]
while (p):
if (visited[p.v] == False):
visited[p.v] = True
if (a[p.v] != 0):
cat[p.v] = cat[now] + 1
if (isLeave(p.v) == True and cat[p.v] <= m):
ans += 1
elif (cat[p.v] <= m):
q.put(p.v)
p = p.next
return ans
if __name__ == '__main__':
n, m = map(int, input().split())
a += list(map(int, input().split()))
for i in range(1, n):
x, y = map(int, input().split())
lianjie(x, y);
lianjie(y, x);
ans = BFS()
print(ans)
``` | output | 1 | 43,397 | 13 | 86,795 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,398 | 13 | 86,796 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
import sys
def input(): return sys.stdin.readline().strip()
n, m = map(int, input().split())
a = [int(i) for i in input().split()]
edge = [[] for i in range(n)]
for i in range(n-1):
x, y = map(int, input().split())
edge[x-1].append(y-1)
edge[y-1].append(x-1)
visited = [0 for i in range(n)]
cur = edge[0]
count = [[0, 0] for i in range(n)]
if a[0]:
count[0][0] += 1
count[0][1] = max(count[0])
for i in range(len(cur)):
count[cur[i]][0] += count[0][0]
count[cur[i]][1] = max(count[cur[i]])
# print(edge)
visited[0] = 1
total = 0
while len(cur) > 0:
pos = cur.pop()
visited[pos] = 1
if a[pos]:
count[pos][0] += 1
count[pos][1] = max(count[pos])
if count[pos][1] <= m:
for i in range(len(edge[pos])):
if not visited[edge[pos][i]]:
visited[edge[pos][i]] = 1
cur.append(edge[pos][i])
count[edge[pos][i]][0] += count[pos][0]
count[edge[pos][i]][1] += max(count[edge[pos][i]])
else:
for i in range(len(edge[pos])):
if not visited[edge[pos][i]]:
visited[edge[pos][i]] = 1
cur.append(edge[pos][i])
count[edge[pos][i]][1] = count[pos][1]
if len(edge[pos]) == 1 and count[pos][1] <= m:
total += 1
# print(leaves)
# print(count)
print(total)
``` | output | 1 | 43,398 | 13 | 86,797 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,399 | 13 | 86,798 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
def dfs(d,lst,n,m):
stack = [[0,0]]
mark = {i:False for i in range(n)}
mark[0]=True
res=0
while stack:
q = stack.pop()
s,a = q[0],q[1]
e=0
if lst[s]==1:
a+=1
else:
if a<=m:
a=0
for i,x in enumerate(d[s]):
if mark[x]==False:
e+=1
stack.append([x,a])
mark[x]=True
if e==0:
if a<=m:
res+=1
print(res)
def prog():
from sys import stdin
n,m = map(int,stdin.readline().split())
lst = {i:int(x) for i,x in enumerate(input().split())}
d = {}
for i in range(n-1):
x,y = map(int,stdin.readline().split())
x,y=x-1,y-1
if d.get(x)==None:
d[x]=[]
if d.get(y)==None:
d[y]=[]
d[x].append(y)
d[y].append(x)
dfs(d,lst,n,m)
prog()
``` | output | 1 | 43,399 | 13 | 86,799 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,400 | 13 | 86,800 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n,m=map(int,input().split())
cats=list(map(int,input().split()))
q=[[] for i in range(n)]
for i in range(n-1):
x,y=map(int,input().split())
q[x-1].append(y-1)
q[y-1].append(x-1)
#0 is start_index,0 is the number of cats initially.
query=[(0,0)]
l=0
ans=0
visited=[0 for i in range(n)]
while(l<len(query)):
current_index,nofcatsforthegivenvertex=query[l]
visited[current_index]=1
if nofcatsforthegivenvertex+cats[current_index]<=m:
isLeaf=True
for i in q[current_index]:
if visited[i]==0:
isLeaf=False
query.append((i,cats[current_index]*(cats[current_index]+nofcatsforthegivenvertex)))
if isLeaf:
ans+=1
l+=1
print(ans)
``` | output | 1 | 43,400 | 13 | 86,801 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,401 | 13 | 86,802 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
n, m = (map(int, input().split()))
a = [int(x) for x in input().split()]
a.insert(0, 0)
catNumbers = {}
tree = {}
restCount = 0
def handle(i, prev_i, streak):
global restCount, catNumbers, tree, front
newStreak = streak + 1 if a[i] else 0
catNumbers[i] = max(catNumbers[prev_i], newStreak)
leaf = True
for next_i in tree[i]:
if next_i not in catNumbers:
leaf = False
front.append((next_i, i, newStreak))
if leaf and (catNumbers[i] <= m):
restCount += 1
for i in range(n - 1):
x, y = (map(int, input().split()))
if x not in tree: tree[x] = []
tree[x].append(y)
if y not in tree: tree[y] = []
tree[y].append(x)
catNumbers[1] = a[1]
front = [(x, 1, a[1]) for x in tree[1]]
while len(front) > 0:
handle(*front.pop())
# print(catNumbers)
print(restCount)
``` | output | 1 | 43,401 | 13 | 86,803 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,402 | 13 | 86,804 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
global k
n,k=map(int, input().split())
global g
global v
g = [ [] for i in range(n)]
v = list(map(int, input().split()))
g[0].append(0)
for i in range (n-1):
a,b=map(int, input().split())
g[a-1].append(b-1)
g[b-1].append(a-1)
t=0
q=[[0,0,v[0]]]
while len(q):
z=q.pop()
a=z[0]
b=z[1]
c=z[2]
if len(g[a])==1:
t+=1
continue
for i in g[a]:
if i!=b and c+v[i]<=k:
if v[i]!=0:
q.append([i,a,c+v[i]])
else:
q.append([i,a,0])
print (t)
``` | output | 1 | 43,402 | 13 | 86,805 |
Provide tags and a correct Python 3 solution for this coding contest problem.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7. | instruction | 0 | 43,403 | 13 | 86,806 |
Tags: dfs and similar, graphs, trees
Correct Solution:
```
# recursive too deep might causing stack overflow
def go_child(node, path_cat, parent):
# check if too more cat
m_cat = 0
if cat[node] == 0:
m_cat = 0
else:
m_cat = path_cat + cat[node]
# too more cat then leaves are not achievable
if m_cat > m:
return 0
isLeaf = True
sums = 0
# traverse edges belongs to node
for j in e[node]:
# ignore parent edge
if j == parent:
continue
# node has child
isLeaf = False
# dfs from child of node
sums += go_child(j, m_cat, node)
# achievable leaf
if isLeaf:
return 1
# return achievable leaves count
return sums
# AC
def go_bfs():
bfs = [(cat[0], 0, 0)]
sums = 0
while bfs:
isLeaf = True
# pop(0) takes O(n) and order of visiting won't affect result
level_cat, v, p = bfs.pop()
for j in e[v]:
if j == p:
continue
isLeaf = False
if cat[j] == 0:
bfs.append((0, j, v))
elif level_cat + 1 <= m:
bfs.append((level_cat + 1, j, v))
if isLeaf:
sums += 1
return sums
if __name__ == '__main__':
n, m = map(int, input().split())
cat = list(map(int, input().split()))
e = [[] for i in range(n)]
for i in range(n - 1):
v1, v2 = map(int, input().split())
# store undirected edge
e[v1 - 1].append(v2 - 1)
e[v2 - 1].append(v1 - 1)
# dfs from root
# print(go_child(0, 0, -1))
print(go_bfs())
``` | output | 1 | 43,403 | 13 | 86,807 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
import math
import sys
import collections
import bisect
import string
import time
def get_ints():return map(int, sys.stdin.readline().strip().split())
def get_list():return list(map(int, sys.stdin.readline().strip().split()))
def get_string():return sys.stdin.readline().strip()
for tc in range(1):
n, m = get_ints()
cat = get_list()
g = []
for i in range(n):
g.append([])
for i in range(n - 1):
x, y = get_ints()
g[x - 1].append(y - 1)
g[y-1].append(x-1)
ans = 0
v = [False] * n
q = [(0, 0)]
l = 0
while l < len(q):
x, num = q[l]
v[x] = 1
if cat[x] + num <= m:
leaf = True
for y in g[x]:
if not v[y]:
leaf = False
q.append((y, cat[x] * (cat[x] + num)))
if leaf:
ans += 1
l += 1
print(ans)
``` | instruction | 0 | 43,404 | 13 | 86,808 |
Yes | output | 1 | 43,404 | 13 | 86,809 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
from collections import defaultdict
import sys
import threading
n, m = map(int, input().strip().split())
cats = list(map(int, input().strip().split()))
g = []
for _ in range(n):
g.append([])
edges = []
for i in range(n - 1):
idx_f, idx_t = map(int, input().strip().split())
g[idx_f - 1].append(idx_t - 1)
g[idx_t - 1].append(idx_f - 1)
visited = [False] * n
def dfs(g, start, visited):
c_sums = 0
def get_children(parent, node):
return [x for x in g[node] if x != parent]
q = []
q.append((-1, start, cats[start]))
while q:
parent, node, cat_sum = q.pop(0)
visited[node] = True
children = get_children(parent, node)
if not children:
c_sums += 1
else:
for new_node in children:
if not visited[new_node]:
if cats[node]:
n_sum = cat_sum + cats[new_node]
else:
n_sum = cats[new_node]
if n_sum <= m:
q.append((node, new_node, n_sum))
return c_sums
print(dfs(g, 0, visited))
``` | instruction | 0 | 43,405 | 13 | 86,810 |
Yes | output | 1 | 43,405 | 13 | 86,811 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
n,m=[int(x) for x in input().split()]
cat=[int(x) for x in input().split()]
t=[[] for x in range(n)]
v=[0 for x in range(n)]
for k in range(1,n):
s,e=[int(x) for x in input().split()]
t[s-1].append(e-1)
t[e-1].append(s-1)
ans=0
lq=[(0,0)]
l=0
while l<len(lq):
x,p=lq[l]
v[x]=1
if cat[x]+p<=m:
Isleaf=True
for y in t[x]:
if not v[y]:
Isleaf=False
lq.append((y,cat[x]*(cat[x]+p)))
if Isleaf:
ans+=1
l+=1
print(ans)
``` | instruction | 0 | 43,406 | 13 | 86,812 |
Yes | output | 1 | 43,406 | 13 | 86,813 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
from queue import Queue
# import
class point():
def __init__(seft,id,preCat):
seft.id = id
seft.preCat = preCat
n, m = map(int,input().split())
status = list(map(int,input().split()))
path = [-1]*(n+1)
graph = [[] for i in range(n+1)]
for i in range(n-1):
first, second = map(int,input().split())
# path[max(first, second)] = min(first, second)
graph[first].append(second)
graph[second].append(first)
visited = [False for i in range(n + 1)]
visited[1] = True
queuePoints = Queue()
total = 0
queuePoints.put(point(1,status[0]))
while not queuePoints.empty():
pointer = queuePoints.get()
for i in graph[pointer.id]:
if len(graph[i]) == 1 and visited[i] == False:
if status[i - 1] + pointer.preCat <= m:
total += 1
else:
if visited[i] == False:
if status[i - 1] == 0:
queuePoints.put(point(i, 0))
elif pointer.preCat < m:
queuePoints.put(point(i, pointer.preCat + 1))
visited[i] = True
print(total)
``` | instruction | 0 | 43,407 | 13 | 86,814 |
Yes | output | 1 | 43,407 | 13 | 86,815 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
n,x = [int(x) for x in input().split()]
dogs = [int(x) for x in input().split()]
edges = {}
for i in range(0,n-1):
s,t = [int(x) for x in input().split()]
if edges.get(s):
edges[s].append(t)
else:
edges[s] = [t]
#create a stack with each element as a tuple of size 2
# first element of tuple is the node number
# and second element is the presence of dog in the node
stack = [(1,dogs[0])]
total_roads = 0
while stack!=[]:
ele = stack.pop(-1)
if edges.get(ele[0]):
new_edges = edges[ele[0]]
new_edges=new_edges[::-1]
for e in new_edges:
# if number of dogs in the path is less
# than x then add the current node
# into the stack with number of dogs in the
# current path otherwise ignore the path. So
# do not add current node into the stack
if dogs[e-1]==1:
curr_dogs = ele[1] + dogs[e-1]
if curr_dogs<=x:
stack.append((e,curr_dogs))
else:
stack.append((e, 0))
else:
#when there is no edge for the current node
# it is a leaf node so increment total_roads
total_roads+=1
print(total_roads)
``` | instruction | 0 | 43,408 | 13 | 86,816 |
No | output | 1 | 43,408 | 13 | 86,817 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
r = lambda: map(int,input().split())
n,c = r()
cats = list(r())
pos = [0] * (n)
for x in range(n-1):
s,e = r()
s,e = s-1,e-1
pos[e] = s
pos[0] = -1
s = 0
not_restaurant = set(pos)
for i,x in enumerate(pos):
if i in not_restaurant: continue
score = 1
cat_count = cats[i]
if cat_count>c:
continue
while x!=-1:
if cats[x]:
cat_count+=1
else:
cat_count = 0
if cat_count>c:
score = 0
break
x = pos[x]
s+=score
print (s)
``` | instruction | 0 | 43,409 | 13 | 86,818 |
No | output | 1 | 43,409 | 13 | 86,819 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
import sys
input = sys.stdin.buffer.readline
from collections import deque
def prog():
n,m = map(int,input().split())
cats = list(map(int,input().split()))
adj_list = [[[],0] for i in range(n+1)]
for i in range(n-1):
a,b = map(int,input().split())
adj_list[a][0].append(b)
adj_list[b][0].append(a)
consecutive_cats = [0 for i in range(n+1)]
consecutive_at_node = [0 for i in range(n+1)]
s = deque([0,1])
visited = set([0])
while s:
curr = s[-1]
if curr not in visited:
if cats[curr-1] == 1:
consecutive_at_node[curr] = consecutive_at_node[s[-2]] + 1
consecutive_cats[curr] = max(consecutive_cats[s[-2]],consecutive_at_node[curr])
else:
consecutive_at_node[curr] = 0
consecutive_cats[curr] = consecutive_cats[s[-2]]
visited.add(curr)
had_neighbor = False
for i in range(adj_list[curr][1],len(adj_list[curr][0])):
neighbor = adj_list[curr][0][i]
if neighbor not in visited:
had_neighbor = True
s.append(neighbor)
adj_list[curr][1] = i+1
break
if not had_neighbor:
s.pop()
visitable_restaurants = 0
for node in range(1,n+1):
if len(adj_list[node][0]) == 1 and consecutive_cats[node] <= m:
visitable_restaurants += 1
print(visitable_restaurants)
prog()
``` | instruction | 0 | 43,410 | 13 | 86,820 |
No | output | 1 | 43,410 | 13 | 86,821 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1 (then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yi are the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
Output
A single integer — the number of distinct leaves of a tree the path to which from Kefa's home contains at most m consecutive vertices with cats.
Examples
Input
4 1
1 1 0 0
1 2
1 3
1 4
Output
2
Input
7 1
1 0 1 1 0 0 0
1 2
1 3
2 4
2 5
3 6
3 7
Output
2
Note
Let us remind you that a tree is a connected graph on n vertices and n - 1 edge. A rooted tree is a tree with a special vertex called root. In a rooted tree among any two vertices connected by an edge, one vertex is a parent (the one closer to the root), and the other one is a child. A vertex is called a leaf, if it has no children.
Note to the first sample test: <image> The vertices containing cats are marked red. The restaurants are at vertices 2, 3, 4. Kefa can't go only to the restaurant located at vertex 2.
Note to the second sample test: <image> The restaurants are located at vertices 4, 5, 6, 7. Kefa can't go to restaurants 6, 7.
Submitted Solution:
```
import time
vershkoti = input().split(" ")
it = 0
listi = 0
for ab in vershkoti:
vershkoti[it] = int(ab)
it += 1
neko = input().split(" ")
it = 0
alfa = 1
rebra = [[-1]]
while it < vershkoti[0]:
rebra.append([neko[it],-1])
it += 1
it = 0
kotoiter = 0
koti = []
puti = 0
def shestputei(spisok):
global rebra
global listi
global vershkoti
global koti
global kotoiter
global puti
mas = []
it = 1
while it <= vershkoti[0]:
if rebra[it][1] == -1:
puti += 1
it +=1
it = 0
while it < puti:
koti.append([rebra[1][0]])
it += 1
it = 0
for ab in spisok:
mas.append(ab)
while len(mas) != 0:
if rebra[mas[it]][1] != -1:
temp = 0
kotoiter_1 = kotoiter
while temp < len(rebra[mas[it]][1:]):
koti[kotoiter_1].append(rebra[mas[it]][0])
temp += 1
kotoiter_1 += 1
ab = mas[it]
mas.remove(mas[it])
mas = rebra[ab][1:]+mas
else:
koti[kotoiter].append(rebra[mas[it]][0])
kotoiter += 1
mas.remove(mas[it])
# for ab in mas:
# if rebra[ab][1] != -1:
# koti[kotoiter].append(rebra[ab][0])
# mas.remove(ab)
# mas = rebra[ab][1:]+mas
# else:
# koti[kotoiter].append(rebra[ab][0])
# kotoiter += 1
# mas.remove(ab)
t0 = time.time()
vershini = [[-1,-1]]
it = 1
while it < vershkoti[0]:
temp = input().split(" ")
vershini.append([int(temp[0]),int(temp[1])])
it += 1
it = 2
prioritet = [[-1,-1],[1,1]]
while it < vershkoti[0]+1:
prioritet.append([it,-1])
it += 1
it = 1
print(time.time()-t0,'1')
t0 = time.time()
pommas = [1]
while len(pommas) != 0:
while it < vershkoti[0]:
if vershini[it][0] == pommas[0]:
ab = vershini[it][1]
if prioritet[ab][1] == -1:
prioritet[ab][1] = prioritet[pommas[0]][1]+1
pommas.append(ab)
if vershini[it][1] == pommas[0]:
ab = vershini[it][0]
if prioritet[ab][1] == -1:
prioritet[ab][1] = prioritet[pommas[0]][1]+1
pommas.append(ab)
it += 1
it = 1
pommas.pop(0)
it = 0
print(time.time()-t0,'2')
for ab in vershini:
if ab[1] != -1:
if prioritet[ab[0]][1] > prioritet[ab[1]][1]:
x = vershini[it][0]
vershini[it][0] = vershini[it][1]
vershini[it][1] = x
it += 1
t0 = time.time()
it = 1
while it < vershkoti[0]:
temp = vershini[it]
if temp[0] == alfa:
if rebra[alfa][1] == -1:
rebra[alfa].remove(-1)
rebra[alfa].append(temp[1])
else:
alfa = temp[0]
if rebra[alfa][1] == -1:
rebra[alfa].remove(-1)
rebra[alfa].append(temp[1])
it += 1
print(time.time()-t0,'2')
t0 = time.time()
shestputei(rebra[1][1:])
print(time.time()-t0,'3')
t0 = time.time()
pamyat = 0
kolvo = puti
for ab in koti:
for itr in ab:
if itr == '1':
pamyat += 1
if pamyat > vershkoti[1]:
kolvo -= 1
else:
pamyat = 0
pamyat = 0
print(time.time()-t0,'4')
print(kolvo)
``` | instruction | 0 | 43,411 | 13 | 86,822 |
No | output | 1 | 43,411 | 13 | 86,823 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8 | instruction | 0 | 43,656 | 13 | 87,312 |
"Correct Solution:
```
import sys
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
readlines = sys.stdin.buffer.readlines
N = int(readline())
data = list(map(int,read().split()))
A = data[:N+N-2:2]
B = data[1:N+N-2:2]
INF = 10 ** 18 + 100
S = [INF] + data[-N:]
graph = [[] for _ in range(N+1)]
for a,b in zip(A,B):
graph[a].append(b)
graph[b].append(a)
root = S.index(min(S))
parent = [0] * (N+1)
order = []
stack = [root]
while stack:
x = stack.pop()
order.append(x)
for y in graph[x]:
if y == parent[x]:
continue
parent[y] = x
stack.append(y)
subtree_size = [1] * (N+1)
for v in reversed(order):
subtree_size[parent[v]] += subtree_size[v]
length = [0] * (N+1)
for v,p in zip(A,B):
if parent[p] == v:
v,p = p,v
s = subtree_size[v]
d = N - s - s
length[v] = 0 if d == 0 else(S[v] - S[p]) // d
# 重心間以外は決まった。いったん、重心間を 0 として計算
dist = [0] * (N+1)
for v in order[1:]:
p = parent[v]
dist[v] = dist[p] + length[v]
d_root = sum(dist)
x = (S[root] - d_root) * 2 // N
answer = []
for v,p in zip(A,B):
if parent[p] == v:
v,p = p,v
if length[v] == 0:
length[v] = x
answer.append(length[v])
print('\n'.join(map(str,answer)))
``` | output | 1 | 43,656 | 13 | 87,313 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8 | instruction | 0 | 43,657 | 13 | 87,314 |
"Correct Solution:
```
def main():
n = int(input())
ab = [sorted(list(map(int, input().split()))) for _ in [0]*(n-1)]
s = list(map(int, input().split()))
g = [[] for _ in [0]*n]
[g[a-1].append(b-1) for a, b in ab]
[g[b-1].append(a-1) for a, b in ab]
root = 0 # 根
d = [-1]*n # 根からの距離
d[root] = 0
q = [root]
cnt = 0
while q: # BFS
cnt += 1
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] == -1:
d[j] = cnt
qq.append(j)
q = qq
dd = [[j, i] for i, j in enumerate(d)]
dd.sort(key=lambda x: -x[0])
dd = [j for i, j in dd]
dp = [1]*n
for i in dd:
for j in g[i]:
if d[j] > d[i]:
dp[i] += dp[j]
ans = []
for a, b in ab:
a -= 1
b -= 1
if d[a] > d[b]:
a, b = b, a
ay = dp[b]-1
ax = n-2-ay
if ax-ay == 0:
ans.append(1j)
else:
ans.append(abs(s[a]-s[b])//abs(ax-ay))
ab_dict = {(ab[i][0]-1, ab[i][1]-1): ans[i] for i in range(n-1)}
if 1j in ans:
cnt = 0
for i in ans:
if i == 1j:
cnt += 1
if cnt > 1:
return
p = ans.index(1j)
q = [root]
temp_1 = 0
temp_2 = 0
while q:
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] > d[i]:
a, b = min(i, j), max(i, j)
temp = ab_dict[(a, b)]
if temp == 1j:
temp_2 = dp[j]
else:
temp_1 += dp[j]*temp
qq.append(j)
q = qq
ans[p] = (s[0]-temp_1)//temp_2
for i in ans:
print(i)
main()
``` | output | 1 | 43,657 | 13 | 87,315 |
Provide a correct Python 3 solution for this coding contest problem.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8 | instruction | 0 | 43,658 | 13 | 87,316 |
"Correct Solution:
```
import sys
sys.setrecursionlimit(10**8)
N=int(input())
G=[[] for i in range(N)]
E=[]
ans=[0]*(N-1)
for i in range(N-1):
a,b=map(int,input().split())
G[a-1].append((b-1,i))
G[b-1].append((a-1,i))
s=[int(i) for i in input().split()]
n=[0]*N
visited=[False]*N
def size(x):
res=1
visited[x]=True
for i,e in G[x]:
if visited[i]:
continue
res+=size(i)
E.append((e,x,i))
n[x]=res
return res
size(0)
#print(n)
flag=0
E.sort()
for i in range(N-1):
e,a,b=E[i]
if 2*n[b]==N:
flag=e+1
continue
ans[e]=abs((s[a]-s[b])//(2*n[b]-N))
#print(ans,flag)
#print(E)
if flag:
A=s[0]
for i in range(N-1):
A-=n[E[i][2]]*ans[i]
ans[flag-1]=A//n[E[flag-1][2]]
for i in range(N-1):
print(ans[i])
``` | output | 1 | 43,658 | 13 | 87,317 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8
Submitted Solution:
```
def main():
n = int(input())
ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
s = list(map(int, input().split()))
g = [[] for _ in [0]*n]
[g[a-1].append(b-1) for a, b in ab]
[g[b-1].append(a-1) for a, b in ab]
root = 0 # 根
d = [-1]*n # 根からの距離
d[root] = 0
q = [root]
cnt = 0
while q: # BFS
cnt += 1
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] == -1:
d[j] = cnt
qq.append(j)
q = qq
dd = [[j, i] for i, j in enumerate(d)]
dd.sort(key=lambda x: -x[0])
dd = [j for i, j in dd]
dp = [1]*n
for i in dd:
for j in g[i]:
if d[j] > d[i]:
dp[i] += dp[j]
ans = []
for a, b in ab:
a -= 1
b -= 1
if d[a] > d[b]:
a, b = b, a
ay = dp[b]-1
ax = n-2-ay
if ax-ay == 0:
ans.append(1j)
else:
ans.append(abs(s[a]-s[b])//abs(ax-ay))
ab_dict = {(ab[i][0]-1, ab[i][1]-1): ans[i] for i in range(n-1)}
if 1j in ans:
cnt = 0
for i in ans:
if i == 1j:
cnt += 1
if cnt > 1:
return
p = ans.index(1j)
q = [root]
temp_1 = 0
temp_2 = 0
while q:
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] > d[i]:
a, b = min(i, j), max(i, j)
temp = ab_dict[(a, b)]
if temp == 1j:
temp_2 = dp[j]
else:
temp_1 += dp[j]*temp
qq.append(j)
q = qq
ans[p] = (s[0]-temp_1)//temp_2
for i in ans:
print(i)
main()
``` | instruction | 0 | 43,659 | 13 | 87,318 |
No | output | 1 | 43,659 | 13 | 87,319 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8
Submitted Solution:
```
def main():
n = int(input())
ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
s = list(map(int, input().split()))
g = [[] for _ in [0]*n]
[g[a-1].append(b-1) for a, b in ab]
[g[b-1].append(a-1) for a, b in ab]
root = 0 # 根
d = [-1]*n # 根からの距離
d[root] = 0
q = [root]
cnt = 0
while q: # BFS
cnt += 1
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] == -1:
d[j] = cnt
qq.append(j)
q = qq
dd = [[j, i] for i, j in enumerate(d)]
dd.sort(key=lambda x: -x[0])
dd = [j for i, j in dd]
dp = [1]*n
for i in dd:
for j in g[i]:
if d[j] > d[i]:
dp[i] += dp[j]
ans = []
for a, b in ab:
a -= 1
b -= 1
if d[a] > d[b]:
a, b = b, a
ay = dp[b]-1
ax = n-2-ay
if ax-ay == 0:
ans.append(1j)
else:
ans.append(abs(s[a]-s[b])//abs(ax-ay))
ab_dict = {(ab[i][0]-1, ab[i][1]-1): ans[i] for i in range(n-1)}
if 1j in ans:
p = ans.index(1j)
q = [root]
temp = 0
while q:
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] > d[i]:
a, b = min(i, j), max(i, j)
temp += dp[j]*ab_dict[(a, b)]
qq.append(j)
q = qq
ans[p] = int((s[0]-temp.real)//temp.imag)
for i in ans:
print(i)
main()
``` | instruction | 0 | 43,660 | 13 | 87,320 |
No | output | 1 | 43,660 | 13 | 87,321 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
Snuke found a record of a tree with N vertices in ancient ruins. The findings are as follows:
* The vertices of the tree were numbered 1,2,...,N, and the edges were numbered 1,2,...,N-1.
* Edge i connected Vertex a_i and b_i.
* The length of each edge was an integer between 1 and 10^{18} (inclusive).
* The sum of the shortest distances from Vertex i to Vertex 1,...,N was s_i.
From the information above, restore the length of each edge. The input guarantees that it is possible to determine the lengths of the edges consistently with the record. Furthermore, it can be proved that the length of each edge is uniquely determined in such a case.
Constraints
* 2 \leq N \leq 10^{5}
* 1 \leq a_i,b_i \leq N
* 1 \leq s_i \leq 10^{18}
* The given graph is a tree.
* All input values are integers.
* It is possible to consistently restore the lengths of the edges.
* In the restored graph, the length of each edge is an integer between 1 and 10^{18} (inclusive).
Input
Input is given from Standard Input in the following format:
N
a_1 b_1
:
a_{N-1} b_{N-1}
s_1 s_2 ... s_{N}
Output
Print N-1 lines. The i-th line must contain the length of Edge i.
Examples
Input
4
1 2
2 3
3 4
8 6 6 8
Output
1
2
1
Input
5
1 2
1 3
1 4
1 5
10 13 16 19 22
Output
1
2
3
4
Input
15
9 10
9 15
15 4
4 13
13 2
13 11
2 14
13 6
11 1
1 12
12 3
12 7
2 5
14 8
1154 890 2240 883 2047 2076 1590 1104 1726 1791 1091 1226 841 1000 901
Output
5
75
2
6
7
50
10
95
9
8
78
28
89
8
Submitted Solution:
```
def main():
n = int(input())
ab = [list(map(int, input().split())) for _ in [0]*(n-1)]
s = list(map(int, input().split()))
g = [[] for _ in [0]*n]
[g[a-1].append(b-1) for a, b in ab]
[g[b-1].append(a-1) for a, b in ab]
root = 0 # 根
d = [-1]*n # 根からの距離
d[root] = 0
q = [root]
cnt = 0
while q: # BFS
cnt += 1
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] == -1:
d[j] = cnt
qq.append(j)
q = qq
dd = [[j, i] for i, j in enumerate(d)]
dd.sort(key=lambda x: -x[0])
dd = [j for i, j in dd]
dp = [1]*n
for i in dd:
for j in g[i]:
if d[j] > d[i]:
dp[i] += dp[j]
ans = []
for a, b in ab:
a -= 1
b -= 1
if d[a] > d[b]:
a, b = b, a
ay = dp[b]-1
ax = n-2-ay
if ax-ay == 0:
ans.append(1j)
else:
ans.append(abs(s[a]-s[b])//abs(ax-ay))
ab_dict = {(ab[i][0]-1, ab[i][1]-1): ans[i] for i in range(n-1)}
if 1j in ans:
p = ans.index(1j)
q = [root]
temp_1 = 0
temp_2 = 0
while q:
qq = []
while q:
i = q.pop()
for j in g[i]:
if d[j] > d[i]:
a, b = min(i, j), max(i, j)
temp = ab_dict[(a, b)]
if temp == 1j:
temp_2 = dp[j]
else:
temp_1 += dp[j]*temp
qq.append(j)
q = qq
ans[p] = (s[0]-temp_1)//temp_2
for i in ans:
print(i)
main()
``` | instruction | 0 | 43,661 | 13 | 87,322 |
No | output | 1 | 43,661 | 13 | 87,323 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,845 | 13 | 87,690 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from collections import defaultdict
from sys import stdin, setrecursionlimit
import threading
input = stdin.buffer.readline
def work():
res = 0
ans = 0
setrecursionlimit(1 << 18)
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
graph = defaultdict(list)
dist = dict()
for v in range(n-1):
a1, b = map(int, input().split())
graph[a1].append(b)
graph[b].append(a1)
def dfs(v, par, h=0):
nonlocal res
res += h*a[v]
dist[v] = a[v]
for node in graph[v]:
if node != par:
dfs(node, v, h+1)
dist[v] += dist[node]
def dfs2(v, par):
nonlocal ans, res
ans = max(ans, res)
for node in graph[v]:
if node != par:
res -= dist[node]
dist[v] -= dist[node]
res += dist[v]
dist[node] += dist[v]
dfs2(node, v)
dist[node] -= dist[v]
res -= dist[v]
dist[v] += dist[node]
res += dist[node]
dfs(1, -1)
dfs2(1, -1)
print(ans)
setrecursionlimit(300050)
threading.stack_size(100000000)
thread = threading.Thread(target=work)
thread.start()
``` | output | 1 | 43,845 | 13 | 87,691 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,846 | 13 | 87,692 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
'''t=int(input())
while(t):
t-=1
n,k=[int(x) for x in input().split()]
s=""
while(len(s)!=n):
i=0
while(i<k):
if len(s)==n:
break
s+=chr(97+i)
i+=1
print(s)'''
'''n=int(input())
arr=[int(x) for x in input().split()]
arr=sorted(arr)
ans=0
for i in range(0,n-1,2):
ans+=abs(arr[i]-arr[i+1])
print(ans)'''
from collections import defaultdict
import sys,threading
def work():
sys.setrecursionlimit(1 << 18)
def fun(u,level,p):
l[1]+=level*arr[u-1]
summ[u]=arr[u-1]
for i in graph[u]:
if i!=p:
fun(i,level+1,u)
summ[u]+=summ[i]
def fun2(u,p):
for i in graph[u]:
if i!=p:
l[i]=l[u]+s-2*summ[i]
fun2(i,u)
n=int(input())
n1=n
arr=[int(x) for x in input().split()]
graph=defaultdict(list)
while(n1-1):
n1-=1
u,v=[int(x) for x in input().split()]
graph[u].append(v)
graph[v].append(u)
s=0
for i in arr:
s+=i
summ=[0]*(n+1)
l=[0]*(n+1)
fun(1,0,0)
fun2(1,0)
print(max(l))
if __name__ == '__main__':
sys.setrecursionlimit(200050)
threading.stack_size(80000000)
thread = threading.Thread(target=work)
thread.start()
``` | output | 1 | 43,846 | 13 | 87,693 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,847 | 13 | 87,694 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
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")
sys.setrecursionlimit(2*10**5)
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
@bootstrap
def dfs(u,p):
for j in adj[u]:
if j!=p:
yield dfs(j,u)
f[u]+=(f[j]+res[j])
res[u]+=res[j]
res[u]+=b[u-1]
yield
@bootstrap
def dfs2(u,p,val):
for j in adj[u]:
if j!=p:
yield dfs2(j,u,f[u]-(f[j]+res[j])+val+(s-res[u]))
ans[u]=f[u]+val+(s-res[u])
yield
n=int(input())
b=list(map(int,input().split()))
s=sum(b)
adj=[[] for i in range(n+1)]
for j in range(n-1):
u,v=map(int,input().split())
adj[u].append(v)
adj[v].append(u)
f=[0]*(n+1)
res=[0]*(n+1)
dfs(1,0)
ans=[0]*(n+1)
dfs2(1,0,0)
print(max(ans[1:]))
``` | output | 1 | 43,847 | 13 | 87,695 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,848 | 13 | 87,696 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import traceback
import sys
sys.setrecursionlimit(200010)
try:
# alpha = "abcdefghijklmnopqrstuvwxyz"
n = int(input())
a = [0]
a.extend(list(map(int, input().split())))
D = [[] for i in range(n+1)]
for i in range(n-1):
e1,e2 = (map(int, input().split()))
D[e1].append(e2)
D[e2].append(e1)
# for i in range(1,n+1):
# if i not in D:
# D[i] = []
visited = [False for i in range(n+1)]
cost = [a[i] for i in range(n+1)]
parent = [0 for i in range(n+1)]
val = 0
def dfs(s, depth):
global visited
global cost
global val
global a
global D
stack = [(s,depth)]
while stack:
s, depth = stack[-1]
if visited[s]:
stack.pop()
cost[parent[s]]+=cost[s]
continue
else:
visited[s] = True
val += depth*a[s]
for i in D[s]:
if not visited[i]:
parent[i] = s
stack.append((i, depth+1))
# cost[s]+=cost[i]
dfs(1, 0)
# ans = 1
max_cost = val
# print(max_cost)
visited = [False for i in range(n+1)]
cost[0] = sum(a)
def trav(s, some_val):
global cost
global visited
global max_cost
global D
stack = [(s,some_val)]
while stack:
s, some_val = stack.pop()
visited[s] = True
# print(some_val, s)
if some_val>max_cost:
max_cost = some_val
for i in D[s]:
if not visited[i]:
# print(i, some_val, cost[s], cost[i])
stack.append((i, some_val+(cost[0]-cost[i])-cost[i] ))
trav(1, val)
print(max_cost)
except Exception as ex:
traceback.print_tb(ex.__traceback__)
print(ex)
``` | output | 1 | 43,848 | 13 | 87,697 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,849 | 13 | 87,698 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import io,os
from collections import deque
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
class Node:
def __init__(self,val):
self.val = int(val)
self.cul = 0
self.child = set()
self.path = {}
def __str__(self):
return f'{self.val} {self.child} {self.path}'
n = int(input())
a = list(map(Node,input().split()))
su = 0
for i in a:
su += i.val
for _ in range(n-1):
u,v = map(int,input().split())
a[u-1].child.add(v)
a[v-1].child.add(u)
st = [1]
while len(st):
x = st[-1]
if not len(a[x-1].child):
curr = a[st.pop()-1].val+a[x-1].cul
if len(st):
a[x-1].path[st[-1]] = su-a[x-1].val-sum(a[x-1].path.values())
a[st[-1]-1].path[x] = curr
a[st[-1]-1].cul += curr
else:
y = a[x-1].child.pop()
a[y-1].child.remove(x)
st.append(y)
curr,visi,ans = deque([1]),{1},0
while len(curr):
x = curr.popleft()
for y in a[x-1].path:
if y not in visi:
ans += a[x-1].path[y]
visi.add(y)
curr.append(y)
maxi,val = ans,[0]*n
val[0] = ans
curr,visi = deque([1]),{1}
while len(curr):
x = curr.popleft()
for y in a[x-1].path:
if y not in visi:
val[y-1] = val[x-1]-a[x-1].path[y]+a[y-1].path[x]
maxi = max(maxi,val[y-1])
visi.add(y)
curr.append(y)
print(maxi)
``` | output | 1 | 43,849 | 13 | 87,699 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,850 | 13 | 87,700 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
import sys
from collections import deque
from types import GeneratorType
sys.setrecursionlimit(200000)
input = sys.stdin.readline
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())
val = [int(i) for i in input().split()]
tree = [[] for i in range(n + 1)]
dp = [0 for i in range(n + 1)]
s = [0 for i in range(n + 1)]
ans = [0 for i in range(n + 1)]
for i in range(n - 1):
a,b = map(int,input().split())
tree[a].append(b)
tree[b].append(a)
@bootstrap
def dfs1(node,dist,pd):
for child in tree[node]:
if child == pd:
continue
yield dfs1(child,dist + 1, node)
dp[node] += dp[child]
s[node] += s[child]
dp[node] += val[node - 1] * dist
s[node] += val[node - 1]
yield dp[node]
dfs1(1,0,1)
q = deque(); ans[1] = dp[1]
for node in tree[1]:
q.append((node,1))
while len(q) > 0:
node,pd = q.popleft()
sub_dp = ans[pd] - (dp[node] + s[node])
added = s[1] - s[node]
ans[node] = sub_dp + added + dp[node]
for child in tree[node]:
if child == pd:
continue
q.append((child,node))
print(max(ans))
``` | output | 1 | 43,850 | 13 | 87,701 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,851 | 13 | 87,702 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
from sys import stdin,setrecursionlimit
n = int(stdin.readline())
ay = [int(x) for x in stdin.readline().split()]
graph = [set() for x in range(n)]
for e in range(n-1):
a,b = [int(x)-1 for x in stdin.readline().split()]
graph[a].add(b)
graph[b].add(a)
dists = {}
child = {}
bruh = sum(ay)
#visited = set()
path = [(0,0)]
for x,p in path:
for y in graph[x]:
if y != p:
path.append((y,x))
for x,parent in path[::-1]:
total = 0
children = ay[x]
for v in graph[x]:
if v != parent:
c, sm = child[v], dists[v]
children += c
total += sm+c
dists[x] = total
child[x] = children
#return (children,total)
b2,b3 = child[0], dists[0]
for x,parent in path:
for v in graph[x]:
if v != parent:
dists[v] = dists[x]+bruh-child[v]*2
print(max([dists[y] for y in range(n)]))
``` | output | 1 | 43,851 | 13 | 87,703 |
Provide tags and a correct Python 3 solution for this coding contest problem.
You are given a tree consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0. | instruction | 0 | 43,852 | 13 | 87,704 |
Tags: dfs and similar, dp, trees
Correct Solution:
```
"""
Satwik_Tiwari ;) .
30th AUGUST , 2020 - SUNDAY
"""
#===============================================================================================
#importing some useful libraries.
from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter # Counter(list) return a dict with {key: count}
from itertools import combinations as comb # if a = [1,2,3] then print(list(comb(a,2))) -----> [(1, 2), (1, 3), (2, 3)]
from itertools import permutations as permutate
from bisect import bisect_left as bl
#If the element is already present in the list,
# the left most position where element has to be inserted is returned.
from bisect import bisect_right as br
from bisect import bisect
#If the element is already present in the list,
# the right most position where element has to be inserted is returned
#==============================================================================================
#fast I/O region
BUFSIZE = 8192
class FastIO(IOBase):
newlines = 0
def __init__(self, file):
self._fd = file.fileno()
self.buffer = BytesIO()
self.writable = "x" in file.mode or "r" not in file.mode
self.write = self.buffer.write if self.writable else None
def read(self):
while True:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
if not b:
break
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines = 0
return self.buffer.read()
def readline(self):
while self.newlines == 0:
b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
self.newlines = b.count(b"\n") + (not b)
ptr = self.buffer.tell()
self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr)
self.newlines -= 1
return self.buffer.readline()
def flush(self):
if self.writable:
os.write(self._fd, self.buffer.getvalue())
self.buffer.truncate(0), self.buffer.seek(0)
class IOWrapper(IOBase):
def __init__(self, file):
self.buffer = FastIO(file)
self.flush = self.buffer.flush
self.writable = self.buffer.writable
self.write = lambda s: self.buffer.write(s.encode("ascii"))
self.read = lambda: self.buffer.read().decode("ascii")
self.readline = lambda: self.buffer.readline().decode("ascii")
def print(*args, **kwargs):
"""Prints the values to a stream, or to sys.stdout by default."""
sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout)
at_start = True
for x in args:
if not at_start:
file.write(sep)
file.write(str(x))
at_start = False
file.write(kwargs.pop("end", "\n"))
if kwargs.pop("flush", False):
file.flush()
if sys.version_info[0] < 3:
sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout)
else:
sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout)
# inp = lambda: sys.stdin.readline().rstrip("\r\n")
#===============================================================================================
### START ITERATE RECURSION ###
from types import GeneratorType
def iterative(f, stack=[]):
def wrapped_func(*args, **kwargs):
if stack: return f(*args, **kwargs)
to = f(*args, **kwargs)
while True:
if type(to) is GeneratorType:
stack.append(to)
to = next(to)
continue
stack.pop()
if not stack: break
to = stack[-1].send(to)
return to
return wrapped_func
#### END ITERATE RECURSION ####
#===============================================================================================
#some shortcuts
mod = 1000000007
def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input
def out(var): sys.stdout.write(str(var)) #for fast output, always take string
def lis(): return list(map(int, inp().split()))
def stringlis(): return list(map(str, inp().split()))
def sep(): return map(int, inp().split())
def strsep(): return map(str, inp().split())
# def graph(vertex): return [[] for i in range(0,vertex+1)]
def zerolist(n): return [0]*n
def nextline(): out("\n") #as stdout.write always print sring.
def testcase(t):
for pp in range(t):
solve(pp)
def printlist(a) :
for p in range(0,len(a)):
out(str(a[p]) + ' ')
def google(p):
print('Case #'+str(p)+': ',end='')
def lcm(a,b): return (a*b)//gcd(a,b)
def power(x, y, p) :
res = 1 # Initialize result
x = x % p # Update x if it is more , than or equal to p
if (x == 0) :
return 0
while (y > 0) :
if ((y & 1) == 1) : # If y is odd, multiply, x with result
res = (res * x) % p
y = y >> 1 # y = y/2
x = (x * x) % p
return res
def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1)))
def isPrime(n) :
if (n <= 1) : return False
if (n <= 3) : return True
if (n % 2 == 0 or n % 3 == 0) : return False
i = 5
while(i * i <= n) :
if (n % i == 0 or n % (i + 2) == 0) :
return False
i = i + 6
return True
#===============================================================================================
# code here ;))
@iterative
def dfs(v,visited,st,sum,par):
# new.append(st)
visited[st] = 1
for i in v[st]:
if(visited[i] == 0):
ok = yield dfs(v,visited,i,sum,par)
# print(st,i)
par[i] = st
sum[st]+=sum[i]
yield True
def bfs(g,st):
visited = [-1]*(len(g))
visited[st] = 0
queue = deque([])
queue.append(st)
new = []
while(len(queue) != 0):
s = queue.popleft()
new.append(s)
for i in g[s]:
if(visited[i] == -1):
visited[i] = visited[s]+1
queue.append(i)
return visited
def solve(case):
n = int(inp())
val = lis()
g = [[] for i in range(n)]
for i in range(n-1):
a,b = sep()
a-=1
b-=1
g[a].append(b)
g[b].append(a)
a = deepcopy(val)
vis = [False]*n
par = [-1]*n
dfs(g,vis,0,val,par)
# print(val)
# print(par)
currans = 0
dist = bfs(g,0)
for i in range(n):
currans+=a[i]*dist[i]
# print(currans)
ans = currans
ss = sum(a)
q = []
q.append((0,currans))
while(len(q)!=0):
s = q.pop()
# print(s)
currans = s[1]
s = s[0]
for i in g[s]:
if(i == par[s]):
continue
temp = currans - val[i] +(ss-val[i])
# print(temp,i,val[i],val[s])
ans = max(ans,temp)
q.append((i,temp))
print(ans)
testcase(1)
# testcase(int(inp()))
``` | output | 1 | 43,852 | 13 | 87,705 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
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")
# ------------------------------
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush
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)
mod = 998244353
INF = float('inf')
# ------------------------------
def main():
n = N()
arr = [0] + RLL()
gp = [[] for _ in range(n+1)]
for _ in range(n-1):
f, t = RL()
gp[f].append(t)
gp[t].append(f)
q = [(1, 0, 0)]
par = [0]*(n+1)
now = 0
rec = [0]*(n+1)
sm = [0]*(n+1)
while q:
nd, st, dp = q.pop()
if st==0:
now+=1
q.append((nd, 1, dp))
for nex in gp[nd]:
if nex==par[nd]: continue
par[nex] = nd
q.append((nex, 0, dp+1))
else:
rec[nd] += dp * arr[nd]
rec[par[nd]] += rec[nd]
sm[nd] += arr[nd]
sm[par[nd]] += sm[nd]
q = [(1, 0)]
res = rec[1]
ret = res
while q:
nd, st = q.pop()
if st==0:
if nd!=1:
res -= sm[nd]
res += (sm[par[nd]]-sm[nd])
sm[par[nd]] -= sm[nd]
sm[nd] += sm[par[nd]]
ret = max(res, ret)
q.append((nd, 1))
for nex in gp[nd]:
if nex==par[nd]: continue
q.append((nex, 0))
else:
if nd!=1:
sm[nd] -= sm[par[nd]]
sm[par[nd]] += sm[nd]
res -= (sm[par[nd]]-sm[nd])
res += sm[nd]
# res -= (sm[par[nd]]-sm[nd])
print(ret)
if __name__ == "__main__":
main()
``` | instruction | 0 | 43,853 | 13 | 87,706 |
Yes | output | 1 | 43,853 | 13 | 87,707 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
import sys
import io, os
input = sys.stdin.buffer.readline
#input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline
n = int(input())
A = list(map(int, input().split()))
g = [[] for _ in range(n)]
for i in range(n-1):
u, v = map(int, input().split())
u, v = u-1, v-1
g[u].append(v)
g[v].append(u)
s = []
s.append(0)
parent = [-1]*n
dist = [0]*n
order = []
while s:
v = s.pop()
order.append(v)
for u in g[v]:
if u == parent[v]:
continue
parent[u] = v
dist[u] = dist[v]+1
s.append(u)
order.reverse()
dp = [0]*n
res = 0
for v in order:
dp[v] += A[v]
res += A[v]*dist[v]
if parent[v] != -1:
dp[parent[v]] += dp[v]
ans = [0]*n
ans[0] = res
for v in reversed(order):
for u in g[v]:
if u == parent[v]:
continue
res = ans[v]
res -= dp[u]
dp[v] -= dp[u]
res += dp[v]
ans[u] = res
dp[v] += dp[u]
dp[u] += (dp[v]-dp[u])
print(max(ans))
``` | instruction | 0 | 43,854 | 13 | 87,708 |
Yes | output | 1 | 43,854 | 13 | 87,709 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
import os
import sys
from io import BytesIO, IOBase
from types import GeneratorType
from collections import defaultdict
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")
sys.setrecursionlimit(2 * 10 ** 5)
ans=0
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
@bootstrap
def dfs(now, lay, fa):
SUM[now] = 0
NUM[now] = C[now]
for to in A[now]:
if to != fa:
yield dfs(to, lay + 1, now)
SUM[now] += SUM[to]
SUM[now] += NUM[to]
NUM[now] += NUM[to]
yield
@bootstrap
def change(now, fa):
global ans
ans = max(ans, SUM[now])
for to in A[now]:
if to != fa:
SUM[now] -= SUM[to]
SUM[now] -= NUM[to]
NUM[now] -= NUM[to]
NUM[to] += NUM[now]
SUM[to] += SUM[now]
SUM[to] += NUM[now]
yield change(to, now)
SUM[to] -= SUM[now]
SUM[to] -= NUM[now]
NUM[to] -= NUM[now]
NUM[now] += NUM[to]
SUM[now] += SUM[to]
SUM[now] += NUM[to]
yield
n = int(input())
A = [[] for i in range(n + 1)]
C = [0] + (list(map(int, input().split())))
NUM = [0] * (n + 1)
SUM = [0] * (n + 1)
for i in range(n - 1):
x, y = map(int, input().split())
A[x].append(y)
A[y].append(x)
dfs(1, 0, 0)
change(1, 0)
print(ans)
# print(NUM)
# print(SUM)
``` | instruction | 0 | 43,855 | 13 | 87,710 |
Yes | output | 1 | 43,855 | 13 | 87,711 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
from collections import defaultdict
from sys import stdin, setrecursionlimit
import threading
input = stdin.buffer.readline
setrecursionlimit(200050)
def work():
setrecursionlimit(1 << 18)
def dfs(v, par, h=0):
global res
res += h*a[v]
dist[v] = a[v]
for node in graph[v]:
if node != par:
dfs(node, v, h+1)
dist[v] += dist[node]
def dfs2(v, par):
global ans, res
ans = max(ans, res)
for node in graph[v]:
if node != par:
res -= dist[node]
dist[v] -= dist[node]
res += dist[v]
dist[node] += dist[v]
dfs2(node, v)
dist[node] -= dist[v]
res -= dist[v]
dist[v] += dist[node]
res += dist[node]
n = int(input())
a = list(map(int, input().split()))
a.insert(0, 0)
graph = defaultdict(list)
dist = dict()
for v in range(n-1):
a1, b = map(int, input().split())
graph[a1].append(b)
graph[b].append(a1)
dfs(1, 0)
dfs2(1, 0)
print(ans)
res = 0
ans = 0
threading.stack_size(80000000)
thread = threading.Thread(target=work)
thread.start()
``` | instruction | 0 | 43,856 | 13 | 87,712 |
No | output | 1 | 43,856 | 13 | 87,713 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
from sys import stdin,setrecursionlimit
import threading
setrecursionlimit(200000)
def main():
n = int(stdin.readline())
ay = [int(x) for x in stdin.readline().split()]
graph = [set() for x in range(n)]
for e in range(n-1):
a,b = [int(x)-1 for x in stdin.readline().split()]
graph[a].add(b)
graph[b].add(a)
dists = {}
child = {}
bruh = sum(ay)
def dist(x,parent):
total = 0
children = ay[x]
for v in graph[x]:
if v != parent:
c, sm = dist(v,x)
children += c
total += sm+c
dists[x] = total
child[x] = children
return (children,total)
b2,b3 = dist(0,0)
def fix(x,parent):
for v in graph[x]:
if v != parent:
dists[v] = dists[x]+bruh-child[v]*2
fix(v,x)
fix(0,0)
print(max([dists[y] for y in range(n)]))
threading.stack_size(10**8)
t = threading.Thread(target=main)
t.start()
t.join()
#bruh
``` | instruction | 0 | 43,857 | 13 | 87,714 |
No | output | 1 | 43,857 | 13 | 87,715 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
import traceback
try:
# alpha = "abcdefghijklmnopqrstuvwxyz"
n = int(input())
a = [0]
a.extend(list(map(int, input().split())))
D = [[] for i in range(n+1)]
for i in range(n-1):
e1,e2 = (map(int, input().split()))
D[e1].append(e2)
D[e2].append(e1)
# for i in range(1,n+1):
# if i not in D:
# D[i] = []
visited = [False for i in range(n+1)]
cost = [a[i] for i in range(n+1)]
val = 0
def dfs(s, depth):
global visited
global cost
global val
global a
global D
visited[s] = True
val += depth*a[s]
for i in D[s]:
if not visited[i]:
dfs(i, depth+1)
cost[s]+=cost[i]
dfs(1, 0)
# ans = 1
max_cost = val
# print(max_cost)
visited = [False for i in range(n+1)]
cost[0] = sum(a)
def trav(s, some_val):
global cost
global visited
global max_cost
global D
visited[s] = True
# print(some_val, s)
if some_val>max_cost:
max_cost = some_val
for i in D[s]:
if not visited[i]:
# print(i, some_val, cost[s], cost[i])
trav(i, some_val+(cost[0]-cost[i])-cost[i] )
trav(1, val)
print(max_cost)
except Exception as ex:
traceback.print_tb(ex.__traceback__)
print(ex)
``` | instruction | 0 | 43,858 | 13 | 87,716 |
No | output | 1 | 43,858 | 13 | 87,717 |
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 consisting exactly of n vertices. Tree is a connected undirected graph with n-1 edges. Each vertex v of this tree has a value a_v assigned to it.
Let dist(x, y) be the distance between the vertices x and y. The distance between the vertices is the number of edges on the simple path between them.
Let's define the cost of the tree as the following value: firstly, let's fix some vertex of the tree. Let it be v. Then the cost of the tree is ∑_{i = 1}^{n} dist(i, v) ⋅ a_i.
Your task is to calculate the maximum possible cost of the tree if you can choose v arbitrarily.
Input
The first line contains one integer n, the number of vertices in the tree (1 ≤ n ≤ 2 ⋅ 10^5).
The second line of the input contains n integers a_1, a_2, ..., a_n (1 ≤ a_i ≤ 2 ⋅ 10^5), where a_i is the value of the vertex i.
Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by two integers u_i and v_i, the labels of vertices it connects (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i).
It is guaranteed that the given edges form a tree.
Output
Print one integer — the maximum possible cost of the tree if you can choose any vertex as v.
Examples
Input
8
9 4 1 7 10 1 6 5
1 2
2 3
1 4
1 5
5 6
5 7
5 8
Output
121
Input
1
1337
Output
0
Note
Picture corresponding to the first example: <image>
You can choose the vertex 3 as a root, then the answer will be 2 ⋅ 9 + 1 ⋅ 4 + 0 ⋅ 1 + 3 ⋅ 7 + 3 ⋅ 10 + 4 ⋅ 1 + 4 ⋅ 6 + 4 ⋅ 5 = 18 + 4 + 0 + 21 + 30 + 4 + 24 + 20 = 121.
In the second example tree consists only of one vertex so the answer is always 0.
Submitted Solution:
```
from collections import defaultdict
from itertools import accumulate
import sys
input = sys.stdin.readline
'''
for CASES in range(int(input())):
n, m = map(int, input().split())
n = int(input())
A = list(map(int, input().split()))
S = input().strip()
sys.stdout.write(" ".join(map(str,ANS))+"\n")
'''
inf = 100000000000000000 # 1e17
mod = 998244353
def gcd(a,b):
if a%b==0:
return b
return gcd(b,a%b)
def lcm(a,b):
return a//gcd(a,b)*b
n = int(input())
A=[[] for i in range(n+1)]
C = [0]+(list(map(int, input().split())))
NUM=[0]*(n+1)
SUM=[0]*(n+1)
for i in range(n-1):
x,y = map(int, input().split())
A[x].append(y)
A[y].append(x)
ans=0
def dfs(now,lay,fa):
SUM[now]=0
NUM[now]=C[now]
for to in A[now]:
if to!=fa:
dfs(to,lay+1,now)
SUM[now]+=SUM[to]
SUM[now]+=NUM[to]
NUM[now]+=NUM[to]
def change(now,fa):
global ans
ans=max(ans,SUM[now])
for to in A[now]:
if to!=fa:
SUM[now]-=SUM[to]
SUM[now]-=NUM[to]
NUM[now]-=NUM[to]
NUM[to]+=NUM[now]
SUM[to]+=SUM[now]
SUM[to]+=NUM[now]
change(to,now)
SUM[to]-=SUM[now]
SUM[to]-=NUM[now]
NUM[to]-=NUM[now]
NUM[now]+=NUM[to]
SUM[now]+=SUM[to]
SUM[now] += NUM[to]
def main():
dfs(1,0,0)
change(1,0)
import threading
t = threading.Thread(target=main)
t.start()
t.join()
print(ans)
# print(NUM)
# print(SUM)
``` | instruction | 0 | 43,859 | 13 | 87,718 |
No | output | 1 | 43,859 | 13 | 87,719 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n nodes and q queries.
Every query starts with three integers k, m and r, followed by k nodes of the tree a_1, a_2, …, a_k. To answer a query, assume that the tree is rooted at r. We want to divide the k given nodes into at most m groups such that the following conditions are met:
* Each node should be in exactly one group and each group should have at least one node.
* In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other.
You need to output the number of ways modulo 10^{9}+7 for every query.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 10^{5}) — the number of vertices in the tree and the number of queries, respectively.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree.
Each of the next q lines starts with three integers k, m and r (1 ≤ k, r ≤ n, 1 ≤ m ≤ min(300,k)) — the number of nodes, the maximum number of groups and the root of the tree for the current query, respectively. They are followed by k distinct integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n), denoting the nodes of the current query.
It is guaranteed that the sum of k over all queries does not exceed 10^{5}.
Output
Print q lines, where the i-th line contains the answer to the i-th query.
Examples
Input
7 2
5 4
2 6
5 3
1 2
7 5
4 6
3 3 2 7 4 3
3 1 4 6 2 1
Output
2
0
Input
7 2
4 7
2 5
4 1
5 1
5 6
4 3
3 3 2 7 1 4
2 1 6 3 2
Output
1
1
Input
5 2
3 5
4 5
4 2
1 4
2 2 3 1 2
2 2 4 5 4
Output
2
1
Note
Consider the first example.
In the first query, we have to divide the three given nodes (7, 4 and 3), into the maximum of three groups assuming that the tree is rooted at 2. When the tree is rooted at 2, 4 is an ancestor of both 3 and 7. So we can't put all the nodes into one group. There is only 1 way to divide the given nodes into two groups, which are [4] and [3, 7]. Also, there is only one way to divide the given nodes into three groups, which are [7], [4] and [3]. So, there are total 2 ways to divide the given nodes into a maximum of three groups.
In the second query, when the tree is rooted at 4, 6 is an ancestor of 2 and 2 is an ancestor of 1. So, we can't put all the given nodes into one group.
Submitted Solution:
```
import operator as op
from functools import reduce
class Node:
def __init__(self, number):
self.__number = number
self.__connected_nodes = []
self.__children_nodes = []
self.__is_root = False
self.__node_towards_root = None
self.__distance_to_root = None
def add_connection(self, node):
if node not in self.__connected_nodes:
self.__connected_nodes.append(node)
def get_number(self):
return self.__number
def get_connections(self):
return self.__connected_nodes
def get_number_of_connections(self):
return len(self.__connected_nodes)
def has_child(self):
return False if len(self.__connected_nodes) == 1 else True
def is_root(self):
return self.__is_root
def set_root(self):
self.__is_root = True
def unset_root(self):
self.__is_root = False
def get_node_to_root(self):
return self.__node_towards_root
def set_node_to_root(self, node):
self.__node_towards_root = node
for connode in self.__connected_nodes:
if connode is not node:
self.__children_nodes.append(connode)
def unset_node_to_root(self):
self.__node_towards_root = None
self.__children_nodes = []
def get_distance_to_root(self):
return self.__distance_to_root
def set_distance_to_root(self, distance):
self.__distance_to_root = distance
def get_children(self):
return self.__children_nodes
class Tree:
def __init__(self, num_nodes):
self.__nodes = []
self.__connections = []
self.__root = None
for i in range(num_nodes):
self.__nodes.append(Node(i + 1))
def add_connection(self, node1, node2):
Node1 = self.__get_node(node1)
Node2 = self.__get_node(node2)
Node1.add_connection(Node2)
Node2.add_connection(Node1)
def __set_directions(self, rootnode=None):
if rootnode is None:
rootnode = self.__root
rootnode.set_node_to_root(self.__root)
for node in rootnode.get_connections():
if node.get_node_to_root() is None:
node.set_node_to_root(rootnode)
self.__set_directions(node)
def __set_distances_to_root(self, count=0, startnode=None):
if count == 0:
startnode = self.__root
startnode.set_distance_to_root(count)
count += 1
for node in startnode.get_children():
self.__set_distances_to_root(count, node)
else:
startnode.set_distance_to_root(count)
count += 1
if startnode.has_child():
for node in startnode.get_children():
self.__set_distances_to_root(count, node)
def __set_root(self, root):
self.__get_node(root).set_root()
self.__root = self.__get_node(root)
self.__set_directions()
self.__set_distances_to_root()
def __unset_root(self):
for node in self.__nodes:
node.unset_root()
node.unset_node_to_root()
self.__root = None
def __get_node(self, node):
return self.__nodes[node - 1]
def __are_related(self, node1, node2):
node1 = self.__get_node(node1)
node2 = self.__get_node(node2)
if node1 == self.__root or node2 == self.__root or node1 == node2:
return True
# Make Node 1 the Node with greatest distance from root:
if node1.get_distance_to_root() < node2.get_distance_to_root():
temp = node2
node2 = node1
node1 = temp
return self.__check_ancestry(node1, node2)
def __check_ancestry(self, node1, node2):
# Node 1 is the farthest from root. If Node2 exists in Node1's line, they are related.
node1 = node1.get_node_to_root()
if node1 == node2:
return True
if node1 is self.__root or node1 is None:
return False
return self.__check_ancestry(node1, node2)
@staticmethod
def __ncr(n, r):
# N choose R - Provides # of possible groups that can form
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer / denom
def check_connections(self):
print("Connections:")
for node in self.__nodes:
children = ""
for subnode in node.get_connections():
children += str(subnode.get_number()) + " "
print("Node " + str(node.get_number()) + " is connected to: " + children)
def query(self, *queryitems):
# Clear current root:
self.__unset_root()
# Get key points:
q_numnodes = int(queryitems[0])
q_maxgroups = int(queryitems[1])
q_rootnode = int(queryitems[2])
# Get nodes:
q_numnodes = queryitems[-q_numnodes:]
q_nodes = []
for q_node in q_numnodes:
q_nodes.append(int(q_node))
# Set root:
self.__set_root(q_rootnode)
# Get max # of groups:
theo_max = self.__ncr(len(q_numnodes), 2) + 1
# Decrement theo_max if there are and relations within the branch:
i = 0
while i < len(q_nodes):
j = i + 1
while j < len(q_nodes):
if self.__are_related(q_nodes[i], q_nodes[j]):
theo_max -= 1
j += 1
i += 1
if theo_max == q_maxgroups == 1:
return 0
return int(theo_max) if int(theo_max) < q_maxgroups else q_maxgroups
def run():
# Variables:
tree = None
tree_nodes = None
num_queries = None
queries = []
# Get First Line (# Nodes, Connections, and # of Queries):
tree_nodes = input()
tree_nodes = tree_nodes.split(" ")
tree = Tree(int(tree_nodes[0]))
num_queries = int(tree_nodes[1])
# Get Connections:
tree_nodes = int(tree_nodes[0])
for i in range(tree_nodes - 1):
connection = input()
connection = connection.split(" ")
tree.add_connection(int(connection[0]), int(connection[1]))
# Get Queries:
for i in range(num_queries):
# Each query is added as a tuple into queries
query = input()
query = query.split(" ")
queries.append(query)
# Get Outputs:
for query in queries:
print(str(tree.query(*query)))
run()
``` | instruction | 0 | 43,860 | 13 | 87,720 |
No | output | 1 | 43,860 | 13 | 87,721 |
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response.
You are given a tree with n nodes and q queries.
Every query starts with three integers k, m and r, followed by k nodes of the tree a_1, a_2, …, a_k. To answer a query, assume that the tree is rooted at r. We want to divide the k given nodes into at most m groups such that the following conditions are met:
* Each node should be in exactly one group and each group should have at least one node.
* In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other.
You need to output the number of ways modulo 10^{9}+7 for every query.
Input
The first line contains two integers n and q (1 ≤ n, q ≤ 10^{5}) — the number of vertices in the tree and the number of queries, respectively.
Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree.
Each of the next q lines starts with three integers k, m and r (1 ≤ k, r ≤ n, 1 ≤ m ≤ min(300,k)) — the number of nodes, the maximum number of groups and the root of the tree for the current query, respectively. They are followed by k distinct integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n), denoting the nodes of the current query.
It is guaranteed that the sum of k over all queries does not exceed 10^{5}.
Output
Print q lines, where the i-th line contains the answer to the i-th query.
Examples
Input
7 2
5 4
2 6
5 3
1 2
7 5
4 6
3 3 2 7 4 3
3 1 4 6 2 1
Output
2
0
Input
7 2
4 7
2 5
4 1
5 1
5 6
4 3
3 3 2 7 1 4
2 1 6 3 2
Output
1
1
Input
5 2
3 5
4 5
4 2
1 4
2 2 3 1 2
2 2 4 5 4
Output
2
1
Note
Consider the first example.
In the first query, we have to divide the three given nodes (7, 4 and 3), into the maximum of three groups assuming that the tree is rooted at 2. When the tree is rooted at 2, 4 is an ancestor of both 3 and 7. So we can't put all the nodes into one group. There is only 1 way to divide the given nodes into two groups, which are [4] and [3, 7]. Also, there is only one way to divide the given nodes into three groups, which are [7], [4] and [3]. So, there are total 2 ways to divide the given nodes into a maximum of three groups.
In the second query, when the tree is rooted at 4, 6 is an ancestor of 2 and 2 is an ancestor of 1. So, we can't put all the given nodes into one group.
Submitted Solution:
```
import operator as op
from functools import reduce
class Node:
def __init__(self, number):
self.__number = number
self.__connected_nodes = []
self.__children_nodes = []
self.__is_root = False
self.__node_towards_root = None
self.__distance_to_root = None
def add_connection(self, node):
if node not in self.__connected_nodes:
self.__connected_nodes.append(node)
def get_number(self):
return self.__number
def get_connections(self):
return self.__connected_nodes
def get_number_of_connections(self):
return len(self.__connected_nodes)
def has_child(self):
return False if len(self.__connected_nodes) == 1 else True
def is_root(self):
return self.__is_root
def set_root(self):
self.__is_root = True
def unset_root(self):
self.__is_root = False
def get_node_to_root(self):
return self.__node_towards_root
def set_node_to_root(self, node):
self.__node_towards_root = node
for connode in self.__connected_nodes:
if connode is not node:
self.__children_nodes.append(connode)
def unset_node_to_root(self):
self.__node_towards_root = None
self.__children_nodes = []
def get_distance_to_root(self):
return self.__distance_to_root
def set_distance_to_root(self, distance):
self.__distance_to_root = distance
def get_children(self):
return self.__children_nodes
class Tree:
def __init__(self, num_nodes):
self.__nodes = []
self.__connections = []
self.__root = None
for i in range(num_nodes):
self.__nodes.append(Node(i + 1))
def add_connection(self, node1, node2):
Node1 = self.__get_node(node1)
Node2 = self.__get_node(node2)
Node1.add_connection(Node2)
Node2.add_connection(Node1)
def __set_directions(self, rootnode=None):
if rootnode is None:
rootnode = self.__root
rootnode.set_node_to_root(self.__root)
for node in rootnode.get_connections():
if node.get_node_to_root() is None:
node.set_node_to_root(rootnode)
self.__set_directions(node)
def __set_distances_to_root(self, count=0, startnode=None):
if count == 0:
startnode = self.__root
startnode.set_distance_to_root(count)
count += 1
for node in startnode.get_children():
self.__set_distances_to_root(count, node)
else:
startnode.set_distance_to_root(count)
count += 1
if startnode.has_child():
for node in startnode.get_children():
self.__set_distances_to_root(count, node)
def __set_root(self, root):
self.__get_node(root).set_root()
self.__root = self.__get_node(root)
self.__set_directions()
self.__set_distances_to_root()
def __unset_root(self):
for node in self.__nodes:
node.unset_root()
node.unset_node_to_root()
self.__root = None
def __get_node(self, node):
return self.__nodes[node - 1]
def __are_related(self, node1, node2):
node1 = self.__get_node(node1)
node2 = self.__get_node(node2)
if node1 == self.__root or node2 == self.__root or node1 == node2:
return True
# Make Node 1 the Node with greatest distance from root:
if node1.get_distance_to_root() < node2.get_distance_to_root():
temp = node2
node2 = node1
node1 = temp
return self.__check_ancestry(node1, node2)
def __check_ancestry(self, node1, node2):
# Node 1 is the farthest from root. If Node2 exists in Node1's line, they are related.
node1 = node1.get_node_to_root()
if node1 == node2:
return True
if node1 is self.__root or node1 is None:
return False
return self.__check_ancestry(node1, node2)
@staticmethod
def __ncr(n, r):
# N choose R - Provides # of possible groups that can form
r = min(r, n - r)
numer = reduce(op.mul, range(n, n - r, -1), 1)
denom = reduce(op.mul, range(1, r + 1), 1)
return numer / denom
def check_connections(self):
print("Connections:")
for node in self.__nodes:
children = ""
for subnode in node.get_connections():
children += str(subnode.get_number()) + " "
print("Node " + str(node.get_number()) + " is connected to: " + children)
def query(self, *queryitems):
# Clear current root:
self.__unset_root()
# Get key points:
q_numnodes = int(queryitems[0])
q_maxgroups = int(queryitems[1])
q_rootnode = int(queryitems[2])
# Get nodes:
q_numnodes = queryitems[-q_numnodes:]
q_nodes = []
for q_node in q_numnodes:
q_nodes.append(int(q_node))
# Set root:
self.__set_root(q_rootnode)
# Get max # of groups:
theo_max = self.__ncr(len(q_numnodes), 2) + 1
# Decrement theo_max if there are and relations within the branch:
i = 0
while i < len(q_nodes):
j = i + 1
while j < len(q_nodes):
if self.__are_related(q_nodes[i], q_nodes[j]):
theo_max -= 1
j += 1
i += 1
if theo_max == q_maxgroups == 1:
return 0
return int(theo_max) if int(theo_max) < q_maxgroups else q_maxgroups
def run():
# Variables:
tree = None
tree_nodes = None
num_queries = None
queries = []
# Get First Line (# Nodes, Connections, and # of Queries):
print("Enter first line (# of nodes, # of queries):")
tree_nodes = input()
tree_nodes = tree_nodes.split(" ")
tree = Tree(int(tree_nodes[0]))
num_queries = int(tree_nodes[1])
# Get Connections:
tree_nodes = int(tree_nodes[0])
print("Enter connections:")
for i in range(tree_nodes - 1):
connection = input()
connection = connection.split(" ")
tree.add_connection(int(connection[0]), int(connection[1]))
# Get Queries:
print("Enter queries:")
for i in range(num_queries):
# Each query is added as a tuple into queries
query = input()
query = query.split(" ")
queries.append(query)
# Get Outputs:
for query in queries:
print(str(tree.query(*query)))
run()
``` | instruction | 0 | 43,861 | 13 | 87,722 |
No | output | 1 | 43,861 | 13 | 87,723 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.