message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2
instruction
0
56,900
13
113,800
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` # optimal answer must be to choose the diameter then remove leaves not on # the diameter then remove the diameter # for every leaf removed, the answer is maximal since otherwise we did not choose # the diameter. When removing the diameter, clearly the maximal answer is # # nodes left - 1 and this is achieved everytime import sys input = sys.stdin.buffer.readline n = int(input()) adj =[[] for i in range(n+1)] for i in range(n-1): a,b = map(int,input().split()) adj[a].append(b) adj[b].append(a) dist1 = [0]*(n+1) dist2 = [0]*(n+1) diameter = [] on_diameter = [0]*(n+1) s = [1] path = [] vis = [0]*(n+1) while s: c = s[-1] if not vis[c]: vis[c] = 1 path.append(c) dist1[c] = len(path)-1 for ne in adj[c]: if not vis[ne]: s.append(ne) else: path.pop() s.pop() mx_dist = 0 endpoint1 = 0 for i in range(1,n+1): if dist1[i] > mx_dist: mx_dist = dist1[i] endpoint1 = i s = [endpoint1] path = [] vis = [0] * (n + 1) while s: c = s[-1] if not vis[c]: vis[c] = 1 path.append(c) dist1[c] = len(path) - 1 for ne in adj[c]: if not vis[ne]: s.append(ne) else: path.pop() s.pop() mx_dist = 0 endpoint2 = 0 for i in range(1, n + 1): if dist1[i] > mx_dist: mx_dist = dist1[i] endpoint2 = i s = [endpoint2] path = [] vis = [0] * (n + 1) while s: c = s[-1] if not vis[c]: vis[c] = 1 path.append(c) if c == endpoint1: diameter = path.copy() dist2[c] = len(path) - 1 for ne in adj[c]: if not vis[ne]: s.append(ne) else: path.pop() s.pop() for i in diameter: on_diameter[i] = 1 mx_answer = 0 operations = [] leaves = [] for i in range(1,n+1): if len(adj[i]) == 1 and not on_diameter[i]: leaves.append(i) degree = [len(adj[i]) for i in range(n+1)] while leaves: c = leaves.pop() if dist1[c] > dist2[c]: mx_answer += dist1[c] operations.append([endpoint1,c,c]) else: mx_answer += dist2[c] operations.append([endpoint2,c,c]) for ne in adj[c]: degree[ne] -= 1 if degree[ne] == 1: leaves.append(ne) while len(diameter) > 1: c = diameter.pop() mx_answer += dist2[c] operations.append([endpoint2,c,c]) print(mx_answer) for operation in operations: print(*operation) ```
output
1
56,900
13
113,801
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2
instruction
0
56,901
13
113,802
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys n = int(sys.stdin.buffer.readline().decode('utf-8')) adj = [[] for _ in range(n)] deg = [0]*n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): adj[u-1].append(v-1) adj[v-1].append(u-1) deg[u-1] += 1 deg[v-1] += 1 def get_dia(adj): from collections import deque n = len(adj) dq = deque([(0, -1)]) while dq: end1, par = dq.popleft() for dest in adj[end1]: if dest != par: dq.append((dest, end1)) prev = [-1]*n prev[end1] = -2 dq = deque([(end1, 0)]) while dq: end2, diameter = dq.popleft() for dest in adj[end2]: if prev[dest] == -1: prev[dest] = end2 dq.append((dest, diameter+1)) return end1, end2, diameter, prev def get_dist(st, dist): dist[st] = 0 stack = [st] while stack: v = stack.pop() for dest in adj[v]: if dist[dest] != -1: continue dist[dest] = dist[v] + 1 stack.append(dest) end1, end2, _, prev = get_dia(adj) dia_path = [0]*n x = end2 while x != end1: dia_path[x] = 1 x = prev[x] dia_path[x] = 1 dist1, dist2 = [-1]*n, [-1]*n get_dist(end1, dist1) get_dist(end2, dist2) ans = [] score = 0 stack = [i for i in range(n) if deg[i] == 1 and dia_path[i] == 0] while stack: v = stack.pop() deg[v] = 0 if dist1[v] > dist2[v]: score += dist1[v] ans.append(f'{end1+1} {v+1} {v+1}') else: score += dist2[v] ans.append(f'{end2+1} {v+1} {v+1}') for dest in adj[v]: if dia_path[dest] == 0 and deg[dest] > 0: deg[dest] -= 1 if deg[dest] <= 1: stack.append(dest) x = end2 while x != end1: score += dist1[x] ans.append(f'{end1+1} {x+1} {x+1}') x = prev[x] sys.stdout.buffer.write( (str(score) + '\n' + '\n'.join(ans)).encode('utf-8') ) ```
output
1
56,901
13
113,803
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2
instruction
0
56,902
13
113,804
Tags: constructive algorithms, dfs and similar, graphs, greedy, trees Correct Solution: ``` import sys n = int(sys.stdin.buffer.readline().decode('utf-8')) adj = [[] for _ in range(n)] deg = [0]*n for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): adj[u-1].append(v-1) adj[v-1].append(u-1) deg[u-1] += 1 deg[v-1] += 1 def get_dia(st): stack = [(st, 0)] prev = [-1]*n prev[st] = -2 dia, t = 0, -1 while stack: v, steps = stack.pop() if dia < steps: dia, t = steps, v for dest in adj[v]: if prev[dest] != -1: continue prev[dest] = v stack.append((dest, steps+1)) return t, prev def get_dist(st, dist): dist[st] = 0 stack = [st] while stack: v = stack.pop() for dest in adj[v]: if dist[dest] != -1: continue dist[dest] = dist[v] + 1 stack.append(dest) edge1, _ = get_dia(0) edge2, prev = get_dia(edge1) dia_path = [0]*n x = edge2 while x != edge1: dia_path[x] = 1 x = prev[x] dia_path[x] = 1 dist1, dist2 = [-1]*n, [-1]*n get_dist(edge1, dist1) get_dist(edge2, dist2) ans = [] score = 0 stack = [i for i in range(n) if deg[i] == 1 and dia_path[i] == 0] while stack: v = stack.pop() deg[v] = 0 if dist1[v] > dist2[v]: score += dist1[v] ans.append(f'{edge1+1} {v+1} {v+1}') else: score += dist2[v] ans.append(f'{edge2+1} {v+1} {v+1}') for dest in adj[v]: if dia_path[dest] == 0 and deg[dest] > 0: deg[dest] -= 1 if deg[dest] <= 1: stack.append(dest) x = edge2 while x != edge1: score += dist1[x] ans.append(f'{edge1+1} {x+1} {x+1}') x = prev[x] sys.stdout.buffer.write( (str(score) + '\n' + '\n'.join(ans)).encode('utf-8') ) ```
output
1
56,902
13
113,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2 Submitted Solution: ``` import sys import traceback class tree: def __init__(self, n): self.edges = dict() self.leaves = set() for i in range(n): self.edges[i + 1] = set() def add_edge(self, edge): self.edges[edge[0]].add(edge[1]) self.edges[edge[1]].add(edge[0]) def remove_vertex(self, v): new_leaves = [] for w in self.edges[v]: self.edges[w].remove(v) if len(self.edges[w]) == 1: self.leaves.add(w) new_leaves.append(w) self.leaves.discard(v) del self.edges[v] return new_leaves def search_leaves(self): for i in self.edges: if len(self.edges[i]) == 1: self.leaves.add(i) def main(): n = int(input()) the_tree = tree(n) edges = sys.stdin.readlines() for edge in edges: edge = tuple(int(i) for i in edge.split(" ")) the_tree.add_edge(edge) the_tree.search_leaves() init_distants = [-1 for i in range(n + 1)] update_distants(the_tree, 0, 1, init_distants) head = get_max_index(init_distants) distants_from_head = [-1 for i in range(n + 1)] update_distants(the_tree, 0, head, distants_from_head) tail = get_max_index(distants_from_head) distants_from_tail = [-1 for i in range(n + 1)] update_distants(the_tree, 0, tail, distants_from_tail) path_len_sum = 0 removal_history = list() process_queue = list(the_tree.leaves) while process_queue: leaf = process_queue.pop(0) if leaf == head or leaf == tail: continue if distants_from_tail[leaf] > distants_from_head[leaf]: path_len_sum += distants_from_tail[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(tail) + " " + str(leaf)) else: path_len_sum += distants_from_head[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) process_queue = list(the_tree.leaves) while process_queue: leaf = process_queue.pop(0) if leaf == head: continue path_len_sum += distants_from_head[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) print(path_len_sum) print("\n".join(removal_history), end="") def update_distants(tree, source, dest, distants): distants[dest] = distants[source] + 1 for new_dest in tree.edges[dest]: if distants[new_dest] == -1: update_distants(tree, dest, new_dest, distants) def get_max_index(some_list): maxi = -1 max_index = -1 for i in range(len(some_list)): if some_list[i] > maxi: maxi = some_list[i] max_index = i return max_index try: main() except Exception as e: print(traceback.format_exc()) ```
instruction
0
56,903
13
113,806
No
output
1
56,903
13
113,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2 Submitted Solution: ``` import sys class tree: def __init__(self, n): self.edges = dict() for i in range(n): self.edges[i + 1] = set() def add_edge(self, edge): edge = [int(i) for i in edge.split(" ")] self.edges[edge[0]].add(edge[1]) self.edges[edge[1]].add(edge[0]) def remove_vertex(self, v): new_leaves = [] for w in self.edges[v]: self.edges[w].remove(v) if len(self.edges[w]) == 1: new_leaves.append(w) return new_leaves def main(): n = int(input()) edges = sys.stdin.read().split() tree_edges = dict() for i in range(n): tree_edges[i + 1] = set() for i in range(len(edges) - 1): tree_edges[int(edges[i])].add(int(edges[i + 1])) tree_edges[int(edges[i + 1])].add(int(edges[i])) init_distants = [-1] * (n + 1) queue = [1] init_distants[1] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if init_distants[next_vertex] == -1: init_distants[next_vertex] = init_distants[process] + 1 if len(tree_edges[next_vertex]) > 1: next_queue.append(next_vertex) queue = next_queue head = init_distants.index(max(init_distants)) distants_from_head = [-1] * (n + 1) queue = [head] distants_from_head[head] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if distants_from_head[next_vertex] == -1: distants_from_head[next_vertex] = distants_from_head[process] + 1 if len(tree_edges[next_vertex]) > 1: next_queue.append(next_vertex) queue = next_queue tail = distants_from_head.index(max(distants_from_head)) distants_from_tail = [-1] * (n + 1) queue = [tail] distants_from_tail[tail] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree_edges[process]: if distants_from_tail[next_vertex] == -1: distants_from_tail[next_vertex] = distants_from_tail[process] + 1 if len(tree_edges[next_vertex]) > 1: next_queue.append(next_vertex) queue = next_queue path_len_sum = 0 removal_history = list() process_queue = [] for vertex, adj in tree_edges.items(): if len(adj) == 1: process_queue.append(vertex) while process_queue: next_queue = [] for leaf in process_queue: if leaf == head or leaf == tail: continue if distants_from_tail[leaf] > distants_from_head[leaf]: path_len_sum += distants_from_tail[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) next_queue.extend(new_leaves) removal_history.append("{0} {1} {0}".format(leaf, tail)) else: path_len_sum += distants_from_head[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) next_queue.extend(new_leaves) removal_history.append("{0} {1} {0}".format(leaf, head)) process_queue = next_queue process_queue = [tail] while process_queue: leaf = process_queue[0] if leaf == head: continue path_len_sum += distants_from_head[leaf] new_leaves = [] for w in tree_edges[leaf]: tree_edges[w].remove(leaf) if len(tree_edges[w]) == 1: new_leaves.append(w) process_queue = new_leaves removal_history.append("{0} {1} {0}".format(leaf, head)) print(str(path_len_sum)) sys.stdout.write("\n".join(removal_history)) sys.stdout.write("\n") main() ```
instruction
0
56,904
13
113,808
No
output
1
56,904
13
113,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2 Submitted Solution: ``` import sys import traceback class tree: def __init__(self, n): self.edges = dict() self.leaves = set() for i in range(n): self.edges[i + 1] = set() def add_edge(self, edge): if edge[0] < 0 or edge[1] < 0 or edge[0] >= len(self.edges) or edge[1] >= len(self.edges): raise Exception("add_edge") self.edges[edge[0]].add(edge[1]) self.edges[edge[1]].add(edge[0]) def remove_vertex(self, v): if v not in self.edges: raise Exception("remove_vertex") new_leaves = [] for w in self.edges[v]: self.edges[w].remove(v) if len(self.edges[w]) == 1: self.leaves.add(w) new_leaves.append(w) self.leaves.discard(v) del self.edges[v] return new_leaves def search_leaves(self): for i in self.edges: if len(self.edges[i]) == 1: self.leaves.add(i) def main(): n = int(input()) the_tree = tree(n) edges = sys.stdin.readlines() for edge in edges: edge = tuple(int(i) for i in edge.split(" ")) the_tree.add_edge(edge) the_tree.search_leaves() init_distants = [-1 for i in range(n + 1)] update_distants(the_tree, 0, 1, init_distants) head = get_max_index(init_distants) distants_from_head = [-1 for i in range(n + 1)] update_distants(the_tree, 0, head, distants_from_head) tail = get_max_index(distants_from_head) distants_from_tail = [-1 for i in range(n + 1)] update_distants(the_tree, 0, tail, distants_from_tail) path_len_sum = 0 removal_history = list() process_queue = list(the_tree.leaves) while process_queue: leaf = process_queue.pop(0) if leaf == head or leaf == tail: continue if distants_from_tail[leaf] > distants_from_head[leaf]: path_len_sum += distants_from_tail[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(tail) + " " + str(leaf)) else: path_len_sum += distants_from_head[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) process_queue = list(the_tree.leaves) while process_queue: leaf = process_queue.pop(0) if leaf == head: continue path_len_sum += distants_from_head[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) print(path_len_sum) print("\n".join(removal_history), end="") def update_distants(tree, source, dest, distants): if len(tree.edges) != len(distants) - 1 or source < 0 or dest < 0 or source >= len(distants) or dest >= len(distants): raise Exception("update_distants") distants[dest] = distants[source] + 1 for new_dest in tree.edges[dest]: if distants[new_dest] == -1: update_distants(tree, dest, new_dest, distants) def get_max_index(some_list): maxi = -1 max_index = -1 for i in range(len(some_list)): if some_list[i] > maxi: maxi = some_list[i] max_index = i return max_index sys.setrecursionlimit(200000) try: main() except Exception as e: print(traceback.format_exc()) ```
instruction
0
56,905
13
113,810
No
output
1
56,905
13
113,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an unweighted tree with n vertices. Then n - 1 following operations are applied to the tree. A single operation consists of the following steps: 1. choose two leaves; 2. add the length of the simple path between them to the answer; 3. remove one of the chosen leaves from the tree. Initial answer (before applying operations) is 0. Obviously after n - 1 such operations the tree will consist of a single vertex. Calculate the maximal possible answer you can achieve, and construct a sequence of operations that allows you to achieve this answer! Input The first line contains one integer number n (2 ≀ n ≀ 2Β·105) β€” the number of vertices in the tree. Next n - 1 lines describe the edges of the tree in form ai, bi (1 ≀ ai, bi ≀ n, ai β‰  bi). It is guaranteed that given graph is a tree. Output In the first line print one integer number β€” maximal possible answer. In the next n - 1 lines print the operations in order of their applying in format ai, bi, ci, where ai, bi β€” pair of the leaves that are chosen in the current operation (1 ≀ ai, bi ≀ n), ci (1 ≀ ci ≀ n, ci = ai or ci = bi) β€” choosen leaf that is removed from the tree in the current operation. See the examples for better understanding. Examples Input 3 1 2 1 3 Output 3 2 3 3 2 1 1 Input 5 1 2 1 3 2 4 2 5 Output 9 3 5 5 4 3 3 4 1 1 4 2 2 Submitted Solution: ``` import sys import time class tree: def __init__(self, n): self.edges = dict() for i in range(n): self.edges[i + 1] = set() def add_edge(self, edge): self.edges[edge[0]].add(edge[1]) self.edges[edge[1]].add(edge[0]) def remove_vertex(self, v): new_leaves = [] neighbors = self.edges[v] for w in neighbors: self.edges[w].remove(v) if len(self.edges[w]) == 1: new_leaves.append(w) del neighbors return new_leaves def main(): times = [] n = int(input()) the_tree = tree(n) times.append(time.time()) edges = sys.stdin.readlines() for edge in edges: edge = tuple(int(i) for i in edge.split(" ")) the_tree.add_edge(edge) init_distants = [-1 for i in range(n + 1)] update_distants(the_tree, 1, init_distants) head = init_distants.index(max(init_distants)) distants_from_head = [-1 for i in range(n + 1)] update_distants(the_tree, head, distants_from_head) tail = distants_from_head.index(max(distants_from_head)) distants_from_tail = [-1 for i in range(n + 1)] update_distants(the_tree, tail, distants_from_tail) times.append(time.time()) path_len_sum = 0 removal_history = list() process_queue = [] for vertex, adj in the_tree.edges.items(): if len(adj) == 1: process_queue.append(vertex) while process_queue: next_queue = [] for leaf in process_queue: if leaf == head or leaf == tail: continue if distants_from_tail[leaf] > distants_from_head[leaf]: path_len_sum += distants_from_tail[leaf] next_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(tail) + " " + str(leaf)) else: path_len_sum += distants_from_head[leaf] next_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) process_queue = next_queue times.append(time.time()) process_queue = [tail] while process_queue: leaf = process_queue.pop(0) if leaf == head: continue path_len_sum += distants_from_head[leaf] process_queue.extend(the_tree.remove_vertex(leaf)) removal_history.append(str(leaf) + " " + str(head) + " " + str(leaf)) times.append(time.time()) print(path_len_sum) print("\n".join(removal_history)) for i in range(len(times) - 1): print(times[i + 1] - times[i]) def update_distants(tree, source, distants): queue = [source] distants[source] = 0 while queue: next_queue = [] for process in queue: for next_vertex in tree.edges[process]: if distants[next_vertex] == -1: distants[next_vertex] = distants[process] + 1 if len(tree.edges[next_vertex]) > 1: next_queue.append(next_vertex) queue = next_queue main() ```
instruction
0
56,906
13
113,812
No
output
1
56,906
13
113,813
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. <image> You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible! Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n; ai β‰  bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them. If it is impossible to cut the given graph, print "No solution" (without quotes). Examples Input 8 12 1 2 2 3 3 4 4 1 1 3 2 4 3 5 3 6 5 6 6 7 6 8 7 8 Output 1 2 4 1 3 2 1 4 3 5 3 6 5 6 8 6 7 8 Input 3 3 1 2 2 3 3 1 Output No solution Input 3 2 1 2 2 3 Output 1 2 3
instruction
0
57,474
13
114,948
Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) if m % 2 != 0: print("No solution") exit(0) return graph def dfs(graph): n = len(graph) w = [0] * n pi = [None] * n visited = [False] * n finished = [False] * n adjacency = [[] for _ in range(n)] stack = [1] while stack: current_node = stack[-1] if visited[current_node]: stack.pop() if finished[current_node]: w[current_node] = 0 continue # print(current_node, adjacency[current_node]) finished[current_node] = True unpair = [] for adj in adjacency[current_node]: if w[adj] == 0: # print('unpaired ->', adj, w[adj]) unpair.append(adj) else: print(' '.join([str(current_node), str(adj), str(w[adj]), '\n'])) while len(unpair) > 1: print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n'])) w[current_node] = unpair.pop() if unpair else 0 continue visited[current_node] = True not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]] stack += not_blocked_neighbors adjacency[current_node] = not_blocked_neighbors # print('stack:', stack, current_node) # def recursive_dfs(graph): # n = len(graph) # visited = [False] * n # recursive_dfs_visit(graph, 1, visited) # def recursive_dfs_visit(graph, root, visited): # unpair = [] # visited[root] = True # adjacency = [x for x in graph[root] if not visited[x]] # for adj in adjacency: # w = recursive_dfs_visit(graph, adj, visited) # if w == 0: # unpair.append(adj) # else: # print(' '.join([str(root), str(adj), str(w), '\n'])) # while len(unpair) > 1: # print(' '.join([str(unpair.pop()), str(root), str(unpair.pop()), '\n'])) # if unpair: # return unpair.pop() # return 0 if __name__ == "__main__": graph = get_input() dfs(graph) ```
output
1
57,474
13
114,949
Provide tags and a correct Python 3 solution for this coding contest problem. Little Chris is participating in a graph cutting contest. He's a pro. The time has come to test his skills to the fullest. Chris is given a simple undirected connected graph with n vertices (numbered from 1 to n) and m edges. The problem is to cut it into edge-distinct paths of length 2. Formally, Chris has to partition all edges of the graph into pairs in such a way that the edges in a single pair are adjacent and each edge must be contained in exactly one pair. For example, the figure shows a way Chris can cut a graph. The first sample test contains the description of this graph. <image> You are given a chance to compete with Chris. Find a way to cut the given graph or determine that it is impossible! Input The first line of input contains two space-separated integers n and m (1 ≀ n, m ≀ 105), the number of vertices and the number of edges in the graph. The next m lines contain the description of the graph's edges. The i-th line contains two space-separated integers ai and bi (1 ≀ ai, bi ≀ n; ai β‰  bi), the numbers of the vertices connected by the i-th edge. It is guaranteed that the given graph is simple (without self-loops and multi-edges) and connected. Note: since the size of the input and output could be very large, don't use slow output techniques in your language. For example, do not use input and output streams (cin, cout) in C++. Output If it is possible to cut the given graph into edge-distinct paths of length 2, output <image> lines. In the i-th line print three space-separated integers xi, yi and zi, the description of the i-th path. The graph should contain this path, i.e., the graph should contain edges (xi, yi) and (yi, zi). Each edge should appear in exactly one path of length 2. If there are multiple solutions, output any of them. If it is impossible to cut the given graph, print "No solution" (without quotes). Examples Input 8 12 1 2 2 3 3 4 4 1 1 3 2 4 3 5 3 6 5 6 6 7 6 8 7 8 Output 1 2 4 1 3 2 1 4 3 5 3 6 5 6 8 6 7 8 Input 3 3 1 2 2 3 3 1 Output No solution Input 3 2 1 2 2 3 Output 1 2 3
instruction
0
57,475
13
114,950
Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write def get_input(): n, m = [int(x) for x in input().split(' ')] graph = [[] for _ in range(n + 1)] for _ in range(m): c1, c2 = [int(x) for x in input().split(' ')] graph[c1].append(c2) graph[c2].append(c1) if m % 2 != 0: print("No solution") exit(0) return graph def partitions_bottom_up(graph): n = len(graph) w = [0] * n pi = [None] * n visited = [False] * n finished = [False] * n adjacency = [[] for _ in range(n)] stack = [1] while stack: current_node = stack[-1] if visited[current_node]: stack.pop() if finished[current_node]: w[current_node] = 0 continue finished[current_node] = True unpair = [] for adj in adjacency[current_node]: if w[adj] == 0: unpair.append(adj) else: print(' '.join([str(current_node), str(adj), str(w[adj]), '\n'])) while len(unpair) > 1: print(' '.join([str(unpair.pop()), str(current_node), str(unpair.pop()), '\n'])) w[current_node] = unpair.pop() if unpair else 0 continue visited[current_node] = True not_blocked_neighbors = [x for x in graph[current_node] if not visited[x]] stack += not_blocked_neighbors adjacency[current_node] = not_blocked_neighbors def partitions_top_down(graph): n = len(graph) visited = [False] * n for node in range(1, n): if not visited[node]: prev_node = None current_node = node while current_node is not None: visited[current_node] = True leafs = [prev_node] if prev_node is not None else [] adjacency = [] for adj in graph[current_node]: if not visited[adj]: if len(graph[adj]) == 1: leafs.append(adj) else: adjacency.append(adj) while len(leafs) > 1: print(' '.join([str(leafs.pop()), str(current_node), str(leafs.pop()), '\n'])) if leafs: adjacency.append(leafs.pop()) while len(adjacency) > 1: print(' '.join([str(adjacency.pop()), str(current_node), str(adjacency.pop()), '\n'])) if adjacency: current_node, prev_node = adjacency.pop(), current_node else: current_node = None if __name__ == "__main__": graph = get_input() partitions_bottom_up(graph) ```
output
1
57,475
13
114,951
Provide tags and a correct Python 3 solution for this coding contest problem. ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
instruction
0
57,649
13
115,298
Tags: binary search, constructive algorithms, graphs, shortest paths Correct Solution: ``` import heapq from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial, end): visited = {initial: 0} path = {} h = [(0, initial)] nodes = set(graph.nodes) while nodes and h: current_weight, min_node = heapq.heappop(h) try: while min_node not in nodes: current_weight, min_node = heapq.heappop(h) except IndexError: break if min_node == end: break nodes.remove(min_node) for v in graph.edges[min_node]: weight = current_weight + graph.distances[min_node, v] if v not in visited or weight < visited[v]: visited[v] = weight heapq.heappush(h, (weight, v)) path[v] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_ls, min_p = dijkstra(min_g, s, t) try: min_l = min_ls[t] max_l = dijkstra(max_g, s, t)[0][t] except KeyError: min_l = 0 max_l = -1 if min_l <= L <= max_l: while min_l < L: a = s b = z = t while z != s: if g.distances[z, min_p[z]] == 0: max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]] max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]] a = z b = min_p[z] z = min_p[z] new_dist = min_g.distances[a, b] + L - min_l max_g.distances[a, b] = new_dist max_g.distances[b, a] = new_dist min_g = max_g min_ls, min_p = dijkstra(min_g, s, t) min_l = min_ls[t] if min_l == L: print('YES') print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v)) else: print('NO') else: print('NO') ```
output
1
57,649
13
115,299
Provide tags and a correct Python 3 solution for this coding contest problem. ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO".
instruction
0
57,650
13
115,300
Tags: binary search, constructive algorithms, graphs, shortest paths Correct Solution: ``` import heapq from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial): visited = {initial: 0} path = {} h = [(0, initial)] nodes = set(graph.nodes) while nodes and h: current_weight, min_node = heapq.heappop(h) try: while min_node not in nodes: current_weight, min_node = heapq.heappop(h) except IndexError: break nodes.remove(min_node) for v in graph.edges[min_node]: weight = current_weight + graph.distances[min_node, v] if v not in visited or weight < visited[v]: visited[v] = weight heapq.heappush(h, (weight, v)) path[v] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_ls, min_p = dijkstra(min_g, s) try: min_l = min_ls[t] max_l = dijkstra(max_g, s)[0][t] except KeyError: min_l = 0 max_l = -1 if min_l <= L <= max_l: while min_l < L: a = s b = z = t while z != s: if g.distances[z, min_p[z]] == 0: max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]] max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]] a = z b = min_p[z] z = min_p[z] new_dist = min_g.distances[a, b] + L - min_l max_g.distances[a, b] = new_dist max_g.distances[b, a] = new_dist min_g = max_g min_ls, min_p = dijkstra(min_g, s) min_l = min_ls[t] if min_l == L: print('YES') print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in min_g.distances.items() if u < v)) else: print('NO') else: print('NO') ```
output
1
57,650
13
115,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". Submitted Solution: ``` from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial): visited = {initial: 0} path = {} nodes = set(graph.nodes) while nodes: min_node = None for node in nodes: if node in visited: if min_node is None: min_node = node elif visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for edge in graph.edges[min_node]: weight = current_weight + graph.distances[(min_node, edge)] if edge not in visited or weight < visited[edge]: visited[edge] = weight path[edge] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_v, min_p = dijkstra(min_g, s) max_v, _ = dijkstra(max_g, s) try: min_w = min_v[t] max_w = max_v[t] if min_w <= L <= max_w: print('YES') r = L - min_w z = t while z != s: if g.distances[z, min_p[z]] == 0: new_dist = min_g.distances[z, min_p[z]] + r max_g.distances[z, min_p[z]] = new_dist max_g.distances[min_p[z], z] = new_dist r = 0 z = min_p[z] for (u, v), w in max_g.distances.items(): if u < v: print('%s %s %s' % (u, v, w)) else: print('NO') except KeyError: print('NO') ```
instruction
0
57,651
13
115,302
No
output
1
57,651
13
115,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". Submitted Solution: ``` from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial): visited = {initial: 0} path = {} nodes = set(graph.nodes) while nodes: min_node = None for node in nodes & set(visited.keys()): if min_node is None or visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for v in graph.edges[min_node]: weight = current_weight + graph.distances[min_node, v] if v not in visited or weight < visited[v]: visited[v] = weight path[v] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_ls, min_p = dijkstra(min_g, s) max_ls = dijkstra(max_g, s)[0] try: min_l = min_ls[t] max_l = max_ls[t] if min_l <= L <= max_l: while max_l != L: a = s b = z = t while z != s: if g.distances[z, min_p[z]] == 0: g.distances[z, min_p[z]] = -1 max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]] max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]] a = z b = min_p[z] z = min_p[z] new_dist = min_g.distances[a, b] + L - min_l max_g.distances[a, b] = new_dist max_g.distances[b, a] = new_dist min_g = max_g min_ls, min_p = dijkstra(min_g, s) min_l = max_l = min_ls[t] print('YES') print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in max_g.distances.items() if u < v)) else: print('NO') except KeyError: print('NO') ```
instruction
0
57,652
13
115,304
No
output
1
57,652
13
115,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. ZS the Coder has drawn an undirected graph of n vertices numbered from 0 to n - 1 and m edges between them. Each edge of the graph is weighted, each weight is a positive integer. The next day, ZS the Coder realized that some of the weights were erased! So he wants to reassign positive integer weight to each of the edges which weights were erased, so that the length of the shortest path between vertices s and t in the resulting graph is exactly L. Can you help him? Input The first line contains five integers n, m, L, s, t (2 ≀ n ≀ 1000, 1 ≀ m ≀ 10 000, 1 ≀ L ≀ 109, 0 ≀ s, t ≀ n - 1, s β‰  t) β€” the number of vertices, number of edges, the desired length of shortest path, starting vertex and ending vertex respectively. Then, m lines describing the edges of the graph follow. i-th of them contains three integers, ui, vi, wi (0 ≀ ui, vi ≀ n - 1, ui β‰  vi, 0 ≀ wi ≀ 109). ui and vi denote the endpoints of the edge and wi denotes its weight. If wi is equal to 0 then the weight of the corresponding edge was erased. It is guaranteed that there is at most one edge between any pair of vertices. Output Print "NO" (without quotes) in the only line if it's not possible to assign the weights in a required way. Otherwise, print "YES" in the first line. Next m lines should contain the edges of the resulting graph, with weights assigned to edges which weights were erased. i-th of them should contain three integers ui, vi and wi, denoting an edge between vertices ui and vi of weight wi. The edges of the new graph must coincide with the ones in the graph from the input. The weights that were not erased must remain unchanged whereas the new weights can be any positive integer not exceeding 1018. The order of the edges in the output doesn't matter. The length of the shortest path between s and t must be equal to L. If there are multiple solutions, print any of them. Examples Input 5 5 13 0 4 0 1 5 2 1 2 3 2 3 1 4 0 4 3 4 Output YES 0 1 5 2 1 2 3 2 3 1 4 8 4 3 4 Input 2 1 123456789 0 1 0 1 0 Output YES 0 1 123456789 Input 2 1 999999999 1 0 0 1 1000000000 Output NO Note Here's how the graph in the first sample case looks like : <image> In the first sample case, there is only one missing edge weight. Placing the weight of 8 gives a shortest path from 0 to 4 of length 13. In the second sample case, there is only a single edge. Clearly, the only way is to replace the missing weight with 123456789. In the last sample case, there is no weights to assign but the length of the shortest path doesn't match the required value, so the answer is "NO". Submitted Solution: ``` from collections import defaultdict class Graph: def __init__(self, n): self.nodes = set(range(n)) self.edges = defaultdict(list) self.distances = {} def add_edge(self, from_node, to_node, distance): self.edges[from_node].append(to_node) self.edges[to_node].append(from_node) self.distances[from_node, to_node] = distance self.distances[to_node, from_node] = distance def dijkstra(graph, initial): visited = {initial: 0} path = {} nodes = set(graph.nodes) while nodes: min_node = None for node in nodes & set(visited.keys()): if min_node is None or visited[node] < visited[min_node]: min_node = node if min_node is None: break nodes.remove(min_node) current_weight = visited[min_node] for v in graph.edges[min_node]: weight = current_weight + graph.distances[min_node, v] if v not in visited or weight < visited[v]: visited[v] = weight path[v] = min_node return visited, path n, m, L, s, t = map(int, input().split()) min_g = Graph(n) max_g = Graph(n) g = Graph(n) for _ in range(m): u, v, w = map(int, input().split()) if w == 0: min_w = 1 max_w = int(1e18) else: min_w = max_w = w min_g.add_edge(u, v, min_w) max_g.add_edge(u, v, max_w) g.add_edge(u, v, w) min_ls, min_p = dijkstra(min_g, s) max_ls = dijkstra(max_g, s)[0] try: min_l = min_ls[t] max_l = max_ls[t] if min_l <= L <= max_l: while max_l < L: a = s b = z = t while z != s: if g.distances[z, min_p[z]] == 0: max_g.distances[z, min_p[z]] = min_g.distances[z, min_p[z]] max_g.distances[min_p[z], z] = min_g.distances[z, min_p[z]] a = z b = min_p[z] z = min_p[z] new_dist = min_g.distances[a, b] + L - min_l max_g.distances[a, b] = new_dist max_g.distances[b, a] = new_dist min_g = max_g min_ls, min_p = dijkstra(min_g, s) min_l = max_l = min_ls[t] if max_l == L: print('YES') print('\n'.join('%s %s %s' % (u, v, w) for (u, v), w in max_g.distances.items() if u < v)) else: print('NO') else: print('NO') except KeyError: print('NO') ```
instruction
0
57,653
13
115,306
No
output
1
57,653
13
115,307
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,725
13
115,450
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` import sys, math, os.path FILE_INPUT = "e.in" DEBUG = os.path.isfile(FILE_INPUT) if DEBUG: sys.stdin = open(FILE_INPUT) def ni(): return map(int, input().split()) def nia(): return list(map(int,input().split())) def log(x): if (DEBUG): print(x) n,m = ni() a = [{i} for i in range(n)] for _ in range(m): x,y = ni() x,y = x-1, y-1 a[x].add(y) a[y].add(x) # print(i) # log(a) q = [] willVisit = set(range(n)) # log(willVisit) while willVisit: x = willVisit.pop() # loang tai x queue = [x] count = 1 while queue: y = queue.pop() sibling = willVisit - a[y] count += len(sibling) queue.extend(sibling) willVisit &= a[y] # willVisit -= sibling # count += 1 # for z in willVisit: # if (not z in a[y]): # queue.add(z) # log(f" y = {y} - {willVisit} - {count} - {sibling}") # log(willVisit) q.append(count) q.sort() print(len(q)) print(" ".join(map(str,q))) ```
output
1
57,725
13
115,451
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,726
13
115,452
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify, nlargest from copy import deepcopy,copy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split())) def inps(): return sys.stdin.readline() def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x]) def err(x): print(x); exit() 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 union(self, 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 size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) n,m = inpl() un = [set() for _ in range(n)] for _ in range(m): a,b = inpl_1() un[b].add(a); un[a].add(b) uf = UnionFind(n) seen = [0]*n unknown = set(range(n)) for i in range(n): if seen[i]: continue seen[i] = 1 unknown.discard(i) adj = deque() noadj = set() for j in list(unknown): if not j in un[i]: adj.append(j) else: noadj.add(j) while adj: j = adj.popleft() for k in list(noadj - un[j]): adj.append(k) noadj.discard(k) seen[j] = 1 unknown.discard(j) uf.union(i,j) res = [] for root in uf.roots(): res.append(uf.size(root)) res.sort() print(len(res)) print(*res) ```
output
1
57,726
13
115,453
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,727
13
115,454
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` import sys, math, os.path FILE_INPUT = "e.in" DEBUG = os.path.isfile(FILE_INPUT) if DEBUG: sys.stdin = open(FILE_INPUT) def ni(): return map(int, input().split()) def nia(): return list(map(int,input().split())) def log(x): if (DEBUG): print(x) n,m = ni() a = [{i} for i in range(n)] for i in range(m): x,y = ni() x,y = x-1, y-1 a[x].add(y) a[y].add(x) # print(i) # log(a) q = [] willVisit = set(range(n)) # log(willVisit) while willVisit: x = willVisit.pop() # loang tai x queue = [x] count = 1 while queue: y = queue.pop() sibling = willVisit - a[y] count += len(sibling) queue.extend(sibling) willVisit -= sibling # count += 1 # for z in willVisit: # if (not z in a[y]): # queue.add(z) # log(f" y = {y} - {willVisit} - {count} - {sibling}") # log(willVisit) q.append(count) q.sort() print(len(q)) print(" ".join(map(str,q))) ```
output
1
57,727
13
115,455
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,728
13
115,456
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` n,m = map(int,input().split()) ae = [[] for _ in range(n)] for _ in range(m): a,b = map(int,input().split()) ae[a-1].append(b-1) ae[b-1].append(a-1) mn = -1 nbr = n for i in range(n): if len(ae[i])<nbr: mn = i nbr = len(ae[i]) keep = ae[mn] ok = n-len(keep) while True: toDel = -1 for i in keep: aeo = len(ae[i]) for j in ae[i]: if j in keep: aeo -= 1 if aeo<ok: break if aeo<ok: toDel = i break if toDel == -1: break else: keep.remove(i) ok += 1 out = [ok] d = {} if len(keep) == 1: out.append(1) elif len(keep) == 0: out = out else: keep.sort() for i in range(len(keep)): d[keep[i]] = i edg = [[] for _ in range(len(keep))] for i in range(len(keep)): for j in range(len(keep)): if i == j: continue edg[i].append(j) edg[j].append(i) for i in keep: for j in ae[i]: if j in keep: if d[j] in edg[d[i]]: edg[d[i]].remove(d[j]) if d[i] in edg[d[j]]: edg[d[j]].remove(d[i]) used = [False]*len(keep) uss = 0 while uss<len(keep): fi = -1 for i in range(len(keep)): if not used[i]: fi = i break bfs = [fi] used[fi] = True usn = 1 uss += 1 while len(bfs) > 0: temp = bfs.pop() for i in edg[temp]: if not used[i]: used[i] = True bfs.append(i) uss += 1 usn += 1 out.append(usn) out.sort() print(len(out)) print(' '.join(map(str,out))) ```
output
1
57,728
13
115,457
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,729
13
115,458
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` import sys, math, os.path FILE_INPUT = "e.in" DEBUG = os.path.isfile(FILE_INPUT) if DEBUG: sys.stdin = open(FILE_INPUT) def ni(): return map(int, input().split()) def nia(): return list(map(int,input().split())) def log(x): if (DEBUG): print(x) n,m = ni() a = [{i} for i in range(n)] for i in range(m): x,y = ni() x,y = x-1, y-1 a[x].add(y) a[y].add(x) # print(i) # log(a) q = [] willVisit = set(range(n)) # log(willVisit) while willVisit: x = willVisit.pop() # loang tai x queue = [x] count = 1 while queue: y = queue.pop() sibling = willVisit - a[y] count += len(sibling) queue.extend(sibling) willVisit &= a[y] # willVisit -= sibling # count += 1 # for z in willVisit: # if (not z in a[y]): # queue.add(z) # log(f" y = {y} - {willVisit} - {count} - {sibling}") # log(willVisit) q.append(count) q.sort() print(len(q)) print(" ".join(map(str,q))) ```
output
1
57,729
13
115,459
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,730
13
115,460
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` import sys from collections import deque n, m = map(int, sys.stdin.buffer.readline().decode('utf-8').split()) adj = [set() for _ in range(n)] for u, v in (map(int, line.decode('utf-8').split()) for line in sys.stdin.buffer): adj[u-1].add(v-1) adj[v-1].add(u-1) dq = deque(range(n)) ans = [] while dq: stack = [dq.popleft()] size = 1 while stack: v = stack.pop() for _ in range(len(dq)): if dq[0] not in adj[v]: size += 1 stack.append(dq.popleft()) dq.rotate() ans.append(size) print(len(ans)) print(*sorted(ans)) ```
output
1
57,730
13
115,461
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,731
13
115,462
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` N,M = map(int,input().split()) nE = [{i} for i in range(N)] for _ in range(M): u,v = map(int,input().split()) u,v = u-1,v-1 nE[u].add(v) nE[v].add(u) unvisited = set(range(N)) res = [] while unvisited: t = len(unvisited) s = next(iter(unvisited)) unvisited.discard(s) stack = [s] while stack: v = stack.pop() s = unvisited & nE[v] stack.extend(unvisited-s) unvisited = s res.append(t-len(unvisited)) res.sort() print(len(res)) print(' '.join(map(str,res))) ```
output
1
57,731
13
115,463
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4
instruction
0
57,732
13
115,464
Tags: data structures, dfs and similar, dsu, graphs Correct Solution: ``` n, m = map(int, input().split()) bar = [{i} for i in range(n)] for i in range(m): u, v = map(int, input().split()) u, v = u - 1, v - 1 bar[u].add(v) bar[v].add(u) nodes = set(range(n)) ans = [] while (nodes): u = next(iter(nodes)) nodes.remove(u) stk = [u] cnt = 1 while (stk): v = stk.pop() s = nodes - bar[v] cnt += len(s) stk.extend(s) nodes &= bar[v] ans.append(cnt) ans.sort() print(len(ans)) print(' '.join(map(str, ans))) ```
output
1
57,732
13
115,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify, nlargest from copy import deepcopy,copy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split())) def inps(): return sys.stdin.readline() def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x]) def err(x): print(x); exit() 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 union(self, 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 size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) n,m = inpl() un = [set() for _ in range(n)] for _ in range(m): a,b = inpl_1() un[b].add(a); un[a].add(b) uf = UnionFind(n) seen = [0]*n unknown = set(range(n)) for i in range(n): if seen[i]: continue seen[i] = 1 unknown.discard(i) adj = deque() noadj = set() for j in unknown: if not j in un[i]: adj.append(j) else: noadj.add(j) while adj: j = adj.popleft() for k in noadj - un[j]: adj.append(k) noadj.discard(k) seen[j] = 1 unknown.discard(j) uf.union(i,j) res = [] for root in uf.roots(): res.append(uf.size(root)) res.sort() print(len(res)) print(*res) ```
instruction
0
57,733
13
115,466
Yes
output
1
57,733
13
115,467
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` import sys input = sys.stdin.readline n, m = map(int, input().split()) eins = set() for _ in range(m): v, to = map(int, input().split()) eins.add((v, to)) eins.add((to, v)) notVisited = set(range(1, n+1)) comps = [] for s in range(1, n+1): if s in notVisited: notVisited.remove(s) ctr = 1 stack = [s] while stack: v = stack.pop() visited = set() for to in notVisited: if (v, to) not in eins: visited.add(to) stack.append(to) ctr += 1 notVisited -= visited comps.append(ctr) comps.sort() print(len(comps)) print(*comps) ```
instruction
0
57,734
13
115,468
Yes
output
1
57,734
13
115,469
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` N,M = map(int,input().split()) nE = [{i} for i in range(N)] for _ in range(M): u,v = map(int,input().split()) u,v = u-1,v-1 nE[u].add(v) nE[v].add(u) unvisited = set(range(N)) res = [] while unvisited: s = next(iter(unvisited)) unvisited.discard(s) stack = [s] cnt = 1 while stack: v = stack.pop() s = unvisited-nE[v] cnt += len(s) stack.extend(s) unvisited &= nE[v] res.append(cnt) res.sort() print(len(res)) print(' '.join(map(str,res))) ```
instruction
0
57,735
13
115,470
Yes
output
1
57,735
13
115,471
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` import sys input = sys.stdin.buffer.readline n,m = map(int,input().split()) adj = [set() for i in range(n+1)] for i in range(m): x,y = map(int,input().split()) adj[x].add(y) adj[y].add(x) unpaired = set([i for i in range(1,n+1)]) comps = [] vis = [0]*(n+1) for i in range(1,n+1): if not vis[i]: comps.append(0) s = [i] while s: c = s[-1] if not vis[c]: comps[-1] += 1 vis[c] = 1 remove = [] for ne in unpaired: if ne not in adj[c]: remove.append(ne) s.append(ne) for ne in remove: unpaired.remove(ne) else: s.pop() print(len(comps)) print(*sorted(comps)) ```
instruction
0
57,736
13
115,472
Yes
output
1
57,736
13
115,473
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` henritt=input() n=int(henritt[0]) m=int(henritt[2]) lol=[] for i in range(1,n+1): for z in range(i, n+1): lol.append(str(i)+" "+str(z)) for i in range(0,m): r=input() if (int(r[0])>int(r[2])): r=r[2]+" "+r[0] lol.remove(r) lolset=[] for i in range(0,int(len(lol))): p=lol[i] hi=p[0] bye=(p[2]) a=set(hi) a.add(bye) lolset.append(a) for i in range(0,int(len(lolset))): for z in range(i+1,int(len(lolset))): s=lolset[i] d=lolset[z] for w in lolset[i]: if w in d: lolset[i]=lolset[i].union(lolset[z]) lolset[z]=lolset[i].union(lolset[z]) p=[lolset[0]] for i in range(1,int(len(lolset))): if lolset[i] in p: g=0 else: p.append(lolset[i]) print(str(len(p))) o=set(str(len(p[0]))) for i in range(1,len(p)): o.add(len(p[i])) c="" for i in o: c=c+str(i)+" " print(c) ```
instruction
0
57,737
13
115,474
No
output
1
57,737
13
115,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` def read_int(): return int(input()) def read_str(): return input() def read_list(type=int): return list(map(type, input().split())) def print_list(x): print(len(x), ' '.join(map(str, x))) # ------------------------------------------------------ def mex(x, n): last = -1 for i in x: if i != last+1: return last+1 last = i return n+1 N = 200123 nbs = [[] for i in range(N)] new_nbs = [[] for i in range(N)] up = [i for i in range(N)] vis = [False] * N def dfs(v): if vis[v]: return 0 vis[v] = True r = 1 for w in new_nbs[v]: r += dfs(w) return r def main(): n, m = read_list() for i in range(m): a, b = read_list() a -= 1 b -= 1 nbs[a].append(b) nbs[b].append(a) for v in range(n): nbs[v].sort() byup = [] for v in range(n): byup.append((min(v, mex(nbs[v], n)), v)) byup.sort() for u, v in byup: up[v] = v if u != v: up[v] = up[u] new_nbs[v].append(up[v]) new_nbs[up[v]].append(v) res = [] for v in range(n): if not vis[v]: res.append(dfs(v)) print(len(res)) res.sort() for r in res: print(r, end=' ') if __name__ == '__main__': main() ```
instruction
0
57,738
13
115,476
No
output
1
57,738
13
115,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` n, m = map(int, input().split()) g = [[] for i in range(n)] for i in range(m): u, v = map(int, input().split()) g[u - 1].append(v - 1) g[v - 1].append(u - 1) c = 0 vis = [0 for i in range(n)] for i in range(n): if vis[i] == 0: c += 1 if c == 2: break else: continue q = [i] vis[i] = 1 while len(q) > 0: v = q[0] del q[0] for u in g[v]: if vis[u] == 0: vis[u] = 1 q.append(u) if c == 2: print(1) print(n) exit() from collections import defaultdict h = defaultdict(lambda: 0) for i in range(n): h[len(g[i])] += 1 ans = [] s = 0 for i in range(1, n + 1): s += h[n - i] while s >= i: s -=i ans.append(i) print(len(ans)) print(' '.join([str(i) for i in ans])) ```
instruction
0
57,739
13
115,478
No
output
1
57,739
13
115,479
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and <image> edges. Instead of giving you the edges that exist in the graph, we give you m unordered pairs (x, y) such that there is no edge between x and y, and if some pair of vertices is not listed in the input, then there is an edge between these vertices. You have to find the number of connected components in the graph and the size of each component. A connected component is a set of vertices X such that for every two vertices from this set there exists at least one path in the graph connecting these vertices, but adding any other vertex to X violates this rule. Input The first line contains two integers n and m (1 ≀ n ≀ 200000, <image>). Then m lines follow, each containing a pair of integers x and y (1 ≀ x, y ≀ n, x β‰  y) denoting that there is no edge between x and y. Each pair is listed at most once; (x, y) and (y, x) are considered the same (so they are never listed in the same test). If some pair of vertices is not listed in the input, then there exists an edge between those vertices. Output Firstly print k β€” the number of connected components in this graph. Then print k integers β€” the sizes of components. You should output these integers in non-descending order. Example Input 5 5 1 2 3 4 3 2 4 2 2 5 Output 2 1 4 Submitted Solution: ``` import sys,math,itertools from collections import Counter,deque,defaultdict from bisect import bisect_left,bisect_right from heapq import heappop,heappush,heapify, nlargest from copy import deepcopy,copy mod = 10**9+7 INF = float('inf') def inp(): return int(sys.stdin.readline()) def inpl(): return list(map(int, sys.stdin.readline().split())) def inpl_1(): return list(map(lambda x:int(x)-1, sys.stdin.readline().split())) def inps(): return sys.stdin.readline() def inpsl(x): tmp = sys.stdin.readline(); return list(tmp[:x]) def err(x): print(x); exit() 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 union(self, 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 size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) n,m = inpl() un = [[] for _ in range(n)] for _ in range(m): a,b = inpl_1() un[b].append(a); un[a].append(b) uf = UnionFind(n) seen = [0]*n unknown = set(range(n)) for i in range(n): if seen[i]: continue unknown.discard(i) seen[i] = 1 lis = copy(unknown) for v in un[i]: lis.discard(v) for v in list(lis): uf.union(i,v) seen[v] = 1 unknown.discard(v) res = [] for root in uf.roots(): res.append(uf.size(root)) res.sort() print(len(res)) print(*res) ```
instruction
0
57,740
13
115,480
No
output
1
57,740
13
115,481
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a simple connected undirected graph G consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Edge i connects Vertex a_i and b_i bidirectionally. It is guaranteed that the subgraph consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a spanning tree of G. An allocation of weights to the edges is called a good allocation when the tree consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a minimum spanning tree of G. There are M! ways to allocate the edges distinct integer weights between 1 and M. For each good allocation among those, find the total weight of the edges in the minimum spanning tree, and print the sum of those total weights modulo 10^{9}+7. Constraints * All values in input are integers. * 2 \leq N \leq 20 * N-1 \leq M \leq N(N-1)/2 * 1 \leq a_i, b_i \leq N * G does not have self-loops or multiple edges. * The subgraph consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a spanning tree of G. Input Input is given from Standard Input in the following format: N M a_1 b_1 \vdots a_M b_M Output Print the answer. Examples Input 3 3 1 2 2 3 1 3 Output 6 Input 4 4 1 2 3 2 3 4 1 3 Output 50 Input 15 28 10 7 5 9 2 13 2 14 6 1 5 12 2 10 3 9 10 15 11 12 12 6 2 12 12 8 4 10 15 3 13 14 1 15 15 12 4 14 1 7 5 11 7 13 9 10 2 7 1 9 5 6 12 14 5 2 Output 657573092 Submitted Solution: ``` a = 3,3 print "6" ```
instruction
0
57,816
13
115,632
No
output
1
57,816
13
115,633
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a simple connected undirected graph G consisting of N vertices and M edges. The vertices are numbered 1 to N, and the edges are numbered 1 to M. Edge i connects Vertex a_i and b_i bidirectionally. It is guaranteed that the subgraph consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a spanning tree of G. An allocation of weights to the edges is called a good allocation when the tree consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a minimum spanning tree of G. There are M! ways to allocate the edges distinct integer weights between 1 and M. For each good allocation among those, find the total weight of the edges in the minimum spanning tree, and print the sum of those total weights modulo 10^{9}+7. Constraints * All values in input are integers. * 2 \leq N \leq 20 * N-1 \leq M \leq N(N-1)/2 * 1 \leq a_i, b_i \leq N * G does not have self-loops or multiple edges. * The subgraph consisting of Vertex 1,2,\ldots,N and Edge 1,2,\ldots,N-1 is a spanning tree of G. Input Input is given from Standard Input in the following format: N M a_1 b_1 \vdots a_M b_M Output Print the answer. Examples Input 3 3 1 2 2 3 1 3 Output 6 Input 4 4 1 2 3 2 3 4 1 3 Output 50 Input 15 28 10 7 5 9 2 13 2 14 6 1 5 12 2 10 3 9 10 15 11 12 12 6 2 12 12 8 4 10 15 3 13 14 1 15 15 12 4 14 1 7 5 11 7 13 9 10 2 7 1 9 5 6 12 14 5 2 Output 657573092 Submitted Solution: ``` a = 4,4 print"50" ```
instruction
0
57,817
13
115,634
No
output
1
57,817
13
115,635
Provide a correct Python 3 solution for this coding contest problem. Mole decided to live in an abandoned mine. The structure of the mine is represented by a simple connected undirected graph which consists of N vertices numbered 1 through N and M edges. The i-th edge connects Vertices a_i and b_i, and it costs c_i yen (the currency of Japan) to remove it. Mole would like to remove some of the edges so that there is exactly one path from Vertex 1 to Vertex N that does not visit the same vertex more than once. Find the minimum budget needed to achieve this. Constraints * 2 \leq N \leq 15 * N-1 \leq M \leq N(N-1)/2 * 1 \leq a_i, b_i \leq N * 1 \leq c_i \leq 10^{6} * There are neither multiple edges nor self-loops in the given graph. * The given graph is connected. Input Input is given from Standard Input in the following format: N M a_1 b_1 c_1 : a_M b_M c_M Output Print the answer. Examples Input 4 6 1 2 100 3 1 100 2 4 100 4 3 100 1 4 100 3 2 100 Output 200 Input 2 1 1 2 1 Output 0 Input 15 22 8 13 33418 14 15 55849 7 10 15207 4 6 64328 6 9 86902 15 7 46978 8 14 53526 1 2 8720 14 12 37748 8 3 61543 6 5 32425 4 11 20932 3 12 55123 8 2 45333 9 12 77796 3 9 71922 12 15 70793 2 4 25485 11 6 1436 2 7 81563 7 11 97843 3 1 40491 Output 133677
instruction
0
57,866
13
115,732
"Correct Solution: ``` n, m = map(int, input().split()) g = [[0 for j in range(n)] for i in range(n)] for i in range(m): u, v, w = map(int, input().split()) g[u - 1][v - 1] = g[v - 1][u - 1] = w e = [sum(g[i][j] for i in range(n) if S >> i & 1 for j in range(i + 1, n) if S >> j & 1) for S in range(1 << n)] dp = [[-10 ** 9 for j in range(n)] for i in range(1 << n)] for i in range(1 << n): for j in range(n): if i >> j & 1: if not j: dp[i][j] = e[i] else: for k in range(n): if j != k and (i >> k & 1) and g[k][j]: dp[i][j] = max(dp[i][j], dp[i ^ (1 << j)][k] + g[k][j]) s = i ^ (1 << j) k = s while k: dp[i][j] = max(dp[i][j], dp[i ^ k][j] + e[k | 1 << j]) k = (k - 1) & s print(e[(1 << n) - 1] - dp[(1 << n) - 1][n - 1]) ```
output
1
57,866
13
115,733
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,072
13
116,144
Tags: dfs and similar, graphs Correct Solution: ``` from sys import stdin input=lambda : stdin.readline().strip() from math import ceil,sqrt,factorial,gcd from collections import deque from bisect import bisect_left def dfs(x,c): global flag stack=deque([[x,c]]) while stack: # print(graph,l) x,c=stack.pop() if l[x]==-1: l[x]=c else: if l[x]!=c: flag=0 return else: continue for i in graph[x]: if l[i]==-1: stack.append([i,c^1]) graph[i].remove(x) # graph[x].remove(i) elif l[x]==l[i]: flag=0 return n,m=map(int,input().split()) graph={i:set() for i in range(1,n+1)} ed=[] for i in range(m): a,b=map(int,input().split()) graph[a].add(b) graph[b].add(a) ed.append([a,b]) l=[-1 for i in range(n+1)] flag=1 dfs(1,0) if flag==0: print("NO") else: print("YES") for i,j in ed: if l[i]==0 and l[j]==1: print("0",end='') else: print('1',end='') ```
output
1
58,072
13
116,145
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,073
13
116,146
Tags: dfs and similar, graphs Correct Solution: ``` # Author : raj1307 - Raj Singh # Date : 23.05.2020 from __future__ import print_function import itertools,os,sys,threading # input=raw_input # range=xrange def ii(): return int(input()) def si(): return input() def mi(): return map(int,input().strip().split(" ")) def msi(): return map(str,input().strip().split(" ")) def li(): return list(mi()) def dmain(): sys.setrecursionlimit(1000000) threading.stack_size(40960000) thread = threading.Thread(target=main) thread.start() from collections import deque, Counter, OrderedDict,defaultdict #from heapq import nsmallest, nlargest, heapify,heappop ,heappush, heapreplace #from math import log,sqrt,factorial,cos,tan,sin,radians #from bisect import bisect,bisect_left,bisect_right,insort,insort_left,insort_right #from decimal import * #from itertools import permutations #Copy 2D list m = [x[:] for x in mark] .. Avoid Using Deepcopy abc='abcdefghijklmnopqrstuvwxyz' abd={'a': 0, 'b': 1, 'c': 2, 'd': 3, 'e': 4, 'f': 5, 'g': 6, 'h': 7, 'i': 8, 'j': 9, 'k': 10, 'l': 11, 'm': 12, 'n': 13, 'o': 14, 'p': 15, 'q': 16, 'r': 17, 's': 18, 't': 19, 'u': 20, 'v': 21, 'w': 22, 'x': 23, 'y': 24, 'z': 25} mod=1000000007 #mod=998244353 inf = float("inf") vow=['a','e','i','o','u'] dx,dy=[-1,1,0,0],[0,0,1,-1] def getKey(item): return item[1] def sort2(l):return sorted(l, key=getKey,reverse=True) def d2(n,m,num):return [[num for x in range(m)] for y in range(n)] def isPowerOfTwo (x): return (x and (not(x & (x - 1))) ) def decimalToBinary(n): return bin(n).replace("0b","") def ntl(n):return [int(i) for i in str(n)] def ncr(n,r): return factorial(n)//(factorial(r)*factorial(max(n-r,1))) def ceil(x,y): if x%y==0: return x//y else: return x//y+1 def powerMod(x,y,p): res = 1 x %= p while y > 0: if y&1: res = (res*x)%p y = y>>1 x = (x*x)%p return res def gcd(x, y): while y: x, y = y, x % y return x def isPrime(n) : # Check Prime Number or not if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True def read(): sys.stdin = open('input.txt', 'r') sys.stdout = open('output.txt', 'w') g=defaultdict(list) color = [-1]*(200005) def bfs(n): #color = [-1]*(n+5) for i in range(n): if color[i]==-1: color[i] = 0 Q = [(i,0)] while Q: node, c = Q.pop() for nei in g[node]: if color[nei] == -1: color[nei] = 1-c Q.append((nei, 1-c)) else: if color[nei]!=1-c: print('NO') exit() def main(): #for _ in range(ii()): n,m=mi() u=[0]*200005 for i in range(m): x,y=mi() u[i]=x g[x].append(y) g[y].append(x) bfs(n) print('YES') ans='' for i in range(m): print(color[u[i]],end='') if __name__ == "__main__": #read() #dmain() sys.setrecursionlimit(1000) # threading.stack_size(10240000) # thread = threading.Thread(target=main) # thread.start() main() # Comment Read() ```
output
1
58,073
13
116,147
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,074
13
116,148
Tags: dfs and similar, graphs Correct Solution: ``` import sys from typing import List, Tuple, Dict # **Note: To enable DEBUG, just add argument "-d" to the binary**. I.e.: # `python solution.py -d` DEBUG = len(sys.argv) > 1 and sys.argv[1] == '-d' # Sample usage: `LOG("a =", 1,"b =", 2)`. def LOG(*argv): if (DEBUG): print(*argv, file=sys.stderr) def CHECK(cond, err_msg=''): if (DEBUG): assert cond, err_msg def CHECK_EQ(a, b, err_msg=''): CHECK(a == b, err_msg='{} v.s. {} {}'.format(a, b, err_msg)) def readval(typ=int): return typ(input()) def readvals(typ=int): return list(map(typ, input().split())) ###############################################################################/ ############################* Above are tmpl code #############################/ ###############################################################################/ def solve(n: int, m: int, edges: List[Tuple[int, int]]) -> str: r''' There's no path of len>=2 means each node can have only in-degrees or only out-degrees. I.e. be colored as "sink" or "source" nodes. Do a BFS and traverse all nodes/edges to make sure that such a coloring is possible.''' from collections import defaultdict neighbors: Dict[int, List[int]] = defaultdict(list) for u, v in edges: neighbors[u].append(v) neighbors[v].append(u) LOG('neighbors=', neighbors) # color[v] = True if distance(i, v) is even else False. color: Dict[int, bool] = {1: True} queue, visited = [1], set([1]) cur_color = True # BFS by layer, to color all nodes by parity of the distance from node 1. while len(queue) > 0: next_queue = [] next_color = not cur_color for node in queue: for next_node in neighbors[node]: if next_node not in visited: visited.add(next_node) next_queue.append(next_node) color[next_node] = next_color queue = next_queue cur_color = next_color # Get the result from the node colors. solution = '' for u, v in edges: if color[u] == color[v]: return 'NO' solution += '1' if color[u] is True else '0' return f'YES\n{solution}' if __name__ == '__main__': n, m = readvals() edges = [readvals() for _ in range(m)] LOG('edges=', edges) print(solve(n, m, edges)) ```
output
1
58,074
13
116,149
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,075
13
116,150
Tags: dfs and similar, graphs Correct Solution: ``` import os from io import BytesIO #input = BytesIO(os.read(0, os.fstat(0).st_size)).readline def input_as_list(): return list(map(int, input().split())) def array_of(f, *dim): return [array_of(f, *dim[1:]) for _ in range(dim[0])] if dim else f() def main(): n, m = input_as_list() G = array_of(list, n) E = [] for _ in range(m): u, v = input_as_list() u, v = u-1, v-1 G[u].append(v) G[v].append(u) E.append((u, v)) depth = array_of(int, n) visited = array_of(bool, n) visited[0] = True stack = [0] while stack: u = stack.pop() for v in G[u]: if visited[v]: if depth[u]%2 == depth[v]%2: print('NO') return else: depth[v] = depth[u] + 1 visited[v] = True stack.append(v) out = [] for u, v in E: out.append(str(depth[u]%2)) print('YES') print(''.join(out)) main() ```
output
1
58,075
13
116,151
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,076
13
116,152
Tags: dfs and similar, graphs Correct Solution: ``` from collections import defaultdict ,deque def bfs(): q = deque([1]) color[1] = 1 while q : v = q.popleft() for i in g[v]: if color[i] == 0 : color[i] = - color[v] q.append(i) elif color[i] == color[v]: return False return True n , m = map(int,input().split()) edges = [] g = defaultdict(list) for i in range(m): u , v = map(int,input().split()) g[u].append(v) g[v].append(u) edges.append((u , v)) color = [0]*(n + 1) r = bfs() if r == False: print('NO') exit(0) ans = [] #print(color) for u , v in edges : if color[u] == 1 and color[v] == -1 : ans.append('1') else: ans.append('0') print('YES') print(''.join(ans)) ```
output
1
58,076
13
116,153
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,077
13
116,154
Tags: dfs and similar, graphs Correct Solution: ``` # lista doble enlazada o(1) operaciones en los bordes es mejor que si se implementa en el propio lenguaje from collections import deque def bfs_2k(graph, initVertex, color): queue = deque() queue.append(initVertex) color[initVertex] = 0 while queue: u = queue.popleft() for v in graph[u]: if color[v] == color[u]: return False if(color[v]==-1): color[v] = color[u] ^ 1 queue.append(v) return True n, m = input().split() n = int(n) m = int(m) graph = [[] for _ in range(0, n)] color = [-1]*n edges = [] for i in range(0, m): u, v = input().split() u = int(u)-1 v = int(v)-1 edges.append(v) graph[u].append(v) graph[v].append(u) if bfs_2k(graph, 0, color): print("YES") print("".join(str(color[e]) for e in edges)) else: print("NO") ```
output
1
58,077
13
116,155
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,078
13
116,156
Tags: dfs and similar, graphs Correct Solution: ``` def dostuff(d, q): while q: v,inc = q.pop() for e in c[v]: oth = e[1] if e[0]==v else e[0] if e in d: if (d[e]!=v if inc else d[e]==v): return False, d else: d[e]=v if inc else oth q.append((oth, not inc)) return True,d def s(o, d,l=[]): for k in o: l.append(int(d[k]==k[0])) return "".join(map(str,l)) import io,os input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline y=lambda:map(lambda x:int(x)-1, input().split()) n,m = y() c,o = [[] for _ in range(n+1)],[] for _ in range(m+1): a,b = y() c[a].append((a, b)) c[b].append((a, b)) o.append((a,b)) k, d = dostuff({(a,b):a},[(a,True), (b,False)]) print("YES\n"+s(o, d) if k else "NO") ```
output
1
58,078
13
116,157
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image>
instruction
0
58,079
13
116,158
Tags: dfs and similar, graphs Correct Solution: ``` from collections import deque n, m = map(int, input().split()) g = [[] for _ in range(n)] e = [] for _ in range(m): u, v = map(lambda _: int(_) - 1, input().split()) e.append((u, v)) g[u].append(v); g[v].append(u) p = [-1 for _ in range(n)] p[0] = True ok = True q = deque([0]) while q: f = q.popleft() for t in g[f]: if p[t] == -1: q.append(t) p[t] = not p[f] elif p[t] == p[f]: ok = False if not ok: print('NO') else: print('YES') print(''.join(('1' if p[e[i][0]] else '0') for i in range(m))) ```
output
1
58,079
13
116,159
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` from sys import * setrecursionlimit(3000) v, e = map(int, input().split()) V = [] for i in range(v): V.append([-1, []]) edges = [] for i in range(e): a, b = map(int, input().split()) edges.append([a-1,b-1]) V[a-1][1].append(b-1) V[b-1][1].append(a-1) cand = [0] p = 1 f = True while cand: ncan = [] for c in cand: if V[c][0] == p: f = False break V[c][0] = p ^ 1 for d in V[c][1]: if V[d][0] == -1: ncan.append(d) if not f: break p ^= 1 cand = ncan if not f: print("NO") else: ans = [] for x in edges: ans += str(V[x[0]][0]) print("YES") print("".join(ans)) ```
instruction
0
58,080
13
116,160
Yes
output
1
58,080
13
116,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` from sys import stdin from collections import deque input = stdin.readline def solve(): visited = [False]*(n+1) direction = [True]*(n+1) visited[1] = True queue = deque() queue.append(1) while queue: node = queue.popleft() for neighbor in g[node]: if visited[neighbor]: if direction[node] == direction[neighbor]: print("NO") return else: visited[neighbor] = True direction[neighbor] = not direction[node] queue.append(neighbor) ans = [] for u, v in a: ans.append(int(direction[u])) print("YES") print(*ans, sep="") n, m = [int(x) for x in input().split()] g = [[] for _ in range(n+1)] a = [] for _ in range(m): u, v = [int(x) for x in input().split()] g[u].append(v) g[v].append(u) a.append((u, v)) solve() ```
instruction
0
58,081
13
116,162
Yes
output
1
58,081
13
116,163
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` import sys def input(): return sys.stdin.readline() n, m = map(int, input().split()) give = [False] * (n + 1) take = [False] * (n + 1) edge = dict() inputs = [] for i in range(n): edge[i+1] = [] for i in range(m): u, v = map(int, input().split()) inputs.append((u, v)) edge[u].append(v) edge[v].append(u) check = [False] * (n + 1) queue = [1] front = 0 while front < len(queue): u = queue[front] check[u] = True for v in edge[u]: if check[v]: continue queue.append(v) if (give[u] and give[v]) or (take[u] and take[v]): print('NO') exit() if (give[u] and take[v]) or (take[u] and give[v]): continue if give[u]: take[v] = True continue if take[u]: give[v] = True continue if give[v]: take[u] = True continue if take[v]: give[u] = True continue give[u] = True take[v] = True front += 1 print('YES') for u, v in inputs: if give[u] and take[v]: print(1, end="") else: print(0, end="") print() ```
instruction
0
58,082
13
116,164
Yes
output
1
58,082
13
116,165
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` import sys input = sys.stdin.readline from collections import deque class UnDirectedGraph: def __init__(self, N, M): self.V = N self.E = M self.edge = [[] for _ in range(self.V)] self.edges = [0]*self.E self.visited = [False]*self.V self.color = [-1]*self.V def add_edges(self, ind=1): for i in range(self.E): a,b = map(int, input().split()) a -= ind; b -= ind self.edge[a].append(b) self.edge[b].append(a) self.edges[i] = (a,b) def bfs(self, start): d = deque() self.color[start]=0 d.append(start) while len(d)>0: v = d.popleft() for w in self.edge[v]: if self.color[w]==-1: self.color[w]=self.color[v]^1 d.append(w) elif self.color[w]==self.color[v]: return False return True N, M = map(int, input().split()) G = UnDirectedGraph(N,M) G.add_edges(1) if G.bfs(0): print('YES') ans = '' for i in range(M): ans += str(G.color[G.edges[i][0]]) print(ans) else: print('NO') ```
instruction
0
58,083
13
116,166
Yes
output
1
58,083
13
116,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` from sys import stdin from collections import defaultdict def ip(): return [int(i) for i in stdin.readline().split()] def sp(): return [str(i) for i in stdin.readline().split()] def pp(A): for i in A: print(i) bipartite = True def dfs(v,c,color,d): color[v] = c for i in d[v]: if color[i] == -1: dfs(i, c^1, color,d) else: if color[i] == color[v]: bipartite = False return color def solve(): n, m = ip() d = defaultdict(list) e = [] for _ in range(m): x,y = ip() x -= 1 y -= 1 d[x].append(y) d[y].append(x) e.append([x,y]) color = [-1] * n color = dfs(0,0,color,d) if not bipartite: print("NO") return 0 print("YES") for i in range(m): if color[e[i][1]] < color[e[i][0]]: print("0", end="") else: print("1", end="") return 0 solve() ```
instruction
0
58,084
13
116,168
No
output
1
58,084
13
116,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` from collections import * from sys import stdin def arr_inp(n): if n == 1: return [int(x) for x in stdin.readline().split()] elif n == 2: return [float(x) for x in stdin.readline().split()] else: return list(stdin.readline()[:-1]) class graph: # initialize graph def __init__(self, gdict=None): if gdict is None: gdict = defaultdict(list) self.gdict, self.edges, self.l = gdict, [], defaultdict(int) # Get verticies def get_vertices(self): return list(self.gdict.keys()) # add edge def add_edge(self, node1, node2, w=None): self.gdict[node1].append(node2) self.gdict[node2].append(node1) self.edges.append([node1, node2]) def bfs_util(self, i): # self.visit = defaultdict(int) queue, self.visit[i], self.color = deque([i, 0]), 1, [0] * (n + 1) while queue: # dequeue parent vertix s = queue.popleft() # enqueue child vertices for i in self.gdict[s]: if self.visit[i] == 0: queue.append(i) self.visit[i] = 1 self.color[i] = self.color[s] ^ 1 def bfs(self): self.visit = defaultdict(int) for i in self.get_vertices(): if self.visit[i] == 0: self.bfs_util(i) ans, dis = [], set() for u, v in g.edges: ans.append('0' if self.color[u] else '1') if self.color[u] == 0: dis.add(u) # print(self.color, ans) if sum(self.color) + len(dis) != n: print('NO') else: print('YES') print(''.join(ans)) g = graph() n, m = arr_inp(1) for i in range(m): u, v = arr_inp(1) g.add_edge(u, v) g.bfs() ```
instruction
0
58,085
13
116,170
No
output
1
58,085
13
116,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` import sys from collections import defaultdict,deque def cycle(graph,start): vis=defaultdict(int) popped=defaultdict(int) q=deque() q.append(start) vis[start]=1 while q: a=q.popleft() popped[a]=1 for i in graph[a]: if vis[i]==1: if popped[i]==0: return True else: vis[i]=1 q.append(i) return False def color(graph,start,edges): q=deque() q.append([start,'0']) vis=defaultdict(int) vis[start]=1 while q: a,col=q.popleft() if col=='0': col='1' else: col='0' for k in graph[a]: if vis[k]==1: edges[min(k,a),max(k,a)]=col else: vis[k]=1 edges[min(k,a),max(k,a)]=col q.append([k,col]) n,m = map(int,sys.stdin.readline().split()) graph = defaultdict(list) edges = defaultdict(int) mark = [[0,0] for _ in range(m)] for i in range(m): u,v = map(int,sys.stdin.readline().split()) graph[u].append(v) graph[v].append(u) mark[i] = [u,v] #print(graph,'graph') start = u val = '0' a=cycle(graph,start) if a: print("NO") sys.exit() color(graph,start,edges) ans=[0 for _ in range(m)] #print(edges,'edges') for i in range(m): if edges[(mark[i][0],mark[i][1])]!=0: ans[i]=edges[(mark[i][0],mark[i][1])] else: if edges[(mark[i][1],mark[i][0])]=='1': ans[i]='0' else: ans[i]='1' #ans[i]=edges[(min(mark[i][0],mark[i][1]),max(mark[i][0],mark[i][1]))] print("YES") print(''.join(c for c in ans)) ```
instruction
0
58,086
13
116,172
No
output
1
58,086
13
116,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected undirected graph consisting of n vertices and m edges. There are no self-loops or multiple edges in the given graph. You have to direct its edges in such a way that the obtained directed graph does not contain any paths of length two or greater (where the length of path is denoted as the number of traversed edges). Input The first line contains two integer numbers n and m (2 ≀ n ≀ 2 β‹… 10^5, n - 1 ≀ m ≀ 2 β‹… 10^5) β€” the number of vertices and edges, respectively. The following m lines contain edges: edge i is given as a pair of vertices u_i, v_i (1 ≀ u_i, v_i ≀ n, u_i β‰  v_i). There are no multiple edges in the given graph, i. e. for each pair (u_i, v_i) there are no other pairs (u_i, v_i) and (v_i, u_i) in the list of edges. It is also guaranteed that the given graph is connected (there is a path between any pair of vertex in the given graph). Output If it is impossible to direct edges of the given graph in such a way that the obtained directed graph does not contain paths of length at least two, print "NO" in the first line. Otherwise print "YES" in the first line, and then print any suitable orientation of edges: a binary string (the string consisting only of '0' and '1') of length m. The i-th element of this string should be '0' if the i-th edge of the graph should be directed from u_i to v_i, and '1' otherwise. Edges are numbered in the order they are given in the input. Example Input 6 5 1 5 2 1 1 4 3 1 6 1 Output YES 10100 Note The picture corresponding to the first example: <image> And one of possible answers: <image> Submitted Solution: ``` a = 1 ```
instruction
0
58,087
13
116,174
No
output
1
58,087
13
116,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n. You have to process q queries of two types: * 1 v β€” among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; * 2 i β€” delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). Input The first line contains three integers n, m and q (1 ≀ n ≀ 2 β‹… 10^5; 1 ≀ m ≀ 3 β‹… 10^5; 1 ≀ q ≀ 5 β‹… 10^5). The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 ≀ p_i ≀ n). Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≀ a_i, b_i ≀ n, a_i β‰  b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges. Then q lines follow, which describe the queries. Each line is given by one of the following formats: * 1 v β€” denotes a query of the first type with a vertex v (1 ≀ v ≀ n). * 2 i β€” denotes a query of the second type with an edge i (1 ≀ i ≀ m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. Output For every query of the first type, print the value of p_u written on the chosen vertex u. Example Input 5 4 6 1 2 5 4 3 1 2 2 3 1 3 4 5 1 1 2 1 2 3 1 1 1 2 1 2 Output 5 1 2 0 Submitted Solution: ``` n, m, q = map(int, input().split()) values_list = [0] + list(map(int, input().split())) values = {} for i in range(1, n + 1): values[i] = values_list[i] edges = {} for i in range(1, m + 1): x, y = map(int, input().split()) edges[i] = [x, y] for i in range(q): w, v = map(int, input().split()) if w == 1: marks = set([v]) result = values[v] deleted = v for i in edges: x, y = edges[i] if (x in marks) or (y in marks): marks.add(x) marks.add(y) if values[x] > result: result = values[x] deleted = x if values[y] > result: result = values[y] deleted = y values[deleted] = 0 print(result) else: edges.pop(v) m -= 1 ```
instruction
0
58,217
13
116,434
No
output
1
58,217
13
116,435