message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a graph with 3 ⋅ n vertices and m edges. You are to find a matching of n edges, or an independent set of n vertices. A set of edges is called a matching if no two edges share an endpoint. A set of vertices is called an independent set if no two vertices are connected with an edge. Input The first line contains a single integer T ≥ 1 — the number of graphs you need to process. The description of T graphs follows. The first line of description of a single graph contains two integers n and m, where 3 ⋅ n is the number of vertices, and m is the number of edges in the graph (1 ≤ n ≤ 10^{5}, 0 ≤ m ≤ 5 ⋅ 10^{5}). Each of the next m lines contains two integers v_i and u_i (1 ≤ v_i, u_i ≤ 3 ⋅ n), meaning that there is an edge between vertices v_i and u_i. It is guaranteed that there are no self-loops and no multiple edges in the graph. It is guaranteed that the sum of all n over all graphs in a single test does not exceed 10^{5}, and the sum of all m over all graphs in a single test does not exceed 5 ⋅ 10^{5}. Output Print your answer for each of the T graphs. Output your answer for a single graph in the following format. If you found a matching of size n, on the first line print "Matching" (without quotes), and on the second line print n integers — the indices of the edges in the matching. The edges are numbered from 1 to m in the input order. If you found an independent set of size n, on the first line print "IndSet" (without quotes), and on the second line print n integers — the indices of the vertices in the independent set. If there is no matching and no independent set of the specified size, print "Impossible" (without quotes). You can print edges and vertices in any order. If there are several solutions, print any. In particular, if there are both a matching of size n, and an independent set of size n, then you should print exactly one of such matchings or exactly one of such independent sets. Example Input 4 1 2 1 3 1 2 1 2 1 3 1 2 2 5 1 2 3 1 1 4 5 1 1 6 2 15 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 4 5 4 6 5 6 Output Matching 2 IndSet 1 IndSet 2 4 Matching 1 15 Note The first two graphs are same, and there are both a matching of size 1 and an independent set of size 1. Any of these matchings and independent sets is a correct answer. The third graph does not have a matching of size 2, however, there is an independent set of size 2. Moreover, there is an independent set of size 5: 2 3 4 5 6. However such answer is not correct, because you are asked to find an independent set (or matching) of size exactly n. The fourth graph does not have an independent set of size 2, but there is a matching of size 2. Submitted Solution: ``` import sys input = sys.stdin.readline T = int(input()) for test in range(T): n,m = map(int,input().split()) edge = [[] for i in range(3*n)] for i in range(m): v1, v2 = map(int,input().split()) u = min(v1,v2) - 1 v = max(v1,v2) - 1 edge[u].append((v,i+1)) match = [] num = 0 matched = [False] * (3*n) for v in range(3*n): if not matched[v]: for (u,e) in edge[v]: if not matched[u]: num += 1 match.append(e) matched[u] = True matched[v] = True break if len(match) == n: print('Matching') print(' '.join(map(str,match[:n]))) else: left = n out = [] for i in range(3*n): if not matched[i]: out.append(str(i+1)) left -= 1 if left == 0: break print('IndSet') print(' '.join(out)) ```
instruction
0
45,479
13
90,958
No
output
1
45,479
13
90,959
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,555
13
91,110
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` import sys from collections import defaultdict,deque input=sys.stdin.readline for _ in range(int(input())): n=int(input()) g=defaultdict(list) for i in range(n-1): u,v=map(int,input().split()) g[u].append(v) g[v].append(u) d=[1]*(n+1) p=[0]*(n+1) l=[10**6]*(n+1) q=deque([1]) v=[0]*(n+1) v[1]=1 rec=[] c=defaultdict(list) while q: x=q.popleft() rec.append(x) for i in g[x]: if v[i]==0: v[i]=1 p[i]=x c[x].append(i) q.append(i) rec.reverse() for i in rec: for j in c[i]: d[i]+=d[j] x=max(d) for i in range(1,n+1): mm=-1 for j in c[i]: mm=max(mm,d[j]) mm=max(mm,x-d[i]) l[i]=mm m=min(l) cnt=l.count(m) if cnt==1: print(1,c[1][0]) print(1,c[1][0]) else: for i in range(1,n+1): if l[i]==m: break for j in range(i+1,n+1): if l[j]==m: break m=10**9 mi=-1 for k in g[j]: if k==i: continue if m>d[k]: m=d[k] mi=k print(j,mi) print(i,mi) ```
output
1
45,555
13
91,111
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,556
13
91,112
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` """ NTC here """ #!/usr/bin/env python import os import sys from io import BytesIO, IOBase # def dfs(adj, start=0): # n = len(adj) # visited = [False]*n # srt = [start] # parent = [-1]*n # childs = [[] for i in range(n)] # count_elements = [1]*n # while srt: # v = srt.pop() # # print(v, end="->") # if visited[v]: # if parent[v] != -1: # childs[parent[v]].append(count_elements[v]) # count_elements[parent[v]] += count_elements[v] # continue # visited[v] = True # if parent[v] != -1: # srt.append(parent[v]) # found_ch = 0 # for u in adj[v]: # if not visited[u]: # parent[u] = v # srt.append(u) # print(childs, count_elements) # recusive with optimization from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def DFS(adj): parent = {} # dp[i] = number of elements in sub tree N = len(adj) dp = [1]*N centroid = [-1]*N @bootstrap def DFS_use(adj, s): sm = 0 mx = 0 for i in adj[s]: if i not in parent: parent[i] = s val_sub = (yield DFS_use(adj, i)) sm += val_sub mx = max(mx, val_sub) dp[s] += sm centroid[s] = max(mx, N-dp[s]) yield dp[s] s = 0 parent[s] = None DFS_use(adj, s) # print(centroid, dp) return centroid def find_centroid(adj): pass def main(): T = iin() while T: T-=1 n = iin() adj = [[] for i in range(n)] for _ in range(n-1): i, j = lin() adj[i-1].append(j-1) adj[j-1].append(i-1) c1 = DFS(adj) c1 = [[c1[i], i] for i in range(n)] c1.sort() mn = c1[0][0] c2 = [] for val, idx in c1: if val == mn: c2.append(idx) # print(c2) ch1 = c2[0] sol = [[adj[ch1][0], ch1], [adj[ch1][0], ch1]] if len(c2)>1: # assume only 2 and both are connected ch1, ch2 = c2[0], c2[1] for v in adj[ch1]: if v != ch2: # attach it to ch2 sol = [[v, ch1], [v, ch2]] break for i, j in sol: print(i+1, j+1) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def iin(): return int(input()) def lin(): return list(map(int, input().split())) # endregion if __name__ == "__main__": main() ```
output
1
45,556
13
91,113
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,557
13
91,114
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` from sys import stdin, stdout readline, printline = stdin.readline, stdout.write def mint(): return int(readline()) def mints(): return list(map(int, readline().split())) class Node: def __init__(self, val): self.val = val self.neighbours = [] self.subtree, self.maxsub = 1, 0 self.visited, self.parent = False, 0 def dfs(tree): q = [-1, 1] tree[1].visited = True while q: v = q.pop() if v < 0: v = -v p = tree[v].parent tree[p].subtree += tree[v].subtree tree[p].maxsub = max(tree[p].maxsub, tree[v].subtree) tree[v].maxsub = max(tree[v].maxsub, n - tree[v].subtree) for neighbour in tree[v].neighbours: if tree[neighbour].visited: continue tree[neighbour].parent = v q.append(-neighbour) q.append(neighbour) tree[neighbour].visited = True return 1 # ip = open("input.txt", "r") for _ in range(mint()): # n = int(ip.readline()) n = mint() graph = {} for _ in range(n-1): x, y = mints() # x, y = map(int, ip.readline().split()) if x not in graph: graph[x] = Node(x) graph[x].neighbours.append(y) if y not in graph: graph[y] = Node(y) graph[y].neighbours.append(x) graph[0] = Node(0) graph[0].neighbours.append(1) dfs(graph) mmcc = graph[min(graph, key=lambda x: graph[x].maxsub)].maxsub centroids = [graph[x] for x in range(1, n + 1) if graph[x].maxsub == mmcc] i = 0 if centroids[0].neighbours[i] == centroids[-1].val: i += 1 printline("{} {}\n".format(centroids[0].val, centroids[0].neighbours[i])) printline("{} {}\n".format(centroids[-1].val, centroids[0].neighbours[i])) ```
output
1
45,557
13
91,115
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,558
13
91,116
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase _str = str BUFSIZE = 8192 def str(x=b''): return x if type(x) is bytes else _str(x).encode() class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') def inp(): return sys.stdin.readline().rstrip() def mpint(): return map(int, inp().split(' ')) def itg(): return int(inp()) # ############################## import # from ACgenerator.Y_Testing import get_code def tree_bfs(tree, flat=True, start=0) -> list: stack = [start] result = [] while stack: new_stack = [] if flat: result.extend(stack) else: result.append(stack) for node in stack: new_stack.extend(tree[node]) stack = new_stack return result def tree_postorder(tree, flat=True, root=0): """ children -> parent """ return tree_bfs(tree, flat, root)[::-1] def get_parent_list(tree): result = [0] * len(tree) for parent, children in enumerate(tree): for child in children: result[child] = parent return result def edge_descendant(tree, edge_time_count=False): """ :return: [{child: num, ...}, ...] the number of vertices under each edge if edge_time_count: the num will translate to the sum of times that walking on the edge the walk mean the path of any pair (u, v) and (u < v) """ vertices = len(tree) results = [{} for _ in range(vertices)] parent_list = get_parent_list(tree) for child in tree_postorder(tree): parent = parent_list[child] if parent != child: results[parent][child] = sum(results[child].values()) + 1 if edge_time_count: for parent in results: for child in parent: num = parent[child] parent[child] = num * (vertices - num) return results def node_split_size(tree) -> list: """ return a list for each node, which contains the size of each tree if take off the node """ vertices = len(tree) results = [list(d.values()) for d in edge_descendant(tree)] for descendant in results: other = vertices - sum(descendant) - 1 if other: descendant.append(other) return results def to_tree(graph, root=0): """ graph: [{child, ...}, ...] (undirected) :return directed graph that parent -> children """ stack = [[root]] while stack: if not stack[-1]: del stack[-1] continue parent = stack[-1].pop() for child in graph[parent]: graph[child].discard(parent) stack.append(list(graph[parent])) def tree_centroid(tree) -> list: vertices = len(tree) half = vertices >> 1 split_count = node_split_size(tree) centroid = [] for node, count in enumerate(split_count): if max(count) <= half: centroid.append(node) if vertices & 1 or len(centroid) == 2: break return centroid def peek(iterable): """ :return first element in the iterable :return None if iterable has nothing """ for element in iterable: return element # ############################## main def solve(): n = itg() if n & 1: for _ in range(n - 2): inp() ans = inp() print(ans) print(ans) return tree = [set() for _ in range(n)] for _ in range(n - 1): u, v = mpint() u -= 1 v -= 1 tree[u].add(v) tree[v].add(u) to_tree(tree) centroids = tree_centroid(tree) if len(centroids) == 1: c1 = centroids[0] print(c1 + 1, peek(tree[c1]) + 1) print(c1 + 1, peek(tree[c1]) + 1) return c1, c2 = centroids if c2 in tree[c1]: c1, c2 = c2, c1 parent = c1 leaf = peek(tree[c1]) while tree[leaf]: # leaf is not leaf parent = leaf leaf = peek(tree[leaf]) print(parent + 1, leaf + 1) print(c2 + 1, leaf + 1) def main(): # solve() # print(solve()) for _ in range(itg()): solve() # print("YES" if solve() else "NO") # print("yes" if solve() else "no") DEBUG = 0 URL = '' if __name__ == '__main__': if DEBUG == 1: import requests # ImportError: cannot import name 'md5' from 'sys' (unknown location) from ACgenerator.Y_Test_Case_Runner import TestCaseRunner runner = TestCaseRunner(main, URL) inp = runner.input_stream print = runner.output_stream runner.checking() elif DEBUG == 2: main() else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) main() # Please check! ```
output
1
45,558
13
91,117
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,559
13
91,118
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` import io import os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc from collections import defaultdict, deque for _ in range(int(input())): n = int(input()) tree = defaultdict(list) edges = [] for i in range(n-1): u, v = map(int, input().split()) tree[u].append(v) tree[v].append(u) edges.append((u, v)) level = {} stack = deque([1]) seen = {} while stack: current = stack[0] if len(tree[current]) == 1 and current != 1: level[current] = 1 stack.popleft() else: if current in seen: for child in tree[current]: if child in level: level[current] = level.get(current, 1)+level[child] stack.popleft() else: for nxt in tree[current]: if nxt not in seen: stack.appendleft(nxt) seen[current] = 1 #print(level) mc = [0]*(n+1) for edge in edges: u, v = edge[0], edge[1] if level[v]<level[u]: u, v = v, u mc[u] = max(mc[u], n-level[u]) mc[v] = max(mc[v], level[u]) #print(mc) m = n-1 for i in range(1, n+1): if mc[i]<m: m = mc[i] #print(m) mins = [] t = 0 for i in range(1, n+1): if mc[i] == m: t+=1 mins.append(i) if t == 1: edge = edges[0] print(edge[0], edge[1]) print(edge[0], edge[1]) else: a = mins[0] b = mins[1] #print(a, b, 'adadd') for i in tree[a]: #print("HAHA") if i!=b: x = i #print(x) break print(a, x) print(b, x) ```
output
1
45,559
13
91,119
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,560
13
91,120
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` import sys from collections import defaultdict, deque from operator import itemgetter sys.setrecursionlimit(200000) _DEBUG = False if _DEBUG: sys.stdin = open('c.in') else: input = sys.stdin.readline def solve(n: int, edges): g = defaultdict(set) for a, b in edges: g[a].add(b) g[b].add(a) # nodes = [None, root] + [None] * (n - 1) deq = deque([1]) while deq: node = deq.popleft() for next in g[node]: g[next].remove(node) deq.append(next) calc_order = [] stack = [1] while stack: node = stack.pop() for child in g[node]: calc_order.append((node, child)) stack.append(child) vertex_count = [0] + [1] * n for parent, child in calc_order[::-1]: vertex_count[parent] += vertex_count[child] candidates = [] for i in range(1, n + 1): largest_child_count = max(vertex_count[child] for child in g[i]) if g[i] else 0 largest_sub_component_size = max(largest_child_count, n - vertex_count[i]) candidates.append((largest_sub_component_size, len(g[i]), i)) candidates.sort(key=itemgetter(0, 1)) if candidates[0][0] < candidates[1][0]: # only one centroid return [edges[0], edges[0]] child = candidates[0][2] parent = candidates[1][2] if parent in g[child]: child, parent = parent, child first_child_of_child = list(g[child])[0] return [ [child, first_child_of_child], [parent, first_child_of_child] ] for _ in range(int(input())): # t n = int(input()) edges = [] for _ in range(n - 1): a, b = map(int, input().split()) edges.append((a, b)) cuts = solve(n, edges) for a, b in cuts: print(a, b) ```
output
1
45,560
13
91,121
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,561
13
91,122
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline def solve(N, graph): stack = [0] Par = [-1]*N checked = [False]*N Children = [1]*N checked[0] = True Ch = [-1]*N while stack: p = stack.pop() if p >= 0: stack.append(~p) for np in graph[p]: if not checked[np]: checked[np] = True Par[np] = p Ch[p] = np stack.append(np) else: p = ~p if p > 0: Children[Par[p]] += Children[p] if N%2 == 1: return 1, graph[0][0]+1, 1, graph[0][0]+1 for n in range(N): if Children[n] == N//2: m = Par[n] l = n while Ch[l] != -1: l = Ch[l] return Par[l]+1, l+1, m+1, l+1 return 1, graph[0][0]+1, 1, graph[0][0]+1 Q = int(input()) for _ in range(Q): N = int(input()) graph = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) a, b, c, d = solve(N, graph) print(a, b) print(c, d) ```
output
1
45,561
13
91,123
Provide tags and a correct Python 3 solution for this coding contest problem. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3.
instruction
0
45,562
13
91,124
Tags: constructive algorithms, dfs and similar, graphs, trees Correct Solution: ``` #Code by Sounak, IIESTS #------------------------------warmup---------------------------- import os import sys import math from io import BytesIO, IOBase from fractions import Fraction import collections from itertools import permutations from collections import defaultdict from collections import deque import threading threading.stack_size(10**8) sys.setrecursionlimit(300000) BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") #-------------------game starts now----------------------------------------------------- #mod = 9223372036854775807 def main(): for ik in range(int(input())): n=int(input()) graph=defaultdict(list) visited = [False] * n sub=[0]*n cen=[] def dfssub(v): visited[v] = True c = 1 for i in graph[v]: if visited[i] == False: c += dfssub(i) sub[v]=c return c def dfs(v): visited[v] = True f=0 for i in graph[v]: if visited[i] == False: dfs(i) if sub[i]>n//2: f=1 if n-sub[v]>n//2: f=1 if f==0: cen.append(v) for i in range(n-1): a,b=map(int,input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) dfssub(0) visited=[False]*n dfs(0) #print(cen,sub) if len(cen)==1: print(1,graph[0][0]+1) print(1, graph[0][0] + 1) continue for i in graph[cen[0]]: if cen[1]!=i: print(cen[0]+1,i+1) print(cen[1] + 1, i + 1) break t = threading.Thread(target=main) t.start() t.join() ```
output
1
45,562
13
91,125
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` from sys import setrecursionlimit,stdin setrecursionlimit(10**8) import threading threading.stack_size(10**8) input=stdin.readline def best(p,prev): x=0 for i in child[p]: if(i!=prev): x+=best(i,p)+1 dp[p]+=dp[i] dp[p]+=x nodes[p]=x return x def dfs1(p,prev,lvl): level[p]=lvl parent[p]=prev for i in child[p]: if(i!=prev): dp[i]+=(dp[p]-(dp[i]+nodes[i]+1))+(n-(nodes[i]+1)) dfs1(i,p,lvl+1) def dfs(p,prev): global leaf for i in child[p]: if(i != prev): dfs(i,p) break if(len(child[p])==1): leaf=p print(prev,leaf) n=0 child,dp,nodes,parent,level=[],[],[],[],[] leaf=-1 def main(): global n global child global dp,nodes,parent,level global leaf for T in range(int(input())): n=int(input()) child=[[] for i in range(n + 1)] for i in range(n-1): u,v=map(int,input().split()) child[u].append(v) child[v].append(u) dp=[0]*(n + 1) nodes=[0]*(n + 1) level=[0]*(n + 1) parent=[-1]*(n + 1) best(1,-1) dfs1(1,-1,0) m=min(dp[1:]) x,y=-1,-1 for i in range(1,n+1): if(m==dp[i]): if(x==-1):x=i else:y=i if(y==-1): print(1,child[1][0]) print(1,child[1][0]) else: leaf=-1 if(level[x] < level[y]): dfs(y,parent[y]) print(x,leaf) else: dfs(x,parent[x]) print(y,leaf) if __name__ == '__main__': threading.Thread(target=main).start() ```
instruction
0
45,563
13
91,126
Yes
output
1
45,563
13
91,127
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` '''# Author : -pratyay- import sys inp=sys.stdin.buffer.readline inar=lambda: list(map(int,inp().split())) inin=lambda: int(inp()) inst=lambda: inp().decode().strip() wrt=sys.stdout.write pr=lambda *args,end='\n': wrt(' '.join([str(x) for x in args])+end) enum=enumerate inf=float('inf') # Am I debugging ? Check if I'm using same variable name in two places # fun() returning empty list ? check new=temp[:] or new=temp _T_=inin() for _t_ in range(_T_): n=inin() a=inar() last=[-1 for i in range(n+1)] gap=[-1 for i in range(n+1)] for i in range(n): gap[a[i]]=max(gap[a[i]],i-last[a[i]]) last[a[i]]=i for i in a: gap[i]=max(gap[i],n-last[i]) gapmin=[inf for i in range(n+1)] for i in range(1,n+1): if gap[i]==-1: continue gapmin[gap[i]]=min(gapmin[gap[i]],i) for i in range(1,n+1): gapmin[i]=min(gapmin[i-1],gapmin[i]) for i in range(n+1): if gapmin[i]==inf: gapmin[i]=-1 pr(*gapmin[1:]) # react.js # javascript # node.js # async await, fetch # dunzo # cred # freecharge # share chat -> they ask, how operating system works # threading # Air bnb''' ''' import pyttsx3 import datetime import speech_recognition as sr engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') #print(voices) engine.setProperty('voice',voices[0].id) def userInit(): print("Login Name : ",end='') _name_=input() return _name_ def speak(audio): engine.say(audio) engine.runAndWait() def wishMe(User): hour = int(datetime.datetime.now().hour) if hour>=0 and hour<12: speak("Good Morning") elif hour>=12 and hour<18: speak("Good Evening") speak("Jarvis here {}, whatcha wanna do?".format(User)) def takeCommand(): #It takes mocrophone input from user and returns string output r = sr.Recognizer() with sr.Microphone() as source: print("Listening...") r.pause_threshold = 1 audio = r.listen(source) if __name__ == "__main__": User=userInit() wishMe(User) a=input() sad=['Sad','sad','SAD'] sadbool=False for i in sad: if i in a: sadbool=True if sadbool: speak("Why are you sad? man") ''' # Author : -Pratyay- import sys,threading inp=sys.stdin.buffer.readline inar=lambda: list(map(int,inp().split())) inin=lambda: int(inp()) inst=lambda: inp().decode().rstrip('\n\r') # Am I debugging, check if I'm using same variable name in two places def centroid(g): n=len(g) centroid=[] size=[0 for i in range(n)] def dfs(node,par): size[node]=1 iscent=True for nei in g[node]: if nei!=par: dfs(nei,node) size[node]+=size[nei] if size[nei]> n//2: iscent=False if n-size[node]>n//2: iscent=False if iscent: centroid.append(node) dfs(0,-1) return centroid,size def main(): _T_=inin() for _t_ in range(_T_): n=inin() gr=[[] for i in range(n)] vis=[False for i in range(n)] for i in range(n-1): x,y=inar() x-=1 y-=1 gr[x].append(y) gr[y].append(x) cent,size=centroid(gr) if len(cent)==1: print(x+1,y+1) print(x+1,y+1) else: #print(size) opponent=-1 maxsize=-12 to_remove=-1 for node in cent: for nei in gr[node]: if size[nei]>maxsize and nei not in cent: maxsize=size[nei] opponent=node to_remove=nei if opponent==cent[0]: print(cent[0]+1,to_remove+1) print(cent[1]+1,to_remove+1) else: print(cent[1]+1,to_remove+1) print(cent[0]+1,to_remove+1) if (1): sys.setrecursionlimit(10**7) threading.stack_size(10**8) threading.Thread(target=main).start() else: main() ```
instruction
0
45,564
13
91,128
Yes
output
1
45,564
13
91,129
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` from collections import defaultdict import sys import threading ans = 1e5 def dfs1(i,p): c = 1 for j in tree[i]: if j!=p: c+= dfs1(j,i) dic[(p,i)]=c dic[(i,p)]=n-c return c def dfs2(i,p): global ans tmp = dic[(i,p)] for j in tree[i]: if j!=p: dfs2(j,i) tmp = max(tmp, dic[(i,j)]) ans = min(ans, tmp) def dfs3(i,p): tmp = dic[(i,p)] for j in tree[i]: if j!=p: dfs3(j,i) tmp = max(tmp, dic[(i,j)]) if ans == tmp: res.append(i) def solve(): global ans,tree,dic,n,res t = int(input()) for _ in range(t): n = int(input()) ans = 1e5 res = [] tree = [[] for _ in range(n+1)] dic = defaultdict() for _ in range(n-1): x,y = map(int, input().split()) tree[x].append(y) tree[y].append(x) dfs1(1,0) dfs2(1,0) dfs3(1,0) if len(res)==1: a = res[0] b = tree[a][0] print(a,b) print(a,b) else: a,b = res[0],res[1] c = 0 for j in tree[a]: if j!=b: c=j break print(a,c) print(b,c) res = [] tree = [] dic = [] n = 0 max_recur_size = 10**5*2 + 1000 max_stack_size = max_recur_size*500 sys.setrecursionlimit(max_recur_size) threading.stack_size(max_stack_size) thread = threading.Thread(target=solve) thread.start() ```
instruction
0
45,565
13
91,130
Yes
output
1
45,565
13
91,131
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` ###pyrival template for fast IO 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") t=int(input()) while t>0: t-=1 def graph_undirected(): n=int(input()) graph={} #####adjecancy list using dict for i in range(n-1): vertex,neighbour=[int(x) for x in input().split()] if vertex in graph: graph[vertex].append(neighbour) else: graph[vertex]=[neighbour] if neighbour in graph: #####for undirected part remove to get directed graph[neighbour].append(vertex) else: graph[neighbour]=[vertex] return graph,n graph,n=graph_undirected() dp=[[] for x in range(n+1)] ####store sizes of all sub graph for each articulation point ###### undirected def dfs(graph,n,currnode): visited=[False for x in range(n+1)] stack=[currnode] while stack: currnode=stack[-1] if visited[currnode]==False: visited[currnode]=True for neighbour in graph[currnode]: if visited[neighbour]==False: visited[neighbour]=True stack.append(neighbour) break #####if we remove break it becomes bfs else: if len(stack)>1: s=sum(dp[stack[-1]]) dp[stack[-1]].append(n-s-1) dp[stack[-2]].append(s+1);#print(stack[-2],stack[-1]) stack.pop() ####we are backtracking to previous node which is in our stack dfs(graph,n,1);ans=[] #print(dp) indexmin=[];valmin=float("inf") for i in range(1,n+1): m=max(dp[i]) if m<valmin: valmin=m indexmin.clear() indexmin.append(i) elif m==valmin: indexmin.append(i) if len(indexmin)==1: print(indexmin[0],graph[indexmin[0]][0]) print(indexmin[0],graph[indexmin[0]][0]) else: a,b=indexmin[0],indexmin[1] ans=None;val=float("inf") for neighbour in graph[a]: if neighbour!=b: m=max(dp[neighbour]) if m<val: val=m ans=neighbour print(a,ans) print(b,ans) ```
instruction
0
45,566
13
91,132
Yes
output
1
45,566
13
91,133
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` from random import choice as _choice import sys as _sys def main(): t = int(input()) for i in range(t): n, = _read_ints() graph = [set() for v in range(n)] for i_edge in range(n-1): v1, v2 = _read_ints() v1 -= 1 v2 -= 1 graph[v1].add(v2) graph[v2].add(v1) operations = find_operations_necessary_to_remain_one_centroid(graph) for v1, v2 in operations: print(v1+1, v2+1) def _read_line(): result = _sys.stdin.readline() assert result[-1] == "\n" return result[:-1] def _read_ints(): return map(int, _read_line().split(" ")) def find_operations_necessary_to_remain_one_centroid(graph): assert len(graph) > 2 graph = [set(neighbors) for neighbors in graph] centroids = find_centroids(graph) assert 0 < len(centroids) <= 2 if len(centroids) == 1: operation_remove = (0, 1) operation_add = (0, 1) else: assert len(centroids) == 2 centroid_1, centroid_2 = centroids graph[centroid_1].remove(centroid_2) graph[centroid_2].remove(centroid_1) centroid_1_component = _find_component(graph, centroid_1) centroid_2_component = list(_find_component(graph, centroid_2)) graph[centroid_1].add(centroid_2) graph[centroid_2].add(centroid_1) vertex_to_move = { leave for leave in centroid_1_component if len(graph[leave]) == 1 and leave != centroid_1 }.pop() vertex_to_move_parent = tuple(graph[vertex_to_move])[0] operation_remove = (vertex_to_move, vertex_to_move_parent) graph[vertex_to_move].remove(vertex_to_move_parent) graph[vertex_to_move_parent].remove(vertex_to_move) new_parent = _choice(centroid_2_component) graph[vertex_to_move].add(new_parent) graph[new_parent].add(vertex_to_move) while len(find_centroids(graph)) == 2: graph[vertex_to_move].remove(new_parent) graph[new_parent].remove(vertex_to_move) new_parent = _choice(centroid_2_component) graph[vertex_to_move].add(new_parent) graph[new_parent].add(vertex_to_move) operation_add = (vertex_to_move, new_parent) return operation_remove, operation_add def find_centroids(graph): vertices_n = len(graph) vertices_values = [None] * len(graph) leaves = [vertex for vertex in range(len(graph)) if len(graph[vertex]) == 1] vertices_accumulated = [None] * len(graph) for leave in leaves: vertices_accumulated[leave] = 1 neighbors = graph[leave] assert len(neighbors) == 1 vertices_values[leave] = vertices_n - 1 active = set().union(*(graph[leave] for leave in leaves)) passed = set(leaves) active -= passed while len(passed) < len(graph): old_active = active active = set() for vertex in old_active: neighbors = graph[vertex] neighbors_not_passed = neighbors - passed if len(neighbors_not_passed) > 1: active.add(vertex) continue vertices_accumulated[vertex] = sum( vertices_accumulated[neighbor] for neighbor in neighbors if neighbor in passed ) + 1 components_remain_sizes = [] for neighbor in neighbors - neighbors_not_passed: components_remain_sizes.append(vertices_accumulated[neighbor]) assert len(neighbors_not_passed) <= 1 for neighbor in neighbors_not_passed: components_remain_sizes.append(vertices_n - vertices_accumulated[vertex]) vertex_value = max(components_remain_sizes) vertices_values[vertex] = vertex_value passed.add(vertex) active.update(neighbors_not_passed) active = active - passed centroid_value = min(vertices_values) centroids = [vertex for vertex, value in enumerate(vertices_values) if value == centroid_value] return centroids def _find_component(graph, start_vertex): passed = set() active = {start_vertex} while active: old_active = active active = set() for vertex in old_active: passed.add(vertex) active |= graph[vertex] active = active - passed return passed if __name__ == '__main__': main() ```
instruction
0
45,567
13
91,134
No
output
1
45,567
13
91,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` import collections for t in range(int(input())): n=int(input()) val=0 k=collections.defaultdict(set) for i in range(n-1): u,v=map(int,input().split()) k[u].add(v) k[v].add(u) val=max(val,len(k[u]),len(k[v])) temp=set([]) for i in k: if len(k[i])==val: temp.add(i) if len(temp)==1: i=temp.pop() v=k[i].pop() print(i,v) print(i,v) elif len(temp)==2: v1=temp.pop() v2=temp.pop() if v1 in k[v2]: k[v2].remove(v1) k[v1].remove(v2) j=k[v1].pop() k[v1].add(j) for i in k[v1]: if i not in k[v2]: j=i break print(v1,j) print(v2,j) else: v1=temp.pop() for i in range(1,n+1): if i!=v1 and i not in k[v1]: x=k[i].pop() print(x,i) print(v1,i) break ```
instruction
0
45,568
13
91,136
No
output
1
45,568
13
91,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() def farthest(i): L = [-1] * N L[i] = 0 d = 0 post = [i] while len(post) > 0: d += 1 pre = post post = [] for j in pre: for k in X[j]: if L[k] < 0: L[k] = d post.append(k) return (pre[0], d-1, L) T = int(input()) for _ in range(T): N = int(input()) X = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) X[a-1].append(b-1) X[b-1].append(a-1) s, d1, l1 = farthest(0) t, d2, l2 = farthest(s) if d2 % 2 == 0: i = 0 j = X[i][0] print(i+1, j+1) print(i+1, j+1) continue elif d2 == N - 1: i = s j = X[s][0] print(i+1, j+1) for ii in range(N): if ii == i or ii == j or ii == t: continue print(i+1, ii+1) break else: u, d3, l3 = farthest(t) se = set([i for i, (a, b) in enumerate(zip(l2, l3)) if a + b == d2]) for i in range(N): if i not in se and len(X[i]) == 1: j = X[i][0] print(i+1, j+1) print(i+1, s+1) break ```
instruction
0
45,569
13
91,138
No
output
1
45,569
13
91,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fishing Prince loves trees, and he especially loves trees with only one centroid. The tree is a connected graph without cycles. A vertex is a centroid of a tree only when you cut this vertex (remove it and remove all edges from this vertex), the size of the largest connected component of the remaining graph is the smallest possible. For example, the centroid of the following tree is 2, because when you cut it, the size of the largest connected component of the remaining graph is 2 and it can't be smaller. <image> However, in some trees, there might be more than one centroid, for example: <image> Both vertex 1 and vertex 2 are centroids because the size of the largest connected component is 3 after cutting each of them. Now Fishing Prince has a tree. He should cut one edge of the tree (it means to remove the edge). After that, he should add one edge. The resulting graph after these two operations should be a tree. He can add the edge that he cut. He wants the centroid of the resulting tree to be unique. Help him and find any possible way to make the operations. It can be proved, that at least one such way always exists. Input The input consists of multiple test cases. The first line contains an integer t (1≤ t≤ 10^4) — the number of test cases. The description of the test cases follows. The first line of each test case contains an integer n (3≤ n≤ 10^5) — the number of vertices. Each of the next n-1 lines contains two integers x, y (1≤ x,y≤ n). It means, that there exists an edge connecting vertices x and y. It's guaranteed that the given graph is a tree. It's guaranteed that the sum of n for all test cases does not exceed 10^5. Output For each test case, print two lines. In the first line print two integers x_1, y_1 (1 ≤ x_1, y_1 ≤ n), which means you cut the edge between vertices x_1 and y_1. There should exist edge connecting vertices x_1 and y_1. In the second line print two integers x_2, y_2 (1 ≤ x_2, y_2 ≤ n), which means you add the edge between vertices x_2 and y_2. The graph after these two operations should be a tree. If there are multiple solutions you can print any. Example Input 2 5 1 2 1 3 2 4 2 5 6 1 2 1 3 1 4 2 5 2 6 Output 1 2 1 2 1 3 2 3 Note Note that you can add the same edge that you cut. In the first test case, after cutting and adding the same edge, the vertex 2 is still the only centroid. In the second test case, the vertex 2 becomes the only centroid after cutting the edge between vertices 1 and 3 and adding the edge between vertices 2 and 3. Submitted Solution: ``` import sys sys.setrecursionlimit(10**5) int1 = lambda x: int(x)-1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def MI1(): return map(int1, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] for _ in range(II()): def centroid(u=0, pu=-1): res = [] is_centroid = True u_nodes = 1 for cu in to[u]: if cu == pu: continue pp[cu]=u res += centroid(cu, u) cu_nodes = n_nodes[cu] if cu_nodes > n/2: is_centroid = False u_nodes += cu_nodes n_nodes[u] = u_nodes if n-u_nodes > n/2: is_centroid = False if is_centroid: res.append(u) return res n=II() to=[[] for _ in range(n)] for _ in range(n-1): u,v=MI1() to[u].append(v) to[v].append(u) n_nodes = [0]*n pp=[-1]*n uu=centroid() # print(uu) # print(n_nodes) if len(uu)==1: print(1,to[0][0]+1) print(1,to[0][0]+1) else: u,v=uu for w in to[u]: if w!=v: print(u+1,w+1) print(v+1,w+1) ```
instruction
0
45,570
13
91,140
No
output
1
45,570
13
91,141
Provide tags and a correct Python 2 solution for this coding contest problem. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>.
instruction
0
45,742
13
91,484
Tags: dp, sortings Correct Solution: ``` from sys import stdin, stdout from collections import Counter, defaultdict raw_input = stdin.readline pr = stdout.write mod=10**9+7 def ni(): return int(raw_input()) def li(): return map(int,raw_input().split()) def pn(n): stdout.write(str(n)+'\n') def pa(arr): pr(' '.join(map(str,arr))+'\n') # fast read function for total integer input def inp(): # this function returns whole input of # space/line seperated integers # Use Ctrl+D to flush stdin. return map(int,stdin.read().split()) range = xrange # not for python 3.0+ # main code n,m=li() d=defaultdict(list) for i in range(m): u,v,w=li() d[w].append((u,v)) dp=[0]*(n+1) for i in sorted(d): temp=[(v,dp[u]) for u,v in d[i]] for v,tp in temp: dp[v]=max(dp[v],tp+1) pn(max(dp)) ```
output
1
45,742
13
91,485
Provide tags and a correct Python 3 solution for this coding contest problem. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>.
instruction
0
45,743
13
91,486
Tags: dp, sortings Correct Solution: ``` from sys import * f = list(map(int, stdin.read().split())) n, m = f[0], f[1] d = [[] for i in range(100001)] for j in range(2, len(f), 3): x, y, w = f[j:j + 3] d[w].append((y, x)) s = [0] * (n + 1) for q in d: for y, k in [(y, s[x]) for y, x in q]: s[y] = max(s[y], k + 1) print(max(s)) ```
output
1
45,743
13
91,487
Provide tags and a correct Python 3 solution for this coding contest problem. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>.
instruction
0
45,744
13
91,488
Tags: dp, sortings Correct Solution: ``` from sys import * a = list(map(int, stdin.read().split())) n = a[0] m = a[1] inf = 10**5 + 1 g = [[] for i in range(inf)] for i in range(2, len(a), 3): b, c, w = a[i:i + 3] g[w].append((c, b)) n += 1 s = [0] * n for l in g: for i, k in [(i, s[j]) for i, j in l]: s[i] = max(s[i], k + 1) print(max(s)) ```
output
1
45,744
13
91,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>. Submitted Solution: ``` from sys import * f = lambda: map(int, stdin.readline().split()) n, m = f() d = [{} for i in range(100001)] for j in range(m): x, y, w = f() if y in d[w]: d[w][y].append(x) else: d[w][y] = [x] s = [0] * (n + 1) for q in d: for y, t in q.items(): k = max(s[x] for x in t) s[y] = max(s[y], k + 1) print(max(s)) ```
instruction
0
45,745
13
91,490
No
output
1
45,745
13
91,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>. Submitted Solution: ``` N = 300005 n, m = [int(x) for x in input().split()] wt = [[] for i in range(N)] arr = [0 for i in range(N)] dp = arr[:] for i in range(m): u, v, w = [int(x) for x in input().split()] wt[w].append([u, v]) for i in range(1, N): for j in wt[i]: arr[j[1]] = dp[j[0]] + 1 #print(arr[:10], "for", wt[i]) for j in wt[i]: dp[j[1]] = max(dp[j[1]], arr[j[1]]) #print("dp hai", dp[:10]) print(max(dp)) ```
instruction
0
45,746
13
91,492
No
output
1
45,746
13
91,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>. Submitted Solution: ``` class Solution(): def max_path(n, m, edges): edges = sorted(edges, reverse=True) pathlen = [0]*n lastpath = [0]*n lastweight = [-1]*n for w, u, v in edges: nextpath = lastpath[v] if lastweight[v] == w else pathlen[v] if lastweight[u] == w: pathlen[u] = max(pathlen[u], 1+nextpath) else: lastpath[u] = pathlen[u] lastweight[u] = w pathlen[u] = 1+nextpath return max(pathlen) n, m = list(map(int, input().strip(' ').split(' '))) edges = [] for i in range(m): u,v,w = list(map(int, input().strip(' ').split(' '))) edges.append((w,u-1,v-1)) print(Solution.max_path(n,m,edges)) ```
instruction
0
45,747
13
91,494
No
output
1
45,747
13
91,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Pashmak's homework is a problem about graphs. Although he always tries to do his homework completely, he can't solve this problem. As you know, he's really weak at graph theory; so try to help him in solving the problem. You are given a weighted directed graph with n vertices and m edges. You need to find a path (perhaps, non-simple) with maximum number of edges, such that the weights of the edges increase along the path. In other words, each edge of the path must have strictly greater weight than the previous edge in the path. Help Pashmak, print the number of edges in the required path. Input The first line contains two integers n, m (2 ≤ n ≤ 3·105; 1 ≤ m ≤ min(n·(n - 1), 3·105)). Then, m lines follows. The i-th line contains three space separated integers: ui, vi, wi (1 ≤ ui, vi ≤ n; 1 ≤ wi ≤ 105) which indicates that there's a directed edge with weight wi from vertex ui to vertex vi. It's guaranteed that the graph doesn't contain self-loops and multiple edges. Output Print a single integer — the answer to the problem. Examples Input 3 3 1 2 1 2 3 1 3 1 1 Output 1 Input 3 3 1 2 1 2 3 2 3 1 3 Output 3 Input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 Output 6 Note In the first sample the maximum trail can be any of this trails: <image>. In the second sample the maximum trail is <image>. In the third sample the maximum trail is <image>. Submitted Solution: ``` '''input 6 7 1 2 1 3 2 5 2 4 2 2 5 2 2 6 9 5 4 3 4 3 4 ''' from sys import stdin from collections import defaultdict def dfs(graph, dp, source, mx_w = 0): # print(dp) mx = 0 if dp[source] != 0: if graph[source][0][1] > mx_w: return dp[source] else: return 0 for i in (graph[source]): if i[1] > mx_w: mx = max(mx,1 + dfs(graph, dp, i[0], i[1]) ) else: continue dp[source] = max(dp[source], mx) return dp[source] # main starts n, m = list(map(int, stdin.readline().split())) edges = [] for _ in range(m): edges.append(list(map(int, stdin.readline().split()))) edges = sorted(edges, key = lambda x : x[2]) graph = defaultdict(list) dp = dict() for i in range(1, n + 1): graph[i] dp[i] = 0 for i in range(m): graph[edges[i][0]].append([edges[i][1], edges[i][2]]) #print(graph) maxi = -float('inf') for i in graph: maxi = max(maxi, dfs(graph, dp, i)) print(maxi) ```
instruction
0
45,748
13
91,496
No
output
1
45,748
13
91,497
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,960
13
91,920
"Correct Solution: ``` from collections import defaultdict import sys input = sys.stdin.readline N, M = map(int, input().split()) bxs = list(map(int, input().split())) xs = bxs[:] dd = defaultdict(set) for i, x in enumerate(xs): dd[x].add(i+1) xs = list(set(xs)) xs.sort() #for x, i in xs: G = [set() for _ in range(N+1)] G2 = [set() for _ in range(N+1)] es = [] for i in range(M): u, v = map(int, input().split()) if bxs[u-1] == bxs[v-1]: G2[v].add(u) G2[u].add(v) elif bxs[u-1] > bxs[v-1]: G[u].add(v) else: G[v].add(u) e = (min(u,v), max(u,v)) es.append(e) r = True d = dict() cc = [-1 for _ in range(N+1)] for i in range(N): if len(G[i+1]) + len(G2[i+1]) == 0: print(-1) sys.exit() for x in xs: for u in dd[x]: if cc[u] != -1: continue if not G2[u]: continue cc[u] = 1 stack = [u] while stack: q = stack.pop() for c in G2[q]: e = (min(q,c), max(q,c)) if e in d: continue d[e] = x if cc[c] != -1: continue stack.append(c) cc[c] = 1 - cc[q] for x in xs: for i in dd[x]: for c in G[i]: e = (min(i,c), max(i,c)) d[e] = bxs[i-1] if cc[i] == -1: cc[i] = 1 - cc[c] for i in range(1, N+1): print("B"if cc[i] else "W", end="") print() for i in range(M): print(d[es[i]]) ```
output
1
45,960
13
91,921
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,961
13
91,922
"Correct Solution: ``` import sys N, M = map(int, input().split()) D = list(map(int, input().split())) DI = list(zip(D, list(range(N)))) G = [[] for _ in range(N)] for i in range(M): u, v = map(int, input().split()) G[u-1].append((v-1, i)) G[v-1].append((u-1, i)) DI.sort() V = [-1]*N j = 0 used = [False]*N ans = [10**9]*M BW = ['']*N for j in range(N): d, v = DI[j] if used[v]: continue for nv, i in G[v]: if d == D[nv]: if BW[nv] == '': BW[nv] = 'B' BW[v] = 'W' ans[i] = d used[v] = True used[nv] = True elif BW[nv] == 'W': BW[v] = 'B' ans[i] = d used[v] = True else: BW[v] = 'W' ans[i] = d used[v] = True break elif used[nv]: if BW[nv] == 'B': BW[v] = 'B' ans[i] = d-D[nv] used[v] = True else: BW[v] = 'W' ans[i] = d-D[nv] used[v] = True break if not used[v]: print(-1) sys.exit() print(*BW, sep = '') print(*ans, sep = '\n') ```
output
1
45,961
13
91,923
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,962
13
91,924
"Correct Solution: ``` import os import sys if os.getenv("LOCAL"): sys.stdin = open("_in.txt", "r") sys.setrecursionlimit(10 ** 9) INF = float("inf") IINF = 10 ** 18 MOD = 10 ** 9 + 7 # MOD = 998244353 def argsort(li, key=None, reverse=False): return [i for _, i in sorted( [(a, i) for i, a in enumerate(li)], key=(lambda t: key(t[0])) if key else None, reverse=reverse )] N, M = list(map(int, sys.stdin.buffer.readline().split())) D = list(map(int, sys.stdin.buffer.readline().split())) VU = [list(map(int, sys.stdin.buffer.readline().split())) for _ in range(M)] graph = [[] for _ in range(N)] for i, (v, u) in enumerate(VU): v -= 1 u -= 1 graph[v].append(u) graph[u].append(v) edges = {} colors = [None] * N for v in argsort(D): d = D[v] if colors[v] is not None: continue for u in graph[v]: if colors[u] is not None: edges[v, u] = d colors[v] = not colors[u] break if D[u] == d: edges[v, u] = d colors[v] = True colors[u] = False break if colors[u] is None: print(-1) exit() S = '' for c in colors: S += 'B' if c else 'W' ans = [] for v, u in VU: v -= 1 u -= 1 if (v, u) in edges: ans.append(edges[v, u]) elif (u, v) in edges: ans.append(edges[u, v]) else: ans.append(10 ** 9) print(S) print(*ans, sep='\n') ```
output
1
45,962
13
91,925
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,963
13
91,926
"Correct Solution: ``` import sys input = sys.stdin.readline N, M = map(int, input().split()) xs = list(map(int, input().split())) G = [set() for _ in range(N)] for i in range(M): u, v = sorted(map(int, input().split()),key=lambda x:[xs[x-1],-x]) G[v-1].add((u-1,i)) xs,d,cc = sorted([(x,i) for i, x in enumerate(xs)]),[0]*M,[-1]*N for x, u in xs: if cc[u]+1:continue if not G[u]:break cc[u] = 1 for c, _ in G[u]: if cc[c]+1: cc[u] = 1-cc[c] S = [u] while S: q = S.pop() for c, i in G[q]: d[i] = str(x) if cc[c]+1:continue S.append(c) cc[c] = 1-cc[q] print("".join("BW"[i] for i in cc)+"\n"+"\n".join(d) if cc[u]+1 else -1) ```
output
1
45,963
13
91,927
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,964
13
91,928
"Correct Solution: ``` """ 明らかに無理→最小が2つ無い or 最小同士がペアになってない (最小から接続する頂点に最小がない) 満たしてる→最小の辺を置いちゃおう 小さい奴からGreedyに置いてく? 自分の周りにendしてるやつ or 大きさが同じやつがあったら繋げちゃう そのとき白黒はどうでも良さそう? """ import sys N,M = map(int,input().split()) D = list(map(int,input().split())) dic2 = [[] for i in range(N)] for i in range(M): U,V = map(int,input().split()) U -= 1 V -= 1 if len(dic2[U]) == 0 or dic2[U][0][0] > D[V]: dic2[U] = [] dic2[U].append([D[V],V,i]) if len(dic2[V]) == 0 or dic2[V][0][0] > D[U]: dic2[V] = [] dic2[V].append([D[U],U,i]) dic = [[] for i in range(N)] for i in range(N): for j in dic2[i]: dic[i].append([j[1],j[2]]) #print (dic) end = [False] * N color = [0] * N q = [] ans = [10**9] * M for i in range(N): q.append([D[i],i]) q.sort() #print (q) for i in range(N): if end[q[i][1]]: continue flag = False for vi in dic[q[i][1]]: nexv = vi[0] mind = vi[1] nowd = q[i][0] nowp = q[i][1] #print (vi,q[i]) if end[nexv]: flag = True color[nowp] = color[nexv] ^ 1 end[nowp] = True ans[mind] = nowd break elif D[nexv] == nowd: flag = True color[nowp] = color[nexv] ^ 1 end[nowp] = True end[nexv] = True ans[mind] = nowd break break #print (ans) if not flag: print (-1) sys.exit() S = [] for i in color: if i == 0: S.append("B") else: S.append("W") print ("".join(S)) print (" ".join(map(str,ans))) ```
output
1
45,964
13
91,929
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,965
13
91,930
"Correct Solution: ``` import sys from operator import itemgetter def solve(n, m, ddd, links): ddi = list(enumerate(ddd)) ddi.sort(key=itemgetter(1)) LIMIT = 10 ** 9 + 1 costs = [LIMIT] * m for v, dv in ddi: du, li, u = min(links[v]) if du > dv: print(-1) return costs[li] = dv colors = [-1] * n for i in range(n): q = [(i, 0)] while q: v, color = q.pop() if colors[v] != -1: continue colors[v] = color for du, li, u in links[v]: if costs[li] == LIMIT: continue q.append((u, color ^ 1)) MAX = 10 ** 9 costs = [MAX if cost == LIMIT else cost for cost in costs] print(''.join('BW'[c] for c in colors)) print('\n'.join(map(str, costs))) n, m = map(int, input().split()) ddd = list(map(int, input().split())) links = [[] for _ in range(n)] for li, line in enumerate(sys.stdin): u, v = map(int, line.split()) u -= 1 v -= 1 links[u].append((ddd[v], li, v)) links[v].append((ddd[u], li, u)) solve(n, m, ddd, links) ```
output
1
45,965
13
91,931
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,966
13
91,932
"Correct Solution: ``` import sys input = sys.stdin.readline N, M = map(int, input().split()) xs = list(map(int, input().split())) G = [set() for _ in range(N+1)] es = [] for i in range(M): u, v = sorted(map(int, input().split())) if xs[u-1] == xs[v-1]: G[v].add(u) G[u].add(v) elif xs[u-1] > xs[v-1]: G[u].add(v) else: G[v].add(u) es.append((u,v)) xs,d,cc = sorted([(x,i+1) for i, x in enumerate(xs)]),{},{} for i in range(N): if not G[i+1]: print(-1) sys.exit() for x, u in xs: if u in cc: continue cc[u] = 1 for c in G[u]: if c in cc: cc[u] = 1-cc[c] S = [u] while S: q = S.pop() for c in G[q]: d[tuple(sorted([q,c]))] = x if c in cc: continue S.append(c) cc[c] = 1-cc[q] print("".join("BW"[cc[i]] for i in range(1,N+1))) for i in range(M): print(d[es[i]]) ```
output
1
45,966
13
91,933
Provide a correct Python 3 solution for this coding contest problem. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1
instruction
0
45,967
13
91,934
"Correct Solution: ``` import sys input = sys.stdin.readline N, M = map(int, input().split()) xs = list(map(int, input().split())) G = [set() for _ in range(N+1)] es = [] for i in range(M): u, v = map(int, input().split()) if xs[u-1] == xs[v-1]: G[v].add(u) G[u].add(v) elif xs[u-1] > xs[v-1]: G[u].add(v) else: G[v].add(u) e = (min(u,v), max(u,v)) es.append(e) xs = sorted([(x,i+1) for i, x in enumerate(xs)]) d = dict() cc = dict() for i in range(N): if not G[i+1]: print(-1) sys.exit() for x, u in xs: if u in cc: continue cc[u] = 1 for c in G[u]: if c in cc: cc[u] = 1-cc[c] stack = [u] while stack: q = stack.pop() for c in G[q]: e = (min(q,c), max(q,c)) d[e] = x if c in cc: continue stack.append(c) cc[c] = 1 - cc[q] print("".join("BW"[cc[i]] for i in range(1,N+1))) for i in range(M): print(d[es[i]]) ```
output
1
45,967
13
91,935
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` # coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline read = sys.stdin.read class UnionFind: def __init__(self, n): self.parent = list(range(n)) #親ノード self.size = [1]*n #グループの要素数 def root(self, x): #root(x): xの根ノードを返す. while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる x, y = self.root(x), self.root(y) if x == y: return False if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように self.size[x] += self.size[y] #xの要素数を更新 self.parent[y] = x #yをxにつなぐ return True def issame(self, x, y): #same(x,y): xとyが同じ組ならTrue return self.root(x) == self.root(y) def getsize(self,x): #size(x): xのいるグループの要素数を返す return self.size[self.root(x)] #n = int(input) #h,w = [int(i) for i in readline().split()] #n,k,s = [int(i) for i in read().split()] #n = int(input()) #a = [int(i)-1 for i in readline().split()] n,m = [int(i) for i in readline().split()] d = [int(i) for i in readline().split()] g = [[] for _ in range(n)] a = map(int,read().split()) INF = 10**9 #edges = [] for i,(u,v) in enumerate(zip(a,a)): u -= 1; v -= 1 g[u].append((v,i)) g[v].append((u,i)) #edges.append((u,v)) ans = [INF]*m dd = [(c,i) for i,c in enumerate(d)] dd.sort() UF = UnionFind(2*n) def ng(): print(-1) exit() for c,idx in dd: conn = 0 notconn = [] for (v,i) in g[idx]: if d[v] <= c: UF.merge(v,idx+n) UF.merge(v+n,idx) ans[i] = c break else: ng() s = [] good = set() bad = set() for i in range(n): p = UF.root(i) if p in bad: s.append("B") elif p in good: s.append("W") else: s.append("W") good.add(p) bad.add(UF.root(i+n)) print("".join(s)) print(*ans,sep="\n") ```
instruction
0
45,968
13
91,936
Yes
output
1
45,968
13
91,937
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` import sys readline = sys.stdin.readline N, M = map(int, readline().split()) D = list(map(int, readline().split())) Edge = [[] for _ in range(N)] for i in range(M): u, v = map(int, readline().split()) u -= 1 v -= 1 Edge[u].append((D[v], i, v)) Edge[v].append((D[u], i, u)) inf = 10**9+7 table = [inf]*M Col = [None]*N def solve(): Di = sorted([(D[i], i) for i in range(N)]) for dvn, vn in Di: dvf, enum, vf = min(Edge[vn]) if dvn < dvf: return False table[enum] = dvn used = set() for i in range(N): if i in used: continue Col[i] = 1 stack = [i] while stack: vn = stack.pop() for _, enum, vf in Edge[vn]: if table[enum] == inf: continue if vf in used: continue Col[vf] = not Col[vn] used.add(vf) stack.append(vf) for i in range(M): if table[i] == inf: table[i] = 10**9 return True if not solve(): print(-1) else: print(''.join(['B' if Col[i] else 'W' for i in range(N)])) print('\n'.join(map(str, table))) ```
instruction
0
45,969
13
91,938
Yes
output
1
45,969
13
91,939
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` from collections import defaultdict import sys sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def MI1(): return map(int1, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] def main(): def impossible(): for u in range(n): du = dd[u] for v in to[u]: if dd[v] <= du: break else: return True return False def dfs(u=0,pu=-1,c=0): color[u]="B" if c else "W" for v in to2[u]: if v==pu:continue dfs(v,u,1-c) inf = 10 ** 9 n, m = MI() dd = LI() to = defaultdict(list) uvtoi = {} for i in range(m): u, v = MI1() uvtoi[u, v] = uvtoi[v, u] = i to[u].append(v) to[v].append(u) if impossible(): print(-1) exit() cost = [inf] * m to2 = defaultdict(set) for u in range(n): mn = (inf, inf, inf) for v in to[u]: t = (dd[v], uvtoi[u, v], v) if t < mn: mn = t v = mn[2] cost[mn[1]] = dd[u] to2[u].add(v) to2[v].add(u) color=["N"]*n for u in range(n): if color[u]!="N":continue dfs(u) print("".join(color)) print(*cost,sep="\n") main() ```
instruction
0
45,970
13
91,940
Yes
output
1
45,970
13
91,941
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` import sys I = sys.stdin.readline N, M = map(int, I().split()) X = list(map(int, I().split())) G = [set() for _ in range(N)] for i in range(M): u, v = sorted(map(int, I().split()),key=lambda x:[X[x-1],-x]) G[v-1].add((u-1,i)) X,d,C = sorted([(x,i) for i, x in enumerate(X)]),[0]*M,[0]*N for x, u in X: if C[u]:continue if not G[u]:break C[u],S=-1 if sum(C[c]+1 for c, _ in G[u])else 1,[u] while S: q = S.pop() for c, i in G[q]: d[i]=str(x) if C[c]:continue S+=[c] C[c]=-C[q] print("".join(" BW"[i] for i in C)+"\n"+"\n".join(d) if C[u]else -1) ```
instruction
0
45,971
13
91,942
Yes
output
1
45,971
13
91,943
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` def main(): import sys input = sys.stdin.readline # MAX = 10 ** 9 N, M = map(int, input().split()) D = list(map(int, input().split())) v_color = [-1] * N check = [1] * N #0のとき条件を満たしているとする G = [[] for _ in range(N)] for i in range(M): U, V = map(int, input().split()) U -= 1 V -= 1 G[U].append([V, i]) G[V].append([U, i]) #ここまで入力 v_color[0] = 1 #最初の頂点を白色(1)にする stack = [0] #スタートする点 深さ優先探索で調べる weight = [-1] * M while stack: tmp = stack.pop() tmp_color = v_color[tmp] for lst in G[tmp]: next_ = lst[0] i = lst[1] if v_color[next_] == -1: #初めて訪れるとき #違う色にする if D[tmp] == D[next_]: #距離が同じなら両方OKにする check[tmp] = 0 check[next_] = 0 elif D[tmp] < D[next_]: check[next_] = 0 else: check[tmp] = 0 stack.append(next_) v_color[next_] = 1 - tmp_color weight[i] = max(D[tmp], D[next_]) else: if tmp_color == v_color[next_]: #同じ色のとき #回り道してOkできるようにしておく weight[i] = max(abs(D[tmp] - D[next_]), 1) if D[tmp] < D[next_] and check[tmp] == 0: check[next_] = 0 elif D[next_] < D[tmp] and check[next_] == 0: check[tmp] = 0 else: if D[tmp] >= D[next_]: check[tmp] = 0 if D[tmp] <= D[next_]: check[next_] = 0 weight[i] = max(D[tmp], D[next_]) # print (v_color) # print (weight) # print (check) if max(check) == 1: print (-1) exit() for i in v_color: if i: print ('W', end = '') else: print ('B', end = '') print () print (*weight, sep = '\n') if __name__ == '__main__': main() ```
instruction
0
45,972
13
91,944
No
output
1
45,972
13
91,945
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` """ 明らかに無理→最小が2つ無い or 最小同士がペアになってない (最小から接続する頂点に最小がない) 満たしてる→最小の辺を置いちゃおう 小さい奴からGreedyに置いてく? 自分の周りにendしてるやつ or 大きさが同じやつがあったら繋げちゃう そのとき白黒はどうでも良さそう? """ import sys N,M = map(int,input().split()) D = list(map(int,input().split())) dic = {} for i in range(M): U,V = map(int,input().split()) U -= 1 V -= 1 if U not in dic: dic[U] = [] if V not in dic: dic[V] = [] dic[U].append([V,i]) dic[V].append([U,i]) end = [False] * N color = [0] * N q = [] ans = [10**9] * M for i in range(N): q.append([D[i],i]) q.sort() #print (q) for i in range(N): if end[q[i][1]]: continue flag = False for vi in dic[q[i][1]]: nexv = vi[0] mind = vi[1] nowd = q[i][0] nowp = q[i][1] #print (vi,q[i]) if end[nexv]: flag = True color[nowp] = color[nexv] ^ 1 end[nowp] = True ans[mind] = nowd break elif D[nexv] == nowd: flag = True color[nowp] = color[nexv] ^ 1 end[nowp] = True end[nexv] = True ans[mind] = nowd break #print (ans) if not flag: print (-1) sys.exit() S = "" for i in color: if i == 0: S += "B" else: S += "W" print (S) print (" ".join(map(str,ans))) ```
instruction
0
45,973
13
91,946
No
output
1
45,973
13
91,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` # coding: utf-8 # Your code here! import sys sys.setrecursionlimit(10**6) readline = sys.stdin.readline read = sys.stdin.read class UnionFind: def __init__(self, n): self.parent = list(range(n)) #親ノード self.size = [1]*n #グループの要素数 def root(self, x): #root(x): xの根ノードを返す. while self.parent[x] != x: self.parent[x] = self.parent[self.parent[x]] x = self.parent[x] return x def merge(self, x, y): #merge(x,y): xのいる組とyのいる組をまとめる x, y = self.root(x), self.root(y) if x == y: return False if self.size[x] < self.size[y]: x,y=y,x #xの要素数が大きいように self.size[x] += self.size[y] #xの要素数を更新 self.parent[y] = x #yをxにつなぐ return True def issame(self, x, y): #same(x,y): xとyが同じ組ならTrue return self.root(x) == self.root(y) def getsize(self,x): #size(x): xのいるグループの要素数を返す return self.size[self.root(x)] #n = int(input) #h,w = [int(i) for i in readline().split()] #n,k,s = [int(i) for i in read().split()] #n = int(input()) #a = [int(i)-1 for i in readline().split()] n,m = [int(i) for i in readline().split()] d = [int(i) for i in readline().split()] g = [[] for _ in range(n)] a = map(int,read().split()) INF = 10**9 #edges = [] for i,(u,v) in enumerate(zip(a,a)): u -= 1; v -= 1 g[u].append((v,i)) g[v].append((u,i)) #edges.append((u,v)) ans = [INF]*m dd = [(c,i) for i,c in enumerate(d)] dd.sort() UF = UnionFind(2*n) for c,idx in dd: for (v,i) in g[idx]: if d[v] <= c: UF.merge(v,idx+n) UF.merge(v+n,idx) ans[i] = c break else: print(-1) exit() s = [] for i in range(2*n): if UF.issame(0,i): if i < n: s.append("W") else: s.append("B") print("".join(s)) print(*ans,sep="\n") ```
instruction
0
45,974
13
91,948
No
output
1
45,974
13
91,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a connected undirected graph with N vertices and M edges. Edge i in this graph (1 \leq i \leq M) connects Vertex U_i and Vertex V_i bidirectionally. We are additionally given N integers D_1, D_2, ..., D_N. Determine whether the conditions below can be satisfied by assigning a color - white or black - to each vertex and an integer weight between 1 and 10^9 (inclusive) to each edge in this graph. If the answer is yes, find one such assignment of colors and integers, too. * There is at least one vertex assigned white and at least one vertex assigned black. * For each vertex v (1 \leq v \leq N), the following holds. * The minimum cost to travel from Vertex v to a vertex whose color assigned is different from that of Vertex v by traversing the edges is equal to D_v. Here, the cost of traversing the edges is the sum of the weights of the edges traversed. Constraints * 2 \leq N \leq 100,000 * 1 \leq M \leq 200,000 * 1 \leq D_i \leq 10^9 * 1 \leq U_i, V_i \leq N * The given graph is connected and has no self-loops or multiple edges. * All values in input are integers. Input Input is given from Standard Input in the following format: N M D_1 D_2 ... D_N U_1 V_1 U_2 V_2 \vdots U_M V_M Output If there is no assignment satisfying the conditions, print a single line containing `-1`. If such an assignment exists, print one such assignment in the following format: S C_1 C_2 \vdots C_M Here, * the first line should contain the string S of length N. Its i-th character (1 \leq i \leq N) should be `W` if Vertex i is assigned white and `B` if it is assigned black. * The (i + 1)-th line (1 \leq i \leq M) should contain the integer weight C_i assigned to Edge i. Examples Input 5 5 3 4 3 5 7 1 2 1 3 3 2 4 2 4 5 Output BWWBB 4 3 1 5 2 Input 5 7 1 2 3 4 5 1 2 1 3 1 4 2 3 2 5 3 5 4 5 Output -1 Input 4 6 1 1 1 1 1 2 1 3 1 4 2 3 2 4 3 4 Output BBBW 1 1 1 2 1 1 Submitted Solution: ``` N, M = list(map(int, input().split())) D = list(map(int, input().split())) UB = [list(map(int, input().split())) for _ in range(M)] R = {} for i in range(M): a, b = UB[i] a -= 1 b -= 1 if a not in R: R[a] = [[b, i]] else: R[a].append([b, i]) if b not in R: R[b] = [[a, i]] else: R[b].append([a, i]) DD = [[0] * 2 for _ in range(N)] for i in range(N): DD[i][0] = D[i] DD[i][1] = i DD.sort() L = [0] * N H = [0] * M LL = [-1] * N for i in range(N): h, x = DD[i] if x >= N: exit() if L[x] == 0: if LL[x] == -1: for n, m in R[x]: LL[n] = x if D[n] == D[x] or L[n] != 0: H[m] = h if L[n] == 1: L[n] = 1 L[x] = 2 else: L[n] = 2 L[x] = 1 break else: print(-1) exit() else: n, m = R[x][LL[x]] H[m] = h if L[n] == 1: L[n] = 1 L[x] = 2 else: L[n] = 2 L[x] = 1 t = "" for i in range(N): if L[i] == 1: t += "B" else: t += "W" print(t) for i in range(M): if H[i] == 0: print(10 ** 9) else: print(H[i]) ```
instruction
0
45,975
13
91,950
No
output
1
45,975
13
91,951
Provide a correct Python 3 solution for this coding contest problem. Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, each node i having a Fibonacci label F[i] = (f(i) mod N) assigned for i = 1,..., V ≤ N. If |F(i) - F(j)| < d, then the nodes i and j are connected. Given V and d, how many connected subsets of nodes will you obtain? <image> Figure 1: There are 4 connected subsets for V = 20 and d = 100. Constraints * 1 ≤ V ≤ 1000 * 1 ≤ d ≤ 150 Input Each data set is defined as one line with two integers as follows: Line 1: Number of nodes V and the distance d. Input includes several data sets (i.e., several lines). The number of dat sets is less than or equal to 50. Output Output line contains one integer - the number of connected subsets - for each input line. Example Input 5 5 50 1 13 13 Output 2 50 8
instruction
0
46,115
13
92,230
"Correct Solution: ``` from collections import deque try: while 1: V, d = map(int, input().split()) F = [0]*V a = b = 1 for v in range(V): a, b = (a+b) % 1001, a F[v] = a G = [[] for i in range(V)] for i in range(V): for j in range(i+1, V): if abs(F[i] - F[j]) < d: G[i].append(j) G[j].append(i) L = [0]*V ans = 0 for i in range(V): if L[i]: continue ans += 1 que = deque([i]) L[i] = 1 while que: v = que.popleft() for w in G[v]: if L[w]: continue que.append(w) L[w] = 1 print(ans) except: ... ```
output
1
46,115
13
92,231
Provide a correct Python 3 solution for this coding contest problem. Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, each node i having a Fibonacci label F[i] = (f(i) mod N) assigned for i = 1,..., V ≤ N. If |F(i) - F(j)| < d, then the nodes i and j are connected. Given V and d, how many connected subsets of nodes will you obtain? <image> Figure 1: There are 4 connected subsets for V = 20 and d = 100. Constraints * 1 ≤ V ≤ 1000 * 1 ≤ d ≤ 150 Input Each data set is defined as one line with two integers as follows: Line 1: Number of nodes V and the distance d. Input includes several data sets (i.e., several lines). The number of dat sets is less than or equal to 50. Output Output line contains one integer - the number of connected subsets - for each input line. Example Input 5 5 50 1 13 13 Output 2 50 8
instruction
0
46,116
13
92,232
"Correct Solution: ``` def initSets(N): return [ x for x in range(N) ] def getRoot(arr, n): while arr[n] != n: arr[n] = arr[arr[n]] n = arr[n] return n def union(arr, n, m): a = getRoot(arr, n) b = getRoot(arr, m) if a != b: arr[a] = b def isSameSet(arr, n, m): return getRoot(arr, n) == getRoot(arr, m) def getFibs(): fibs = [] a = 1 b = 1 while len(fibs) < 1000: c = (a + b) % 1001 a = b b = c fibs.append(c) return fibs if __name__ == '__main__': try: FIBS = getFibs() while True: V, d = list(map(int, input().strip().split())) fibs = FIBS[:V] arr = initSets(V) for i in range(V): for j in range(i + 1, V): if abs(fibs[i] - fibs[j]) < d: union(arr, i, j) subsets = {} for i in range(V): root = getRoot(arr, i) if root in subsets: subsets[root].append(fibs[i]) else: subsets[root] = [fibs[i]] print(len(subsets)) except EOFError: pass ```
output
1
46,116
13
92,233
Provide a correct Python 3 solution for this coding contest problem. Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, each node i having a Fibonacci label F[i] = (f(i) mod N) assigned for i = 1,..., V ≤ N. If |F(i) - F(j)| < d, then the nodes i and j are connected. Given V and d, how many connected subsets of nodes will you obtain? <image> Figure 1: There are 4 connected subsets for V = 20 and d = 100. Constraints * 1 ≤ V ≤ 1000 * 1 ≤ d ≤ 150 Input Each data set is defined as one line with two integers as follows: Line 1: Number of nodes V and the distance d. Input includes several data sets (i.e., several lines). The number of dat sets is less than or equal to 50. Output Output line contains one integer - the number of connected subsets - for each input line. Example Input 5 5 50 1 13 13 Output 2 50 8
instruction
0
46,117
13
92,234
"Correct Solution: ``` import sys sys.setrecursionlimit(10000000) MOD = 1001 INF = 10 ** 15 class UnionFind(): def __init__(self,n): self.n = n self.parents = [-1]*n def find(self,x): #根を見つける、繋ぎ直す if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def unite(self,x,y): #x,yの含むグループを併合する x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x,y = y,x self.parents[x] += self.parents[y] self.parents[y] = x def same(self,x,y):#xとyが同じグループにいるか判定 return self.find(x) == self.find(y) def members(self,x):#xと同じグループのメンバーを列挙 root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def size(self,x):#xが属するグループのメンバーの数 return -self.parents[self.find(x)] def roots(self):#ufの根を列挙 return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self):#グループの数を数える return len(self.roots()) def solve(V,d,fib): uf = UnionFind(V) for i in range(V): for j in range(i + 1,V): if abs(fib[i] - fib[j]) < d: uf.unite(i,j) ans = uf.group_count() print(ans) def main(): fib = [0] * 1005 fib[0] = 2; fib[1] = 3 for i in range(2,1005): fib[i] = fib[i - 1] + fib[i - 2] fib[i] %= MOD while True: try: V,d = map(int,input().split()) solve(V,d,fib) except: return if __name__ == '__main__': main() ```
output
1
46,117
13
92,235
Provide a correct Python 3 solution for this coding contest problem. Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, each node i having a Fibonacci label F[i] = (f(i) mod N) assigned for i = 1,..., V ≤ N. If |F(i) - F(j)| < d, then the nodes i and j are connected. Given V and d, how many connected subsets of nodes will you obtain? <image> Figure 1: There are 4 connected subsets for V = 20 and d = 100. Constraints * 1 ≤ V ≤ 1000 * 1 ≤ d ≤ 150 Input Each data set is defined as one line with two integers as follows: Line 1: Number of nodes V and the distance d. Input includes several data sets (i.e., several lines). The number of dat sets is less than or equal to 50. Output Output line contains one integer - the number of connected subsets - for each input line. Example Input 5 5 50 1 13 13 Output 2 50 8
instruction
0
46,119
13
92,238
"Correct Solution: ``` while 1: try: v,d=map(int,input().split()) f=[0]*(v+1) f[0],f[1]=1,2 for i in range(2,v+1): f[i]=(f[i-1]+f[i-2])%1001 f.sort() c=1 for i in range(2,v+1): if f[i]-f[i-1]>=d: c+=1 print(c) except:break ```
output
1
46,119
13
92,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Fibonacci number f(i) appear in a variety of puzzles in nature and math, including packing problems, family trees or Pythagorean triangles. They obey the rule f(i) = f(i - 1) + f(i - 2), where we set f(0) = 1 = f(-1). Let V and d be two certain positive integers and be N ≡ 1001 a constant. Consider a set of V nodes, each node i having a Fibonacci label F[i] = (f(i) mod N) assigned for i = 1,..., V ≤ N. If |F(i) - F(j)| < d, then the nodes i and j are connected. Given V and d, how many connected subsets of nodes will you obtain? <image> Figure 1: There are 4 connected subsets for V = 20 and d = 100. Constraints * 1 ≤ V ≤ 1000 * 1 ≤ d ≤ 150 Input Each data set is defined as one line with two integers as follows: Line 1: Number of nodes V and the distance d. Input includes several data sets (i.e., several lines). The number of dat sets is less than or equal to 50. Output Output line contains one integer - the number of connected subsets - for each input line. Example Input 5 5 50 1 13 13 Output 2 50 8 Submitted Solution: ``` while 1: try: v,d=map(int,input().split()) f=[0]*(v+1) f[0],f[1]=1,2 for i in range(2,v+1): f[i]=f[i-1]+f[i-2] f.sort() c=1 for i in range(2,v+1): if f[i]-f[i-1]>=d: c+=1 print(c) except:break ```
instruction
0
46,120
13
92,240
No
output
1
46,120
13
92,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root. Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold: * x is an ancestor of y; * the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: * for every k < j, d_{x, k} < d_{x, j}; * for every k > j, d_{x, k} ≤ d_{x, j}. For every vertex in the tree calculate its dominant index. Input The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of vertices in a tree. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y). This line denotes an edge of the tree. It is guaranteed that these edges form a tree. Output Output n numbers. i-th number should be equal to the dominant index of vertex i. Examples Input 4 1 2 2 3 3 4 Output 0 0 0 0 Input 4 1 2 1 3 1 4 Output 1 0 0 0 Input 4 1 2 2 3 2 4 Output 2 1 0 0 Submitted Solution: ``` n = int(input()) g = {} p = {} for _ in range(n-1): u, v = map(int, input().split()) if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) S = [1] p[1] = 0 i = 0 dp = {} d = {} while i < len(S): u = S[i] for v in g[u]: if v == p[u]: continue p[v] = u S.append(v) i+=1 for u in S[::-1]: if len(g[u]) == 1 and u != 1: dp[u] = [1] #depth # nums d[u] = [0, 1] else: max_length = -1 first = -1 for v in g[u]: if v == p[u]: continue if max_length < len(dp[v]): max_length = len(dp[v]) first = v g_point = d[first][0] max_ = d[first][1] for v in g[u]: if v == p[u] or v == first: continue for i, val in enumerate(dp[v]): dp[first][i] += val if max_ <= dp[first][i]: max_ = dp[first][i] g_point = i dp[first].insert(0, 1) dp[u] = dp[first] if max_ == 1: d[u] = [0, 1] else: d[u] = [g_point+1, max_] for i, val in enumerate(dp[u]): if max_ < val: max_ = val g_point = i ans = '' for k in range(1, n+1): ans += str(d[k][0]) + '\n' print(ans) ```
instruction
0
46,176
13
92,352
No
output
1
46,176
13
92,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root. Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold: * x is an ancestor of y; * the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: * for every k < j, d_{x, k} < d_{x, j}; * for every k > j, d_{x, k} ≤ d_{x, j}. For every vertex in the tree calculate its dominant index. Input The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of vertices in a tree. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y). This line denotes an edge of the tree. It is guaranteed that these edges form a tree. Output Output n numbers. i-th number should be equal to the dominant index of vertex i. Examples Input 4 1 2 2 3 3 4 Output 0 0 0 0 Input 4 1 2 1 3 1 4 Output 1 0 0 0 Input 4 1 2 2 3 2 4 Output 2 1 0 0 Submitted Solution: ``` def main(): n = int(input()) edges = [[] for _ in range(n+1)] for _ in range(n - 1): x, y = map(int, input().split(' ')) edges[x].append(y) edges[y].append(x) tree = [[] for _ in range(n+1)] def make_tree(i, p): for e in edges[i]: if e != p: tree[i].append(e) make_tree(e, i) make_tree(1, 0) ans = [0] * (n + 1) def dfs(i): ans[i] = 0 if not tree[i]: return 1, [1] m = 1 ml, l = dfs(tree[i][0]) if ml > m: ans[i] = ans[tree[i][0]] + 1 m = ml for k in range(1, len(tree[i])): mr, r = dfs(tree[i][k]) if mr > m: ans[i] = ans[tree[i][k]] + 1 m = mr if len(l) < len(r): l, r = r, l ml, mr = mr, ml for j in range(1, len(r) + 1): l[-j] += r[-j] if m < l[-j]: m = l[-j] ans[i] = j l.append(1) return m, l dfs(1) for i in range(1, n+1): print(ans[i]) if __name__ == '__main__': main() ```
instruction
0
46,177
13
92,354
No
output
1
46,177
13
92,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root. Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold: * x is an ancestor of y; * the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: * for every k < j, d_{x, k} < d_{x, j}; * for every k > j, d_{x, k} ≤ d_{x, j}. For every vertex in the tree calculate its dominant index. Input The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of vertices in a tree. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y). This line denotes an edge of the tree. It is guaranteed that these edges form a tree. Output Output n numbers. i-th number should be equal to the dominant index of vertex i. Examples Input 4 1 2 2 3 3 4 Output 0 0 0 0 Input 4 1 2 1 3 1 4 Output 1 0 0 0 Input 4 1 2 2 3 2 4 Output 2 1 0 0 Submitted Solution: ``` from collections import deque def makegraph(links, num): # ls = {} ls = [[] for a in range(num+1)] for l1, l2 in links: # print(ls) # print(ls.get(l1, [])) # ls.setdefault(l1, []).append(l2) # ls.setdefault(l2, []).append(l1) ls[l1].append(l2) ls[l2].append(l1) ig = [0 for a in range(num+1)] order = [0 for a in range(num)] order[0] = (1, -1) ig[1] = -1 cur = 1 ll = ls[1] for l in ll: order[cur] = (l, 1) ig[l] = 1 cur += 1 for a in range(1, num): c, p = order[a] ll = ls[c] ll.remove(p) for l in ll: order[cur] = (l, c) ig[l] = c cur += 1 return ls, order, ig def calcgraph(num, links): # ss = time.clock() ls, order, ig = makegraph(links, num) # print(time.clock() - ss) # print(g, ig, leaves) ans = [0 for a in range(num)] ansv = [0 for a in range(num)] cscratch = {} csp = {} def combine(childs, n): if len(childs) == 0: return [1], 0 mlen = max([len(a) for a in childs]) newl = None for a in range(len(childs)): if mlen == len(childs[a]): newl = childs[a] childs[a] = [] break mlen2 = max([len(a) for a in childs]) res = newl for c in childs: if c is None: continue for a in range(len(c)): res[mlen-a-1] += c[-1-a] res.append(1) lm = 1 li = 0 if ans[n-1] > 0: li = ans[n-1] + 1 lm = ansv[n-1] for a in range(mlen-1, mlen-1 - mlen2, -1): if res[a] > lm: lm = res[a] li = mlen - a return res, li, lm for ii in range(num-1, -1, -1): n, p = order[ii] ll = ls[n] toc = [] for l in ll: toc.append(cscratch[l-1]) if len(toc) == 0: res = [1] dom = 0 domv = 1 elif len(toc) == 1: res = toc[0] res.append(1) dom = ans[ll[0]-1] if dom > 0: dom += 1 domv = ansv[ll[0]-1] else: res, dom, domv = combine(toc, n) ans[n-1] = dom ansv[n-1] = domv cscratch[n-1] = res return '\n'.join([str(a) for a in ans]) # import random # random.seed(123123) # num = 1000000 # potentials = list(range(2, num+1)) # random.shuffle(potentials) # done = [1] # links = [] # for a in potentials: # b = random.randint(0, len(done)-1) # links.append((a, done[b])) # done.append(a) # random.shuffle(links) # import time # start = time.clock() # calcgraph(num, links) # print(time.clock() - start) n = int(input()) links = [] for a in range(n-1): links.append(list(map(int, input().split()))) print(calcgraph(n, links)) ```
instruction
0
46,178
13
92,356
No
output
1
46,178
13
92,357
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted undirected tree consisting of n vertices. Vertex 1 is the root. Let's denote a depth array of vertex x as an infinite sequence [d_{x, 0}, d_{x, 1}, d_{x, 2}, ...], where d_{x, i} is the number of vertices y such that both conditions hold: * x is an ancestor of y; * the simple path from x to y traverses exactly i edges. The dominant index of a depth array of vertex x (or, shortly, the dominant index of vertex x) is an index j such that: * for every k < j, d_{x, k} < d_{x, j}; * for every k > j, d_{x, k} ≤ d_{x, j}. For every vertex in the tree calculate its dominant index. Input The first line contains one integer n (1 ≤ n ≤ 10^6) — the number of vertices in a tree. Then n - 1 lines follow, each containing two integers x and y (1 ≤ x, y ≤ n, x ≠ y). This line denotes an edge of the tree. It is guaranteed that these edges form a tree. Output Output n numbers. i-th number should be equal to the dominant index of vertex i. Examples Input 4 1 2 2 3 3 4 Output 0 0 0 0 Input 4 1 2 1 3 1 4 Output 1 0 0 0 Input 4 1 2 2 3 2 4 Output 2 1 0 0 Submitted Solution: ``` n = int(input()) g = {} p = {} for _ in range(n-1): u, v = map(int, input().split()) if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) S = [1] p[1] = 0 i = 0 dp = {} d = {} while i < len(S): u = S[i] for v in g[u]: if v == p[u]: continue p[v] = u S.append(v) i+=1 for u in S[::-1]: if len(g[u]) == 1 and u != 1: dp[u] = [1] #depth # nums d[u] = [0, 1] else: max_length = -1 first = -1 for v in g[u]: if v == p[u]: continue if max_length < len(dp[v]): max_length = len(dp[v]) first = v g_point = d[first][0] max_ = d[first][1] for v in g[u]: if v == p[u] or v == first: continue for i, val in enumerate(dp[v]): dp[first][i] += val if max_ <= dp[first][i]: if max_ < dp[first][i] or g_point < i: max_ = dp[first][i] g_point = i dp[first].insert(0, 1) dp[u] = dp[first] if max_ == 1: d[u] = [0, 1] else: d[u] = [g_point+1, max_] ans = '' for k in range(1, n+1): ans += str(d[k][0]) + '\n' print(ans) ```
instruction
0
46,179
13
92,358
No
output
1
46,179
13
92,359
Provide tags and a correct Python 3 solution for this coding contest problem. Mitya has a rooted tree with n vertices indexed from 1 to n, where the root has index 1. Each vertex v initially had an integer number a_v ≥ 0 written on it. For every vertex v Mitya has computed s_v: the sum of all values written on the vertices on the path from vertex v to the root, as well as h_v — the depth of vertex v, which denotes the number of vertices on the path from vertex v to the root. Clearly, s_1=a_1 and h_1=1. Then Mitya erased all numbers a_v, and by accident he also erased all values s_v for vertices with even depth (vertices with even h_v). Your task is to restore the values a_v for every vertex, or determine that Mitya made a mistake. In case there are multiple ways to restore the values, you're required to find one which minimizes the total sum of values a_v for all vertices in the tree. Input The first line contains one integer n — the number of vertices in the tree (2 ≤ n ≤ 10^5). The following line contains integers p_2, p_3, ... p_n, where p_i stands for the parent of vertex with index i in the tree (1 ≤ p_i < i). The last line contains integer values s_1, s_2, ..., s_n (-1 ≤ s_v ≤ 10^9), where erased values are replaced by -1. Output Output one integer — the minimum total sum of all values a_v in the original tree, or -1 if such tree does not exist. Examples Input 5 1 1 1 1 1 -1 -1 -1 -1 Output 1 Input 5 1 2 3 1 1 -1 2 -1 -1 Output 2 Input 3 1 2 2 -1 1 Output -1
instruction
0
46,231
13
92,462
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` n = int(input()) p = list(map(int, input().split())) s = list(map(int, input().split())) a = [0]*n a[0] = s[0] g = [[] for _ in range(n+1)] for i in range(n-1): g[p[i]].append(i+2) for i in range(1, n): if s[i] == -1: if len(g[i+1]) == 0: s[i] = s[p[i-1]-1] else: m = s[g[i+1][0]-1] for j in g[i+1]: m = min(m, s[j-1]) s[i] = m if s[i] < s[p[i-1]-1]: print(-1) exit(0) else: a[i] = s[i]-s[p[i-1]-1] print(sum(a)) ```
output
1
46,231
13
92,463