message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree with n nodes and q queries. Every query starts with three integers k, m and r, followed by k nodes of the tree a_1, a_2, …, a_k. To answer a query, assume that the tree is rooted at r. We want to divide the k given nodes into at most m groups such that the following conditions are met: * Each node should be in exactly one group and each group should have at least one node. * In any group, there should be no two distinct nodes such that one node is an ancestor (direct or indirect) of the other. You need to output the number of ways modulo 10^{9}+7 for every query. Input The first line contains two integers n and q (1 ≤ n, q ≤ 10^{5}) — the number of vertices in the tree and the number of queries, respectively. Each of the next n-1 lines contains two integers u and v (1 ≤ u, v ≤ n, u ≠ v), denoting an edge connecting vertex u and vertex v. It is guaranteed that the given graph is a tree. Each of the next q lines starts with three integers k, m and r (1 ≤ k, r ≤ n, 1 ≤ m ≤ min(300,k)) — the number of nodes, the maximum number of groups and the root of the tree for the current query, respectively. They are followed by k distinct integers a_1, a_2, …, a_k (1 ≤ a_i ≤ n), denoting the nodes of the current query. It is guaranteed that the sum of k over all queries does not exceed 10^{5}. Output Print q lines, where the i-th line contains the answer to the i-th query. Examples Input 7 2 5 4 2 6 5 3 1 2 7 5 4 6 3 3 2 7 4 3 3 1 4 6 2 1 Output 2 0 Input 7 2 4 7 2 5 4 1 5 1 5 6 4 3 3 3 2 7 1 4 2 1 6 3 2 Output 1 1 Input 5 2 3 5 4 5 4 2 1 4 2 2 3 1 2 2 2 4 5 4 Output 2 1 Note Consider the first example. In the first query, we have to divide the three given nodes (7, 4 and 3), into the maximum of three groups assuming that the tree is rooted at 2. When the tree is rooted at 2, 4 is an ancestor of both 3 and 7. So we can't put all the nodes into one group. There is only 1 way to divide the given nodes into two groups, which are [4] and [3, 7]. Also, there is only one way to divide the given nodes into three groups, which are [7], [4] and [3]. So, there are total 2 ways to divide the given nodes into a maximum of three groups. In the second query, when the tree is rooted at 4, 6 is an ancestor of 2 and 2 is an ancestor of 1. So, we can't put all the given nodes into one group. Submitted Solution: ``` import operator as op from functools import reduce class Node: def __init__(self, number): self.__number = number self.__relatives = 0 self.__connected_nodes = [] self.__children_nodes = [] self.__unrelated_nodes = [] self.__is_root = False self.__node_towards_root = None self.__distance_to_root = None def add_connection(self, node): if node not in self.__connected_nodes: self.__connected_nodes.append(node) def add_relative(self): self.__relatives += 1 def clear_relatives(self): self.__relatives = 0 def get_relatives(self): return self.__relatives def add_unrelated_node(self, node): self.__unrelated_nodes.append(node) def clear_unrelated_nodes(self): self.__unrelated_nodes = [] def get_number(self): return self.__number def get_connections(self): return self.__connected_nodes def get_number_of_connections(self): return len(self.__connected_nodes) def has_child(self): return False if len(self.__connected_nodes) == 1 else True def is_root(self): return self.__is_root def set_root(self): self.__is_root = True def unset_root(self): self.__is_root = False def get_node_to_root(self): return self.__node_towards_root def set_node_to_root(self, node): self.__node_towards_root = node for connode in self.__connected_nodes: if connode is not node: self.__children_nodes.append(connode) def unset_node_to_root(self): self.__node_towards_root = None self.__children_nodes = [] def get_distance_to_root(self): return self.__distance_to_root def set_distance_to_root(self, distance): self.__distance_to_root = distance def get_children(self): return self.__children_nodes class Tree: def __init__(self, num_nodes): self.__nodes = [] self.__connections = [] self.__root = None for i in range(num_nodes): self.__nodes.append(Node(i + 1)) def add_connection(self, node1, node2): Node1 = self.__get_node(node1) Node2 = self.__get_node(node2) Node1.add_connection(Node2) Node2.add_connection(Node1) def __set_directions(self, rootnode=None): if rootnode is None: rootnode = self.__root rootnode.set_node_to_root(self.__root) for node in rootnode.get_connections(): if node.get_node_to_root() is None: node.set_node_to_root(rootnode) self.__set_directions(node) def __set_distances_to_root(self, count=0, startnode=None): if count == 0: startnode = self.__root startnode.set_distance_to_root(count) count += 1 for node in startnode.get_children(): self.__set_distances_to_root(count, node) else: startnode.set_distance_to_root(count) count += 1 if startnode.has_child(): for node in startnode.get_children(): self.__set_distances_to_root(count, node) def __set_relatives(self, q_nodes): for q in q_nodes: print("REMOVE ME") def __set_root(self, root): self.__get_node(root).set_root() self.__root = self.__get_node(root) self.__set_directions() self.__set_distances_to_root() def __unset_root(self): for node in self.__nodes: node.unset_root() node.unset_node_to_root() node.clear_relatives() self.__root = None def __get_node(self, node): return self.__nodes[node - 1] def __are_related(self, node1, node2): node1 = self.__get_node(node1) node2 = self.__get_node(node2) if node1 == self.__root or node2 == self.__root or node1 == node2: return True # Make Node 1 the Node with greatest distance from root: if node1.get_distance_to_root() < node2.get_distance_to_root(): temp = node2 node2 = node1 node1 = temp return self.__check_ancestry(node1, node2) def __check_ancestry(self, node1, node2): # Node 1 is the farthest from root. If Node2 exists in Node1's line, they are related. node1 = node1.get_node_to_root() if node1 == node2: return True if node1 is self.__root or node1 is None: return False return self.__check_ancestry(node1, node2) @staticmethod def __ncr(n, r): # N choose R - Provides # of possible groups that can form r = min(r, n - r) numer = reduce(op.mul, range(n, n - r, -1), 1) denom = reduce(op.mul, range(1, r + 1), 1) return numer / denom def check_connections(self): print("Connections:") for node in self.__nodes: children = "" for subnode in node.get_connections(): children += str(subnode.get_number()) + " " print("Node " + str(node.get_number()) + " is connected to: " + children) def query(self, *queryitems): # Clear current root: self.__unset_root() # Get key points: q_numnodes = int(queryitems[0]) q_maxgroups = int(queryitems[1]) q_rootnode = int(queryitems[2]) # Get nodes: q_numnodes = queryitems[-q_numnodes:] q_nodes = [] for q_node in q_numnodes: q_nodes.append(int(q_node)) # Set root: self.__set_root(q_rootnode) # self.__set_relatives(q_nodes) # Get max # of groups: theo_max = self.__ncr(len(q_numnodes), 2) + 1 # Decrement theo_max if there are and relations within the branch: # Check for relatives: i = 0 num_relations = 0 relations_in_group = [] while i < len(q_nodes): relations_in_group.append(0) j = i + 1 while j < len(q_nodes): if self.__are_related(q_nodes[i], q_nodes[j]): self.__get_node(q_nodes[i]).add_relative() self.__get_node(q_nodes[j]).add_relative() relations_in_group[i] += 1 num_relations += 1 theo_max -= 1 j += 1 i += 1 num_combinations = 0 if num_relations == q_maxgroups == 1 or num_relations > q_maxgroups: return 0 else: num_combinations += 1 times_ran_through_loop = 0 for n in range(2, q_maxgroups + 1): for i in q_nodes: if self.__get_node(i).get_relatives() > n: return 0 num_combinations += self.__ncr(len(q_numnodes), n) - relations_in_group[n-2] times_ran_through_loop += 1 if times_ran_through_loop > 1: num_combinations -= 1 if theo_max == q_maxgroups == 1: return 0 return num_combinations def run(): # Variables: tree = None tree_nodes = None num_queries = None queries = [] # Get First Line (# Nodes, Connections, and # of Queries): tree_nodes = input() tree_nodes = tree_nodes.split(" ") tree = Tree(int(tree_nodes[0])) num_queries = int(tree_nodes[1]) # Get Connections: tree_nodes = int(tree_nodes[0]) for i in range(tree_nodes - 1): connection = input() connection = connection.split(" ") tree.add_connection(int(connection[0]), int(connection[1])) # Get Queries: for i in range(num_queries): # Each query is added as a tuple into queries query = input() query = query.split(" ") queries.append(query) # Get Outputs: for query in queries: print(str(tree.query(*query))) run() ```
instruction
0
43,862
13
87,724
No
output
1
43,862
13
87,725
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree. The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): 1. Alice either moves her chip to an adjacent vertex or doesn't move it; 2. for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game. Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted. For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex. Input The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. Then n - 1 lines follow, each line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) that denote the endpoints of an edge. These edges form a tree. The next line contains one integer k (1 ≤ k ≤ n - 1) — the number of Bob's chips. The last line contains k integers a_1, a_2, ..., a_k (1 ≤ a_i ≤ n; a_i ≠ a_j if i ≠ j) — the vertices where the Bob's chips are initially placed. Output Print n integers. The i-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex i. If one of Bob's chips is already placed in vertex i, then the answer for vertex i is 0. Examples Input 5 2 4 3 1 3 4 3 5 2 4 5 Output 2 1 2 0 0 Input 8 4 1 8 4 4 5 6 4 2 5 4 3 1 7 3 2 8 3 Output 3 0 0 3 1 2 3 0 Input 10 2 5 4 3 7 3 7 2 5 8 3 6 8 10 7 9 7 1 4 10 6 9 1 Output 0 2 2 2 2 0 2 2 0 0 Submitted Solution: ``` import sys def get_lines(): lines = [] seen_no_space = 0 to_go = -1 while to_go != 0: lines.append(sys.stdin.readline()) to_go -= 1 if len(lines[-1].split()) == 1: seen_no_space += 1 if seen_no_space == 2: to_go = 1 seen_no_space = 0 return lines def get_adjacent_nodes(edges, n_vertices): result = {i + 1: set() for i in range(n_vertices)} for v1, v2 in edges: result[v1].add(v2) result[v2].add(v1) return result def parse_lines(lines): n_vertices = int(lines[0]) edges = [] for line in lines[1:-2]: edges.append(tuple(int(x) for x in line.split())) bob_vertices = [int(x) for x in lines[-1].split()] return n_vertices, edges, bob_vertices def mark_nodes(adjacents, bob_vertices, n_vertices): # set the nr of steps for bob to reach each node nodes = {x + 1: n_vertices - 1 for x in range(n_vertices)} for v in bob_vertices: nodes[v] = 0 updated = True while updated: updated = False for node in nodes: min_val = min(nodes[x] for x in adjacents[node]) if min_val + 1 < nodes[node]: updated = True nodes[node] = min_val + 1 return nodes def mark_nodes_fast(adjacents, bob_vertices): result = {} working_set = {v: 0 for v in bob_vertices} while len(working_set) > 0: new_working_set = {} result.update(working_set) for n1 in working_set: for n2 in adjacents[n1]: if n2 not in result: new_working_set[n2] = result[n1] + 1 working_set = new_working_set return result def compute_node_turns(node_marks, adjacents): result = {} for node in node_marks: reachable = {node: 0} working_set = {node: 0} while len(working_set) > 0: new_working_set = {} for r1 in working_set: for r2 in adjacents[r1]: if r2 not in reachable and node_marks[r2] > reachable[r1] + 1: new_working_set[r2] = working_set[r1] + 1 working_set = new_working_set reachable.update(working_set) result[node] = max(node_marks[r] for r in reachable) return result def compute_node_turns_fast(node_marks, adjacents): turn = max(node_marks.values()) result = {n: 0 for n in node_marks} while turn >= 0: new_result = {} for node, mark in node_marks.items(): if mark == turn: new_result[node] = turn elif mark > turn: new_result[node] = max( [mark] + [result[a] for a in adjacents[node]]) else: new_result[node] = 0 result = new_result turn -= 1 return result def test_input(size): return size, [(i, i + 1) for i in range(1, size)], [size // 2] def main(): lines = get_lines() n_vertices, edges, bob_vertices = parse_lines(lines) # n_vertices, edges, bob_vertices = test_input(10000) adjacents = get_adjacent_nodes(edges, n_vertices) #node_marks = mark_nodes(adjacents, bob_vertices, n_vertices) node_marks = mark_nodes_fast(adjacents, bob_vertices) result_map = compute_node_turns_fast(node_marks, adjacents) print(" ".join(str(x) for x in result_map.values())) if __name__ == '__main__': main() ```
instruction
0
44,047
13
88,094
No
output
1
44,047
13
88,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree. The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): 1. Alice either moves her chip to an adjacent vertex or doesn't move it; 2. for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game. Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted. For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex. Input The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. Then n - 1 lines follow, each line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) that denote the endpoints of an edge. These edges form a tree. The next line contains one integer k (1 ≤ k ≤ n - 1) — the number of Bob's chips. The last line contains k integers a_1, a_2, ..., a_k (1 ≤ a_i ≤ n; a_i ≠ a_j if i ≠ j) — the vertices where the Bob's chips are initially placed. Output Print n integers. The i-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex i. If one of Bob's chips is already placed in vertex i, then the answer for vertex i is 0. Examples Input 5 2 4 3 1 3 4 3 5 2 4 5 Output 2 1 2 0 0 Input 8 4 1 8 4 4 5 6 4 2 5 4 3 1 7 3 2 8 3 Output 3 0 0 3 1 2 3 0 Input 10 2 5 4 3 7 3 7 2 5 8 3 6 8 10 7 9 7 1 4 10 6 9 1 Output 0 2 2 2 2 0 2 2 0 0 Submitted Solution: ``` import sys def get_lines(): lines = [] seen_no_space = 0 to_go = -1 while to_go != 0: lines.append(sys.stdin.readline()) to_go -= 1 if len(lines[-1].split()) == 1: seen_no_space += 1 if seen_no_space == 2: to_go = 1 seen_no_space = 0 return lines def parse_lines(lines): n_vertices = int(lines[0]) edges = [] for line in lines[1:-2]: edges.append(tuple(int(x) for x in line.split())) bob_vertices = [int(x) for x in lines[-1].split()] return n_vertices, edges, bob_vertices def mark_nodes(edges, nodes, bob_vertices): # set the nr of steps for bob to reach each node for v in bob_vertices: nodes[v] = 0 updated = True while updated: updated = False for v1, v2 in edges: if nodes[v2] > nodes[v1] + 1: nodes[v2] = nodes[v1] + 1 updated = True elif nodes[v1] > nodes[v2] + 1: nodes[v1] = nodes[v2] + 1 updated = True def compute_node_turns(nodes, edges): # set the number of steps alice can survive at each node updated = True turns = 1 result = {k: v for k, v in nodes.items()} while updated: updated = False for v1, v2 in edges: if nodes[v2] > turns and result[v2] > result[v1] and nodes[v1] >= turns: result[v1] = result[v2] updated = True elif nodes[v1] > turns and result[v1] > result[v2] and nodes[v2] >= turns: result[v2] = result[v1] updated = True return result def main(): lines = get_lines() n_vertices, edges, bob_vertices = parse_lines(lines) nodes = {x + 1: n_vertices - 1 for x in range(n_vertices)} mark_nodes(edges, nodes, bob_vertices) result_map = compute_node_turns(nodes, edges) print(" ".join(str(x) for x in result_map.values())) if __name__ == '__main__': main() ```
instruction
0
44,048
13
88,096
No
output
1
44,048
13
88,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree. The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): 1. Alice either moves her chip to an adjacent vertex or doesn't move it; 2. for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game. Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted. For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex. Input The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. Then n - 1 lines follow, each line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) that denote the endpoints of an edge. These edges form a tree. The next line contains one integer k (1 ≤ k ≤ n - 1) — the number of Bob's chips. The last line contains k integers a_1, a_2, ..., a_k (1 ≤ a_i ≤ n; a_i ≠ a_j if i ≠ j) — the vertices where the Bob's chips are initially placed. Output Print n integers. The i-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex i. If one of Bob's chips is already placed in vertex i, then the answer for vertex i is 0. Examples Input 5 2 4 3 1 3 4 3 5 2 4 5 Output 2 1 2 0 0 Input 8 4 1 8 4 4 5 6 4 2 5 4 3 1 7 3 2 8 3 Output 3 0 0 3 1 2 3 0 Input 10 2 5 4 3 7 3 7 2 5 8 3 6 8 10 7 9 7 1 4 10 6 9 1 Output 0 2 2 2 2 0 2 2 0 0 Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) adj = [[] for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) adj[a-1].append(b-1) adj[b-1].append(a-1) k = int(input()) dist = [-1] * n a = map(int, input().split()) from collections import deque q = deque() for v in a: q.append(v-1) dist[v-1] = 0 while q: u = q.popleft() d = dist[u] for v in adj[u]: if dist[v] == -1: dist[v] = d + 1 q.append(v) out = [0] * n help = [-1] * n order = [(dist[i], i) for i in range(n)] order.sort(reverse = True, key = lambda x: x[0]) for _, start in order: if help[start] == -1: q.append(start) out[start] = dist[start] help[start] = dist[start] while q: u = q.popleft() #print(start, u) h = help[u] if help[u] > 1: for v in adj[u]: if help[v] == -1 and dist[v] > 0 and dist[v] < dist[start]: help[v] = h - 1 out[v] = dist[start] q.append(v) print(' '.join(map(str,out))) ```
instruction
0
44,049
13
88,098
No
output
1
44,049
13
88,099
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a game. They have a tree consisting of n vertices. Initially, Bob has k chips, the i-th chip is located in the vertex a_i (all these vertices are unique). Before the game starts, Alice will place a chip into one of the vertices of the tree. The game consists of turns. Each turn, the following events happen (sequentially, exactly in the following order): 1. Alice either moves her chip to an adjacent vertex or doesn't move it; 2. for each Bob's chip, he either moves it to an adjacent vertex or doesn't move it. Note that this choice is done independently for each chip. The game ends when Alice's chip shares the same vertex with one (or multiple) of Bob's chips. Note that Bob's chips may share the same vertex, even though they are in different vertices at the beginning of the game. Alice wants to maximize the number of turns, Bob wants to minimize it. If the game ends in the middle of some turn (Alice moves her chip to a vertex that contains one or multiple Bob's chips), this turn is counted. For each vertex, calculate the number of turns the game will last if Alice places her chip in that vertex. Input The first line contains one integer n (2 ≤ n ≤ 2 ⋅ 10^5) — the number of vertices in the tree. Then n - 1 lines follow, each line contains two integers u_i, v_i (1 ≤ u_i, v_i ≤ n; u_i ≠ v_i) that denote the endpoints of an edge. These edges form a tree. The next line contains one integer k (1 ≤ k ≤ n - 1) — the number of Bob's chips. The last line contains k integers a_1, a_2, ..., a_k (1 ≤ a_i ≤ n; a_i ≠ a_j if i ≠ j) — the vertices where the Bob's chips are initially placed. Output Print n integers. The i-th of them should be equal to the number of turns the game will last if Alice initially places her chip in the vertex i. If one of Bob's chips is already placed in vertex i, then the answer for vertex i is 0. Examples Input 5 2 4 3 1 3 4 3 5 2 4 5 Output 2 1 2 0 0 Input 8 4 1 8 4 4 5 6 4 2 5 4 3 1 7 3 2 8 3 Output 3 0 0 3 1 2 3 0 Input 10 2 5 4 3 7 3 7 2 5 8 3 6 8 10 7 9 7 1 4 10 6 9 1 Output 0 2 2 2 2 0 2 2 0 0 Submitted Solution: ``` import sys def get_lines(): lines = [] seen_no_space = 0 to_go = -1 while to_go != 0: lines.append(sys.stdin.readline()) to_go -= 1 if len(lines[-1].split()) == 1: seen_no_space += 1 if seen_no_space == 2: to_go = 1 seen_no_space = 0 return lines def parse_lines(lines): n_vertices = int(lines[0]) edges = [] for line in lines[1:-2]: edges.append(tuple(int(x) for x in line.split())) bob_vertices = [int(x) for x in lines[-1].split()] return n_vertices, edges, bob_vertices def mark_nodes(edges, nodes, bob_vertices): # set the nr of steps for bob to reach each node for v in bob_vertices: nodes[v] = 0 updated = True while updated: updated = False for v1, v2 in edges: if nodes[v2] > nodes[v1] + 1: nodes[v2] = nodes[v1] + 1 updated = True elif nodes[v1] > nodes[v2] + 1: nodes[v1] = nodes[v2] + 1 updated = True def compute_node_turns(nodes, edges): # set the number of steps alice can survive at each node updated = True turns = 1 result = {k: v for k, v in nodes.items()} while updated: updated = False for v1, v2 in edges: if nodes[v2] > turns and result[v2] > result[v1]: result[v1] = result[v2] updated = True elif nodes[v1] > turns and result[v1] > result[v2]: result[v2] = result[v1] updated = True return result def main(): lines = get_lines() n_vertices, edges, bob_vertices = parse_lines(lines) nodes = {x + 1: n_vertices - 1 for x in range(n_vertices)} mark_nodes(edges, nodes, bob_vertices) result_map = compute_node_turns(nodes, edges) print(" ".join(str(x) for x in result_map.values())) if __name__ == '__main__': main() ```
instruction
0
44,050
13
88,100
No
output
1
44,050
13
88,101
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,485
13
88,970
"Correct Solution: ``` import sys N = int(sys.stdin.buffer.readline()) AB = list(map(int, sys.stdin.buffer.read().split())) A = AB[::2] B = AB[1::2] ans = min(sum(A), sum(B)) AB.sort() pivot = AB[N-1] pivot2 = AB[N] pivot_idxs = [] pivot2_idxs = [] ans2 = sum(AB[:N]) for i, (a, b) in enumerate(zip(A, B)): if a <= pivot and b <= pivot: ans = min(ans, ans2) print(ans) exit() if a == pivot or b == pivot: pivot_idxs.append(i) if a == pivot2 or b == pivot2: pivot2_idxs.append(i) if len(pivot_idxs) == len(pivot2_idxs) == 1 and pivot_idxs[0] == pivot2_idxs[0]: ans2 = min( ans2 - pivot + AB[N+1], ans2 - AB[N-2] + pivot2 ) else: ans2 = ans2 - pivot + pivot2 ans = min(ans, ans2) print(ans) ```
output
1
44,485
13
88,971
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,486
13
88,972
"Correct Solution: ``` N = int(input()) A = [] B = [] Sa = 0 Sb = 0 for i in range(N): a,b = map(int,input().split()) A.append([a,i]) B.append([b,i]) Sa += a Sb += b C = sorted(A+B) ind = [] ans = 0 for i in range(N): ind.append(C[i][1]) ans += C[i][0] ind = set(ind) if len(ind) == N: if C[N-1][1] != C[N][1]: ans += C[N][0]-C[N-1][0] else: ans += min(C[N][0]-C[N-2][0],C[N+1][0]-C[N-1][0]) ans = min(Sa,Sb,ans) print(ans) ```
output
1
44,486
13
88,973
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,487
13
88,974
"Correct Solution: ``` # C from heapq import heappush, heappop N = int(input()) values = [0]*(2*N) for i in range(N): A, B = map(int, input().split()) values[i] = A values[i+N] = B def argsort(R_arr): N = len(R_arr) R_args = [0]*N R_vars = [0]*N h = [] for i in range(N): heappush(h, (R_arr[i], i)) for i in range(N): a, b = heappop(h) R_args[i] = b R_vars[i] = a return R_vars, R_args values_sorted, args = argsort(values) # check for rare case picked = [0]*N for i in range(N): picked[args[i] % N] = 1 if sum(picked) == N: if args[N-1] % N == args[N] % N: res1 = sum(values_sorted[:(N-1)]) + values_sorted[N+1] res2 = sum(values_sorted[:(N+1)]) - values_sorted[N-2] res = min(res1, res2) else: res = sum(values_sorted[:(N-1)]) + values_sorted[N] res3 = sum(values[:N]) res4 = sum(values[N:]) res = min(res, res3, res4) else: res = sum(values_sorted[:N]) print(res) ```
output
1
44,487
13
88,975
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,488
13
88,976
"Correct Solution: ``` n = int(input()) edge = [] num_list = [] for i in range(n): a, b = map(int, input().split()) edge.append([a, b]) num_list.append(a) num_list.append(b) num_list.sort() K = num_list[n-1] ab = [] ax = [] xb = [] for i in range(n): a, b = edge[i] if a <= K and b <= K: ab.append(edge[i]) elif a <= K: ax.append(edge[i]) elif b <= K: xb.append(edge[i]) if len(ab) > 0: ans = sum(num_list[:n]) elif len(ax) == n or len(xb) == n: ans = sum(num_list[:n]) else: yabai_edge = num_list[n-1:n+1] if edge.count(yabai_edge) + edge.count(yabai_edge[::-1]) == 0: diff = num_list[n] - num_list[n-1] elif len(ax) == 1 and edge.count(yabai_edge) == 1: diff = num_list[n] - num_list[n-1] elif len(xb) == 1 and edge.count(yabai_edge[::-1]) == 1: diff = num_list[n] - num_list[n-1] else: diff = min(num_list[n+1]-num_list[n-1], num_list[n]-num_list[n-2]) ans = sum(num_list[:n]) + diff print(ans) ```
output
1
44,488
13
88,977
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,489
13
88,978
"Correct Solution: ``` n = int(input()) c = [] not_c = [] chosen = set() ans = 0 for i in range(n): a, b = map(int, input().split()) not_c.append([max(a, b), i]) c.append([min(a, b), i]) ans += min(a, b) if a < b: chosen.add("a") elif a > b: chosen.add("b") if len(chosen) < 2: print(ans) else: c = sorted(c, reverse=True) not_c = sorted(not_c) #print(c, not_c) #used_c = [False] * n #used_n = [False] * n if c[0][1] != not_c[0][1]: ans = ans - c[0][0] + not_c[0][0] c_cur = 1 not_cur = 1 else: ans = min(ans - c[1][0] + not_c[0][0], ans - c[0][0] + not_c[1][0]) if ans - c[1][0] + not_c[0][0] <= ans - c[0][0] + not_c[1][0]: c_cur = 2 not_cur = 1 else: c_cur = 1 not_cur = 2 if c_cur < n and not_cur < n: while c[c_cur][0] > not_c[not_cur][0]: if c[c_cur][1] != not_c[not_cur][1]: ans = ans - c[c_cur][0] + not_c[not_cur][0] c_cur += 1 not_cur += 1 else: ans = min(ans - c[c_cur+1][0] + not_c[not_cur][0], ans - c[c_cur][0] + not_c[not_cur+1][0]) if ans - c[c_cur+1][0] + not_c[not_cur][0] <= ans - c[c_cur][0] + not_c[not_cur+1][0]: c_cur += 2 not_cur += 1 else: c_cur += 1 not_cur += 2 if c_cur >= n or not_cur >= n: break print(ans) ```
output
1
44,489
13
88,979
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,490
13
88,980
"Correct Solution: ``` N=int(input()) A=[] node=[] for i in range(N): x,y=map(int,input().split()) A.append((x,i,"left")) A.append((y,i,"right")) node.append((x,y)) A.sort() Used=[[False,False] for i in range(N)] Used_node=0 for i in range(N): if A[i][2]=="left": Used[A[i][1]][0]=True if not Used[A[i][1]][1]: Used_node+=1 if A[i][2]=="right": Used[A[i][1]][1]=True if not Used[A[i][1]][0]: Used_node+=1 if Used_node!=N: ans=0 for i in range(N): ans+=A[i][0] print(ans) else: if Used[0][0]: f=0 else: f=1 NO=0 for i in range(N): if not Used[i][f]: NO=1 break ans=0 for i in range(N): ans+=A[i][0] ans2=float("inf") if NO==1: for w in range(N): if A[N][1]==w: ans2=min(ans2,ans-min(node[w])+A[N+1][0]) else: ans2=min(ans2,ans-min(node[w])+A[N][0]) print(ans2) exit() print(ans) ```
output
1
44,490
13
88,981
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,491
13
88,982
"Correct Solution: ``` N=int(input());A=[-1]*N;B=[-1]*N for i in range(N):A[i],B[i]=map(int,input().split()) ans=min(sum(A),sum(B));t=[(A[i],i) for i in range(N)]+[(B[i],i) for i in range(N)];t.sort();d=[0]*N for i in range(N):d[t[i][1]]+=1 S=sum(t[i][0] for i in range(N)) if max(d)==2: print(S) else: ans2=min(S+max(A[i],B[i])-t[N-1-(t[N-1][1]==i)][0] for i in range(N)) print(min(ans,ans2)) ```
output
1
44,491
13
88,983
Provide a correct Python 3 solution for this coding contest problem. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227
instruction
0
44,492
13
88,984
"Correct Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) n=int(input()) Cost=[] s1,s2=0,0 for i in range(n): a,b=map(int,input().split()) s1+=a s2+=b Cost.append([a,i]) Cost.append([b,i]) Cost.sort() s3=sum([Cost[i][0] for i in range(n)]) if len(set([Cost[i][1] for i in range(n)]))==n: if Cost[n-1][1]==Cost[n][1]: s3+=min(Cost[n+1][0]-Cost[n-1][0],Cost[n][0]-Cost[n-2][0]) else: s3+=Cost[n][0]-Cost[n-1][0] print(min(s1,s2,s3)) ```
output
1
44,492
13
88,985
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` import sys readline = sys.stdin.readline N = int(readline()) AB = [tuple(map(int, readline().split())) for _ in range(N)] A, B = map(list, zip(*AB)) ans = min(sum(A), sum(B)) C = [(A[i], i) for i in range(N)] + [(B[i], i) for i in range(N)] C.sort() table = [0]*N for i in range(N): _, idx = C[i] table[idx] += 1 if max(table) > 1: ans = min(ans, sum(c for (c, _) in C[:N])) else: MAB = list(map(max, AB)) D = [None]*N for i in range(N, 2*N): _, idx = C[i] D[idx] = i res = sum(c for (c, _) in C[:N]) for i in range(N-1): _, idx = C[i] ans = min(ans, res + MAB[idx] - C[N-1][0]) ans = min(ans, res + MAB[C[N-1][1]] - C[N-2][0]) print(ans) ```
instruction
0
44,493
13
88,986
Yes
output
1
44,493
13
88,987
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # """ AGC028 C """ from operator import itemgetter n = int(input()) abli = [] for i in range(n): a, b = map(int, input().split()) abli.append((a, i, 0)) abli.append((b, i, 1)) abli.sort(key=itemgetter(0)) tmpans0 = sum(map(itemgetter(0), abli[:n])) aiset = set([i for x, i, aorb in abli[:n] if not aorb]) biset = set([i for x, i, aorb in abli[:n] if aorb]) flag = bool(set.intersection(aiset, biset)) y, j, arob2 = abli[n] z, k, arob3 = abli[n+1] if flag: tmpans = tmpans0 else: min1 = y-max([x for x, i, aorb in abli[:n] if j != i]) min2 = z-max([x for x, i, aorb in abli[:n] if j == i]) tmpans = tmpans0 + min(min1, min2) leftsum = sum([aa for aa, i, aorb in abli if not aorb]) rightsum = sum([bb for bb, i, aorb in abli if aorb]) print(min(leftsum, rightsum, tmpans)) ```
instruction
0
44,494
13
88,988
Yes
output
1
44,494
13
88,989
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` def mincos(n,ab): aball=[] aball+=[(ab[i][0],i+1,'a') for i in range(n)] aball+=[(ab[i][1],i+1,'b') for i in range(n)] aball.sort() ans1=sum([i[0] for i in aball[:n]]) hen=aball[n][0] hen2=aball[n+1][0] d=set() t=None hantei=True for i,c,mab in aball[:n]: if t!=None and t!=mab: hantei=False if c in d: print(ans1) exit() d.add(c) t=mab if hantei: print(ans1) exit() ans2=[] for i,c,aorb in aball[:n]: if aball[n][1]!=c: ans2+=[ans1-i+hen] else: ans2+=[ans1-i+hen2] print(min(ans2)) exit() n=int(input()) print(mincos(n,[list(map(int,input().split())) for i in range(n)])) ```
instruction
0
44,495
13
88,990
Yes
output
1
44,495
13
88,991
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` import sys input = sys.stdin.readline N=int(input()) A=0 B=0 table=[] for i in range(N): a,b=map(int,input().split()) table.append((a,i)) table.append((b,i)) A+=a B+=b ans=min(A,B) table.sort() num=0 for i in range(N): num+=table[i][0] L=[0]*N #print(table) for i in range(N): c,j=table[i] if L[j]!=0: ans=min(num,ans) print(ans) #print(L) sys.exit() L[j]+=1 c,n=table[N-1] if n!=table[N][1]: num=num-table[N-1][0]+table[N][0] ans = min(num, ans) print(ans) sys.exit() num1=num-table[N-1][0]+table[N+1][0] num2=num-table[N-2][0]+table[N][0] print(min(ans,num1,num2)) ```
instruction
0
44,496
13
88,992
Yes
output
1
44,496
13
88,993
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # """ AGC028 C """ from operator import itemgetter n = int(input()) abli = [] for i in range(n): a, b = map(int, input().split()) abli.append((a, i, 0)) abli.append((b, i, 1)) abli.sort(key=itemgetter(0)) tmpans0 = sum(map(itemgetter(0),abli[:n])) alist = [] blist = [] for x, i, aorb in abli[:n]: if not aorb: alist.append(i) else: blist.append(i) flag = False for i in range(n): if i in alist and i in blist: flag = True break """ abli.sort(key=itemgetter(0)) tmpans0 = sum(map(itemgetter(0), abli[:n])) alist = [i for x, i, aorb in abli[:n] if not aorb] blist = [i for x, i, aorb in abli[:n] if aorb] flag = bool([i for i in range(n) if i in alist and i in blist]) """ y, j, arob2 = abli[n] z, k, arob3 = abli[n+1] if flag: tmpans = tmpans0 else: tmpans = 10**16 for x, i, aorb in abli[:n]: if j != i: tmp = tmpans0-x+y else: tmp = tmpans0-x+z if tmpans > tmp: tmpans = tmp leftsum = sum([a for a,i,aorb in abli if not aorb]) rightsum = sum([b for b,i,aorb in abli if aorb]) print(min(leftsum, rightsum, tmpans)) ```
instruction
0
44,497
13
88,994
No
output
1
44,497
13
88,995
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` mod = 1000000007 eps = 10**-9 def main(): import sys from heapq import heappush, heappop, heapify input = sys.stdin.buffer.readline N = int(input()) L = [] R = [] LR = [] for i in range(N): a, b = map(int, input().split()) L.append((-a, i)) R.append((b, i)) LR.append((a, b)) heapify(L) heapify(R) used = set() ans = 0 for new_id in range(N, N*2-1): while True: l_, id_L = heappop(L) l = -l_ if id_L in used: continue else: break while True: r, id_R = heappop(R) if id_R in used: continue else: break if id_L == id_R: while True: l_2, id_L2 = heappop(L) l2 = -l_2 if id_L2 in used: continue else: heappush(L, (l_, id_L)) l = l2 id_L = id_L2 break used.add(id_L) used.add(id_R) ans += min(LR[id_L][0], LR[id_R][1]) LR.append((LR[id_R][0], LR[id_L][1])) heappush(L, (-LR[id_R][0], new_id)) heappush(R, (LR[id_L][1], new_id)) ans += min(LR[-1][0], LR[-1][1]) print(ans) if __name__ == '__main__': main() ```
instruction
0
44,498
13
88,996
No
output
1
44,498
13
88,997
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` import heapq N = int(input()) _AB = [] for i in range(N): a, b = map(int, input().split()) heapq.heappush(_AB, [a, i, 0]) heapq.heappush(_AB, [b, i, 1]) AB = [] for i in range(N + 1): AB.append(heapq.heappop(_AB)) ans = sum([ab[0] for ab in AB]) cnt = 0 for ab in AB[:-1]: if ab[2] == AB[-1][2]: cnt += 1 cmp = ab if cnt == 1: if (len([ab for ab in AB if ab[1] == cmp[1]]) == 1 and len([ab for ab in AB if ab[1] == AB[-1][1]]) == 2): ans -= max(cmp[0], AB[-2][0] if AB[-2][1] != AB[-1][1] or N == 2 else AB[-3][0]) else: ans -= AB[-1][0] else: ans -= AB[-1][0] print(ans) ```
instruction
0
44,499
13
88,998
No
output
1
44,499
13
88,999
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a directed weighted graph with N vertices. Each vertex has two integers written on it, and the integers written on Vertex i are A_i and B_i. In this graph, there is an edge from Vertex x to Vertex y for all pairs 1 \leq x,y \leq N, and its weight is {\rm min}(A_x,B_y). We will consider a directed cycle in this graph that visits every vertex exactly once. Find the minimum total weight of the edges in such a cycle. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i \leq 10^9 * 1 \leq B_i \leq 10^9 * All values in input are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 A_2 B_2 : A_N B_N Output Print the minimum total weight of the edges in such a cycle. Examples Input 3 1 5 4 2 6 3 Output 7 Input 4 1 5 2 6 3 7 4 8 Output 10 Input 6 19 92 64 64 78 48 57 33 73 6 95 73 Output 227 Submitted Solution: ``` n = int(input()) c = [] not_c = [] chosen = set() ans = 0 for i in range(n): a, b = map(int, input().split()) not_c.append([max(a, b), i]) c.append([min(a, b), i]) ans += min(a, b) if a < b: chosen.add("a") elif a > b: chosen.add("b") if len(chosen) < 2: print(ans) else: c = sorted(c, reverse=True) not_c = sorted(not_c) #print(c, not_c) #used_c = [False] * n #used_n = [False] * n if c[0][1] != not_c[0][1]: ans = ans - c[0][0] + not_c[0][0] c_cur = 1 not_cur = 1 else: ans = min(ans - c[1][0] + not_c[0][0], ans - c[0][0] + not_c[1][0]) if ans - c[1][0] + not_c[0][0] <= ans - c[0][0] + not_c[1][0]: c_cur = 2 not_cur = 1 else: c_cur = 1 not_c = 2 if c_cur < n and not_cur < n: while c[c_cur][0] > not_c[not_cur][0]: if c[c_cur][1] != not_c[not_cur][1]: ans = ans - c[c_cur][0] + not_c[not_cur][0] c_cur += 1 not_cur += 1 elif c_cur == n - 1 or not_cur == n - 1: break else: ans = min(ans - c[c_cur+1][0] + not_c[not_cur][0], ans - c[c_cur][0] + not_c[not_cur+1][0]) if ans - c[c_cur+1][0] + not_c[not_cur][0] <= ans - c[c_cur][0] + not_c[not_cur+1][0]: c_cur += 2 not_cur += 1 else: c_cur += 1 not_c += 2 if c_cur >= n or not_cur >= n: break print(ans) ```
instruction
0
44,500
13
89,000
No
output
1
44,500
13
89,001
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,501
13
89,002
"Correct Solution: ``` import sys readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res def dfs(St): dist = [0]*N stack = St[:] used = [False]*N for s in St: used[s] = True while stack: vn = stack.pop() for vf in Edge[vn]: if not used[vf]: used[vf] = True dist[vf] = 1 + dist[vn] stack.append(vf) return dist N = int(readline()) Edge = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) dist0 = dfs([0]) fs = dist0.index(max(dist0)) distfs = dfs([fs]) en = distfs.index(max(distfs)) disten = dfs([en]) Dia = distfs[en] path = [] for i in range(N): if distfs[i] + disten[i] == Dia: path.append(i) if max(dfs(path)) > 1: print(-1) else: path.sort(key = lambda x: distfs[x]) cnt = 1 hold = 0 perm1 = [None]*N onpath = set(path) idx = 0 for i in range(Dia+1): vn = path[i] hold = 0 for vf in Edge[vn]: if vf in onpath: continue hold += 1 perm1[idx] = cnt + hold idx += 1 perm1[idx] = cnt idx += 1 cnt = cnt+hold+1 cnt = 1 hold = 0 perm2 = [None]*N onpath = set(path) idx = 0 for i in range(Dia+1): vn = path[Dia-i] hold = 0 for vf in Edge[vn]: if vf in onpath: continue hold += 1 perm2[idx] = cnt + hold idx += 1 perm2[idx] = cnt idx += 1 cnt = cnt+hold+1 print(*min(perm1, perm2)) ```
output
1
44,501
13
89,003
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,502
13
89,004
"Correct Solution: ``` import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline N = int(input()) VW = [[int(x)-1 for x in input().split()] for _ in range(N-1)] """ 直径に次数1の頂点が生えている """ graph = [[] for _ in range(N)] deg = [0] * N for v,w in VW: graph[v].append(w) graph[w].append(v) deg[v] += 1 deg[w] += 1 def dijkstra(start): INF = 10**10 dist = [INF] * N q = [(start,0)] while q: qq = [] for v,d in q: dist[v] = d for w in graph[v]: if dist[w] == INF: qq.append((w,d+1)) q = qq return dist dist = dijkstra(0) v = dist.index(max(dist)) dist = dijkstra(v) w = dist.index(max(dist)) diag = v,w def create_perm(start): arr = [] v = start parent = None next_p = 1 while True: n = 0 next_v = None for w in graph[v]: if w == parent: continue if next_v is None or deg[next_v] < deg[w]: next_v = w if deg[w] == 1: n += 1 if next_v is None: return arr + [next_p] if deg[next_v] == 1: n -= 1 arr += list(range(next_p+1,next_p+n+1)) arr.append(next_p) next_p += n+1 parent = v v = next_v P = create_perm(diag[1]) Q = create_perm(diag[0]) if len(P) != N: answer = -1 else: if P > Q: P = Q answer = ' '.join(map(str,P)) print(answer) ```
output
1
44,502
13
89,005
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,503
13
89,006
"Correct Solution: ``` import sys #sys.setrecursionlimit(10 ** 6) int1 = lambda x: int(x) - 1 p2D = lambda x: print(*x, sep="\n") def II(): return int(sys.stdin.readline()) def MI(): return map(int, sys.stdin.readline().split()) def MI1(): return map(int1, sys.stdin.readline().split()) def LI(): return list(map(int, sys.stdin.readline().split())) def LLI(rows_number): return [LI() for _ in range(rows_number)] def SI(): return sys.stdin.readline()[:-1] n=II() to=[[] for _ in range(n)] for _ in range(n-1): u,v=MI1() to[u].append(v) to[v].append(u) #print(to) def far(u): stack=[(u,-1,0)] mxd=mxu=-1 while stack: u,pu,d=stack.pop() if d>mxd: mxd=d mxu=u for v in to[u]: if v==pu:continue stack.append((v,u,d+1)) return mxu,mxd s,_=far(0) t,dist=far(s) #print(s,t,dist) def makepath(u,t): stack=[(u,-1)] while stack: u,pu=stack.pop() while path and path[-1]!=pu:path.pop() path.append(u) if u==t:return for v in to[u]: if v==pu:continue stack.append((v,u)) path=[s] makepath(s,t) #print(path) leg=[] for u in path[1:-1]:leg.append(len(to[u])-2) #print(leg) if sum(leg)+dist+1!=n: print(-1) exit() ans=[] ans.append(1) u=2 for l in leg: for v in range(u+1,u+1+l): ans.append(v) ans.append(u) u+=l+1 ans.append(u) leg.reverse() ans2=[] ans2.append(1) u=2 for l in leg: for v in range(u+1,u+1+l): ans2.append(v) ans2.append(u) u+=l+1 ans2.append(u) if ans2<ans:ans=ans2 print(*ans) ```
output
1
44,503
13
89,007
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,504
13
89,008
"Correct Solution: ``` #!/usr/bin/env python3 def solve(n, adj_list, d): s = [] path_adj_list = [[] for _ in range(n)] for v in range(n): if 1 < d[v]: p = path_adj_list[v] for w in adj_list[v]: if 1 < d[w]: p.append(w) if 2 < len(p): print(-1) return if len(p) == 1: s.append(v) if len(s) == 0: ans = [1] + [v for v in range(3, n)] + [2] if 2 < n: ans += [n] print(' '.join(list(map(str, ans)))) return visited = [False] * n v, w = s while v != w and d[v] == d[w]: visited[v] = True visited[w] = True f = False for nv in path_adj_list[v]: if not visited[nv]: f = True v = nv break if not f: break f = False for nw in path_adj_list[w]: if not visited[nw]: f = True w = nw break if not f: break if d[v] > d[w]: v = s[1] else: v = s[0] visited = [False] * n visited[v] = True ans = [1] + [w for w in range(3, d[v] + 1)] + [2] c = d[v] v = path_adj_list[v][0] while True: visited[v] = True ans += [w for w in range(c + 2, c + d[v])] + [c + 1] c += d[v] - 1 f = False for nv in path_adj_list[v]: if not visited[nv]: f = True v = nv break if not f: break ans += [n] print(' '.join(list(map(str, ans)))) return def main(): n = input() n = int(n) adj_list = [[] for _ in range(n)] d = [0] * n for _ in range(n - 1): v, w = input().split() v = int(v) - 1 w = int(w) - 1 adj_list[v].append(w) adj_list[w].append(v) d[v] += 1 d[w] += 1 solve(n, adj_list, d) if __name__ == '__main__': main() ```
output
1
44,504
13
89,009
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,505
13
89,010
"Correct Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(2*10**5) n=int(input()) edge=[[] for i in range(n)] for i in range(n-1): v,w=map(int,input().split()) edge[v-1].append(w-1) edge[w-1].append(v-1) if n==2: exit(print(1,2)) leafcnt=[0]*n for v in range(n): for nv in edge[v]: if len(edge[nv])==1: leafcnt[v]+=1 used=[False]*n line=[] def line_check(v): used[v]=True line.append(leafcnt[v]) flag=False for nv in edge[v]: if not used[nv] and len(edge[nv])!=1: if not flag: line_check(nv) flag=True else: return False return True for v in range(n): if not used[v] and len(edge[v])-leafcnt[v]<=1 and len(edge[v])!=1: if not line: check=line_check(v) if not check: exit(print(-1)) else: exit(print(-1)) line_rev=line[::-1] res=min(line,line_rev) res=[0]+res+[0] res[1]-=1 res[-2]-=1 ans=[] L=1 for val in res: R=L+val for i in range(L+1,R+1): ans.append(i) ans.append(L) L=R+1 print(*ans) ```
output
1
44,505
13
89,011
Provide a correct Python 3 solution for this coding contest problem. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1
instruction
0
44,506
13
89,012
"Correct Solution: ``` import sys from collections import deque def diameter(n, links): q = deque([(0, -1)]) v = 0 while q: v, p = q.popleft() q.extend((u, v) for u in links[v] if u != p) q = deque([(v, -1)]) w = 0 parents = [-1] * n while q: w, p = q.popleft() parents[w] = p q.extend((u, w) for u in links[w] if u != p) parents_rev = [-1] * n p = w while parents[p] != -1: parents_rev[parents[p]] = p p = parents[p] return v, w, parents, parents_rev def construct(s, links, parents, parents_rev): v = s result = [] while v != -1: pv, rv = parents[v], parents_rev[v] child_count = 0 for u in links[v]: if u == pv or u == rv: continue if len(links[u]) != 1: return False child_count += 1 my_value = len(result) + 1 result.extend(range(my_value + 1, my_value + child_count + 1)) result.append(my_value) v = parents[v] return result def solve(n, links): d1, d2, parents, parents_rev = diameter(n, links) result1 = construct(d1, links, parents_rev, parents) if result1 is False: return [-1] result2 = construct(d2, links, parents, parents_rev) return min(result1, result2) n = int(input()) links = [set() for _ in range(n)] INF = 10 ** 9 for line in sys.stdin: v, w = map(int, line.split()) v -= 1 w -= 1 links[v].add(w) links[w].add(v) print(*solve(n, links)) ```
output
1
44,506
13
89,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1 Submitted Solution: ``` import sys input = sys.stdin.readline N = int(input()) VW = [[int(x)-1 for x in input().split()] for _ in range(N-1)] """ 直径に次数1の頂点が生えている """ graph = [[] for _ in range(N)] deg = [0] * N for v,w in VW: graph[v].append(w) graph[w].append(v) deg[v] += 1 deg[w] += 1 def dijkstra(start): INF = 10**10 dist = [INF] * N q = [(start,0)] while q: qq = [] for v,d in q: dist[v] = d for w in graph[v]: if dist[w] == INF: qq.append((w,d+1)) q = qq return dist dist = dijkstra(0) v = dist.index(max(dist)) dist = dijkstra(v) w = dist.index(max(dist)) diag = v,w def create_perm(v,parent,next_p,arr): next_v = None V1 = [] V2 = [] for w in graph[v]: if w == parent: continue if deg[w] == 1: V1.append(w) else: V2.append(w) if len(V1) == 0 and len(V2) == 0: arr.append(next_p) return if len(V2) > 0: next_v = V2[0] else: next_v = V1[-1] V1 = V1[:-1] arr += list(range(next_p+1,next_p+len(V1)+1)) arr.append(next_p) next_p += len(V1)+1 create_perm(next_v,v,next_p,arr) P = [] create_perm(diag[1],None,1,P) Q = [] create_perm(diag[0],None,1,Q) if len(P) != N: answer = -1 else: if P > Q: P = Q answer = ' '.join(map(str,P)) print(answer) ```
instruction
0
44,507
13
89,014
No
output
1
44,507
13
89,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1 Submitted Solution: ``` import sys readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res def dfs(St): dist = [0]*N stack = St[:] used = [False]*N for s in St: used[s] = True while stack: vn = stack.pop() for vf in Edge[vn]: if not used[vf]: used[vf] = True dist[vf] = 1 + dist[vn] stack.append(vf) return dist N = int(readline()) Edge = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) dist0 = dfs([0]) fs = dist0.index(max(dist0)) distfs = dfs([fs]) en = distfs.index(max(distfs)) disten = dfs([en]) Dia = distfs[en] if Dia <= 2: print(*list(range(1, N+1))) else: path = [] for i in range(N): if distfs[i] + disten[i] == Dia: path.append(i) if max(dfs(path)) > 1: print(-1) else: path.sort(key = lambda x: distfs[x]) cnt = 1 hold = 0 perm1 = [None]*N onpath = set(path) idx = 0 for i in range(Dia+1): vn = path[i] hold = 0 for vf in Edge[vn]: if vf in onpath: continue hold += 1 perm1[idx] = cnt + hold idx += 1 perm1[idx] = cnt idx += 1 cnt = cnt+hold+1 cnt = 1 hold = 0 perm2 = [None]*N onpath = set(path) idx = 0 for i in range(Dia+1): vn = path[Dia-i] hold = 0 for vf in Edge[vn]: if vf in onpath: continue hold += 1 perm2[idx] = cnt + hold idx += 1 perm2[idx] = cnt idx += 1 cnt = cnt+hold+1 print(*min(perm1, perm2)) ```
instruction
0
44,508
13
89,016
No
output
1
44,508
13
89,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1 Submitted Solution: ``` import sys input = sys.stdin.readline N = int(input()) VW = [[int(x)-1 for x in input().split()] for _ in range(N-1)] """ 直径に次数1の頂点が生えている """ graph = [[] for _ in range(N)] deg = [0] * (N) for v,w in VW: graph[v].append(w) graph[w].append(v) deg[v] += 1 deg[w] += 1 def dijkstra(start): INF = 10**10 dist = [INF] * N q = [(start,0)] while q: qq = [] for v,d in q: dist[v] = d for w in graph[v]: if dist[w] == INF: qq.append((w,d+1)) q = qq return dist dist = dijkstra(0) v = dist.index(max(dist)) dist = dijkstra(v) w = dist.index(max(dist)) diag = v,w ```
instruction
0
44,509
13
89,018
No
output
1
44,509
13
89,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Takahashi has an ability to generate a tree using a permutation (p_1,p_2,...,p_n) of (1,2,...,n), in the following process: First, prepare Vertex 1, Vertex 2, ..., Vertex N. For each i=1,2,...,n, perform the following operation: * If p_i = 1, do nothing. * If p_i \neq 1, let j' be the largest j such that p_j < p_i. Span an edge between Vertex i and Vertex j'. Takahashi is trying to make his favorite tree with this ability. His favorite tree has n vertices from Vertex 1 through Vertex n, and its i-th edge connects Vertex v_i and w_i. Determine if he can make a tree isomorphic to his favorite tree by using a proper permutation. If he can do so, find the lexicographically smallest such permutation. Constraints * 2 \leq n \leq 10^5 * 1 \leq v_i, w_i \leq n * The given graph is a tree. Input Input is given from Standard Input in the following format: n v_1 w_1 v_2 w_2 : v_{n-1} w_{n-1} Output If there is no permutation that can generate a tree isomorphic to Takahashi's favorite tree, print `-1`. If it exists, print the lexicographically smallest such permutation, with spaces in between. Examples Input 6 1 2 1 3 1 4 1 5 5 6 Output 1 2 4 5 3 6 Input 6 1 2 2 3 3 4 1 5 5 6 Output 1 2 3 4 5 6 Input 15 1 2 1 3 2 4 2 5 3 6 3 7 4 8 4 9 5 10 5 11 6 12 6 13 7 14 7 15 Output -1 Submitted Solution: ``` print(-1) ```
instruction
0
44,510
13
89,020
No
output
1
44,510
13
89,021
Provide tags and a correct Python 3 solution for this coding contest problem. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them.
instruction
0
44,646
13
89,292
Tags: bitmasks, graphs, interactive Correct Solution: ``` import sys def req(a, b): if a == [] or b == []: return -1 print(len(a), len(b),*a,*b) sys.stdout.flush() return int(input()) def br(r, l, d): if d == 1: return list(range(r, (r + l)//2)), list(range((r+l)//2, l)) a, b, c, d = *br(r, (r + l)//2, d-1), *br((r+l)//2, l, d-1) return a + c, b + d def main(n): m = 0 for i in range(1, 10): a, b = br(1, n+1,i) if a == [] or b == []: continue r = req(a, b) if r == -1: return -1 m = max(m, r) return m try: t = int(input()) for i in range(t): u = int(input()) if u == -1: break k = main(u) if k == -1: break print(-1, k) sys.stdout.flush() except: pass ```
output
1
44,646
13
89,293
Provide tags and a correct Python 3 solution for this coding contest problem. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them.
instruction
0
44,647
13
89,294
Tags: bitmasks, graphs, interactive Correct Solution: ``` # AC import sys class Main: def __init__(self): self.buff = None self.index = 0 def next(self): if self.buff is None or self.index == len(self.buff): self.buff = sys.stdin.readline().split() self.index = 0 val = self.buff[self.index] self.index += 1 return val def next_int(self): return int(self.next()) def q(self, a, b, c): print(1, c - b + 1, a, ' '.join([str(x) for x in range(b, c + 1)])) sys.stdout.flush() return self.next_int() def a(self, a, n): print(1, n - 1, a, ' '.join([str(x) for x in filter(lambda x: x != a, range(1, n + 1))])) sys.stdout.flush() return self.next_int() def solve(self): for _ in range(0, self.next_int()): n = self.next_int() d1 = self.q(1, 2, n) low = 2 high = n while high > low: mid = (low + high) // 2 d2 = self.q(1, low, mid) if d2 == d1: high = mid else: low = mid + 1 dd = self.a(low, n) print(-1, dd) sys.stdout.flush() if __name__ == '__main__': Main().solve() ```
output
1
44,647
13
89,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them. Submitted Solution: ``` import sys def askquery(a,b): print (len(a),len(b),*a,*b) sys.stdout.flush() for nt in range(int(input())): n=int(input()) arr=[{} for i in range(7)] for i in range(1,n+1): b=bin(i)[2:] b="0"*(7-len(b))+b for j in range(7): if b[7-j-1]=="1": arr[j][i]=1 ans=0 for i in range(7): g1=[] g2=[] for j in range(1,n+1): if j in arr[i]: g1.append(j) else: g2.append(j) askquery(g1,g2) ans=max(ans,int(input())) print (-1,ans) ```
instruction
0
44,648
13
89,296
No
output
1
44,648
13
89,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them. Submitted Solution: ``` from sys import stdout def query(a, b): print(len(a), len(b), ' '.join(map(str, a)), ' '.join(map(str, b))) stdout.flush() return int(input()) t = int(input()) for k in range(t): n = int(input()) low = 2 high = n m = query([1], list(range(2, n + 1))) while low < high: mid = (low + high) // 2 q = query([1], list(range(low, mid + 1))) if q == m: high = mid else: low = mid + 1 assert low == high print( query([low], [i for i in range(1, n + 1) if i != low]) ) ```
instruction
0
44,649
13
89,298
No
output
1
44,649
13
89,299
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them. Submitted Solution: ``` from sys import stdout m = [([], []) for i in range(9)] for c in range(16): w = c for i in range(9): m[i][w % 2].append(c + 1) w //= 2 # print(m) def ask(i, n): a = [str(c) for c in m[i][0] if c <= n] b = [str(c) for c in m[i][1] if c <= n] if len(a) == 0 or len(b) == 0: return 0 else: print(len(a), len(b), ' '.join(a), ' '.join(b)) stdout.flush() return int(input()) def solve(n): res = 0 for i in range(9): res = max(res, ask(i, n)) return res t = int(input()) for _ in range(t): n = int(input()) ans = solve(n) print(-1, ans) stdout.flush() ```
instruction
0
44,650
13
89,300
No
output
1
44,650
13
89,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a weighted tree with n nodes and n-1 edges. The nodes are conveniently labeled from 1 to n. The weights are positive integers at most 100. Define the distance between two nodes to be the sum of edges on the unique path between the nodes. You would like to find the diameter of the tree. Diameter is the maximum distance between a pair of nodes. Unfortunately, the tree isn't given to you, but you can ask some questions about it. In one question, you can specify two nonempty disjoint sets of nodes p and q, and the judge will return the maximum distance between a node in p and a node in q. In the words, maximum distance between x and y, where x ∈ p and y ∈ q. After asking not more than 9 questions, you must report the maximum distance between any pair of nodes. Interaction Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 1 000). Description of the test cases follows. The first line of each test case contains an integer n (2 ≤ n ≤ 100) — the number of nodes in the tree. To ask a question, print "k_1\ k_2\ a_1\ a_2\ …\ a_{k_1}\ b_1\ b_2\ …\ b_{k_2}" (k_1, k_2 ≥ 1 and k_1+k_2 ≤ n). These two sets must be nonempty and disjoint. The judge will respond with a single integer max_{p,q} dist(a_p, b_q). If you ever get a result of -1 (because you printed an invalid query), exit immediately to avoid getting other verdicts. After printing a query do not forget to output end of line and flush the output. Otherwise, you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. When you are ready to answer, print "-1\ d", where d is the maximum shortest distance over all pairs of nodes. You can only ask at most 9 questions per test case. Hack Format To hack, use the following format. Note that you can only hack with one test case. The first line should contain a single integer t (t=1). The second line should contain a single integer n (2 ≤ n ≤ 100). Each of the next n-1 lines should contain three integers a_i, b_i, c_i (1≤ a_i, b_i≤ n, 1 ≤ c_i ≤ 100). This denotes an undirected edge between nodes a_i and b_i with weight c_i. These edges must form a tree. Example Input 2 5 9 6 10 9 10 2 99 Output 1 4 1 2 3 4 5 1 4 2 3 4 5 1 1 4 3 4 5 1 2 1 4 4 5 1 2 3 1 4 5 1 2 3 4 -1 10 1 1 1 2 -1 99 Note In the first example, the first tree looks as follows: <image> In the first question, we have p = {1}, and q = {2, 3, 4, 5}. The maximum distance between a node in p and a node in q is 9 (the distance between nodes 1 and 5). The second tree is a tree with two nodes with an edge with weight 99 between them. Submitted Solution: ``` from sys import stdout from random import shuffle def solve(): n = int(input()) best = -1 for q in range(9): A = [0 for _ in range(n)] for i in range(len(A)): if i & pow(2, q): A[i] = 1 x = A.count(0) y = A.count(1) out = [x, y] for i in range(len(A)): if A[i] == 0: out.append(i + 1) for i in range(len(A)): if A[i] == 1: out.append(i + 1) print(' '.join(map(str, out))) stdout.flush() dist = int(input()) best = max(best, dist) print(-1, best) t = int(input()) for _ in range(t): solve() ```
instruction
0
44,651
13
89,302
No
output
1
44,651
13
89,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number of nodes and edges as the old graph. * The properties in the first paragraph still hold. * For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible. Input The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v. Output If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format. Examples Input 8 7 1 2 2 3 4 5 5 6 6 8 8 7 7 4 Output 1 4 4 6 1 6 2 7 7 5 8 5 2 8 Input 3 2 1 2 2 3 Output -1 Input 5 4 1 2 2 3 3 4 4 1 Output 1 3 3 5 5 2 2 4 Note The old graph of the first example: <image> A possible new graph for the first example: <image> In the second example, we cannot create any new graph. The old graph of the third example: <image> A possible new graph for the third example: <image> Submitted Solution: ``` import random, time t1 = time.time() n, m = map(int, input().split()) wrong = [frozenset(map(int, input().split())) for _ in range(m)] arr = [_ + 1 for _ in range(n)] #print(arr) #for _ in wrong: while time.time() - t1 < 2.8: random.shuffle(arr) if all(frozenset()not in wrong for i in range(m)): for i in range(m): print(arr[i], arr[i-1]) break else: print("-1") ```
instruction
0
44,895
13
89,790
No
output
1
44,895
13
89,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number of nodes and edges as the old graph. * The properties in the first paragraph still hold. * For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible. Input The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v. Output If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format. Examples Input 8 7 1 2 2 3 4 5 5 6 6 8 8 7 7 4 Output 1 4 4 6 1 6 2 7 7 5 8 5 2 8 Input 3 2 1 2 2 3 Output -1 Input 5 4 1 2 2 3 3 4 4 1 Output 1 3 3 5 5 2 2 4 Note The old graph of the first example: <image> A possible new graph for the first example: <image> In the second example, we cannot create any new graph. The old graph of the third example: <image> A possible new graph for the third example: <image> Submitted Solution: ``` import random n, m = map(int, input().split()) wrong = [(map(int, input().split())) for _ in range(m)] arr = [_ + 1 for _ in range(n)] #print(arr) #for _ in wrong: fail = False for _ in range(98765): random.shuffle(arr) fail = False for i in range(m): if (arr[i], arr[i-1]) in wrong or (arr[i-1], arr[i]) in wrong: fail = True break if not fail: for i in range(m): print (str(arr[i])+" "+ str(arr[i-1])) break if fail: print("-1") ```
instruction
0
44,896
13
89,792
No
output
1
44,896
13
89,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number of nodes and edges as the old graph. * The properties in the first paragraph still hold. * For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible. Input The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v. Output If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format. Examples Input 8 7 1 2 2 3 4 5 5 6 6 8 8 7 7 4 Output 1 4 4 6 1 6 2 7 7 5 8 5 2 8 Input 3 2 1 2 2 3 Output -1 Input 5 4 1 2 2 3 3 4 4 1 Output 1 3 3 5 5 2 2 4 Note The old graph of the first example: <image> A possible new graph for the first example: <image> In the second example, we cannot create any new graph. The old graph of the third example: <image> A possible new graph for the third example: <image> Submitted Solution: ``` import random, time n, m = map(int, input().split()) wrong = set([tuple((map(int, input().split()))) for _ in range(m)]) arr = [_ + 1 for _ in range(n)] #print(arr) #for _ in wrong: random.seed(12321) t1 = time.time() fail = False while time.time() - t1 < 2.75: random.shuffle(arr) fail = False for i in range(m): if (arr[i], arr[i-1]) in wrong or (arr[i-1], arr[i]) in wrong: fail = True break if not fail: for i in range(m): print (arr[i], arr[i-1]) break if fail: print("-1") ```
instruction
0
44,897
13
89,794
No
output
1
44,897
13
89,795
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. I have an undirected graph consisting of n nodes, numbered 1 through n. Each node has at most two incident edges. For each pair of nodes, there is at most an edge connecting them. No edge connects a node to itself. I would like to create a new graph in such a way that: * The new graph consists of the same number of nodes and edges as the old graph. * The properties in the first paragraph still hold. * For each two nodes u and v, if there is an edge connecting them in the old graph, there is no edge connecting them in the new graph. Help me construct the new graph, or tell me if it is impossible. Input The first line consists of two space-separated integers: n and m (1 ≤ m ≤ n ≤ 105), denoting the number of nodes and edges, respectively. Then m lines follow. Each of the m lines consists of two space-separated integers u and v (1 ≤ u, v ≤ n; u ≠ v), denoting an edge between nodes u and v. Output If it is not possible to construct a new graph with the mentioned properties, output a single line consisting of -1. Otherwise, output exactly m lines. Each line should contain a description of edge in the same way as used in the input format. Examples Input 8 7 1 2 2 3 4 5 5 6 6 8 8 7 7 4 Output 1 4 4 6 1 6 2 7 7 5 8 5 2 8 Input 3 2 1 2 2 3 Output -1 Input 5 4 1 2 2 3 3 4 4 1 Output 1 3 3 5 5 2 2 4 Note The old graph of the first example: <image> A possible new graph for the first example: <image> In the second example, we cannot create any new graph. The old graph of the third example: <image> A possible new graph for the third example: <image> Submitted Solution: ``` import random, time n, m = map(int, input().split()) wrong = set([tuple((map(int, input().split()))) for _ in range(m)]) arr = [_ + 1 for _ in range(n)] #print(arr) #for _ in wrong: random.seed(11261) t1 = time.time() fail = False while time.time() - t1 < 2.7: random.shuffle(arr) fail = False for i in range(m): if (arr[i], arr[i-1]) in wrong or (arr[i-1], arr[i]) in wrong: fail = True break if not fail: for i in range(m): print (arr[i], arr[i-1]) break if fail: print("-1") ```
instruction
0
44,898
13
89,796
No
output
1
44,898
13
89,797
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,931
13
89,862
Tags: greedy, math Correct Solution: ``` import sys f = sys.stdin n, m = map(int, f.readline().strip().split()) v = [int(u) for u in f.readline().strip().split()] d = [{} for u in range(n)] for i in range(m): xi, yi, ei = map(int, f.readline().strip().split()) d[yi-1][xi-1] = ei d[xi-1][yi-1] = ei def ff(i,s): for k in d[i]: #print('loc ', i, d, k, s) if rt[k]==0: rt[k] = s dlist[k] = 1 ff(k,s) #print('loc1 ', i, d, k, s) s = 0 rt = [0 for u in range(n)] glist = [] for i in range(n): if rt[i]==0: s += 1 dlist = {} rt[i] = s dlist[i] = 1 ff(i,s) glist.append(dlist) #print('gl ', rt, d, i, s) roMax = 0.0 t_ro = 0.0 ro = 0.0 for g in glist: if len(g)>1: #print(g) for gi in g: for u in d[gi]: if u in g: t_ro = (v[gi] + v[u])/d[gi][u] #print(' - ', ro, t_ro, gi, u) if t_ro>ro: #print(ro, t_ro, g, gi, u) ro = t_ro graf = [gi, u] print(ro) ```
output
1
44,931
13
89,863
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,932
13
89,864
Tags: greedy, math Correct Solution: ``` n, m = map(int, input().split()) x = [int(c) for c in input().split()] ans = 0 for _ in range(m): a, b, c = map(int, input().split()) ans = max(ans, (x[a - 1] + x[b - 1]) / c) print(ans) ```
output
1
44,932
13
89,865
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,933
13
89,866
Tags: greedy, math Correct Solution: ``` import math def solve(): n, m = [int(i) for i in input().split()] vw = [int(i) for i in input().split()] M = 0.0 for _ in range(m): a, b, c = [int(i) for i in input().split()] M = max(M, (vw[a - 1] + vw[b - 1]) / c) print(M) if __name__ == '__main__': solve() ```
output
1
44,933
13
89,867
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,934
13
89,868
Tags: greedy, math Correct Solution: ``` nodes, edges = map(int, input().split()) nodesValues = list(map(int,input().split())) density = 0 total = 0 for i in range(edges): node1, node2, edgeValue = map(int, input().split()) total = (nodesValues[node2-1] + nodesValues[node1-1])/edgeValue if total > density: density = total print(density) ```
output
1
44,934
13
89,869
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,935
13
89,870
Tags: greedy, math Correct Solution: ``` n, m = map(int, input().split()) v = list(map(int, input().split())) mini = 0 for i in range(m): a, b, c = map(int, input().split()) mini = max(mini, (v[a-1]+v[b-1])/c) print(mini) ```
output
1
44,935
13
89,871
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,936
13
89,872
Tags: greedy, math Correct Solution: ``` n, m = map(int, input().split(" ")) val = list(map(int, input().split(" "))) ans = 0 for i in range(m): x, y, z = map(int, input().split(" ")) ans = max(ans, (val[x-1]+val[y-1])/z) print(ans) ```
output
1
44,936
13
89,873
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,937
13
89,874
Tags: greedy, math Correct Solution: ``` nodes , edges = map(int,input().split()) x=list(map(int,input().split())) error =0 for i in range(edges): a,b,c=map(int,input().split()) error = max(error , (x[a-1]+x[b-1])/c) print(error) ```
output
1
44,937
13
89,875
Provide tags and a correct Python 3 solution for this coding contest problem. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal.
instruction
0
44,938
13
89,876
Tags: greedy, math Correct Solution: ``` import sys from collections import defaultdict import math from heapq import * import itertools MAXNUM = math.inf MINNUM = -1 * math.inf ASCIILOWER = 97 ASCIIUPPER = 65 pq = [] # list of entries arranged in a heap entry_finder = {} # mapping of tasks to entries REMOVED = "<removed-task>" # placeholder for a removed task counter = itertools.count() # unique sequence count def add_task(task, priority=0): "Add a new task or update the priority of an existing task" if task in entry_finder: remove_task(task) count = next(counter) entry = [priority, count, task] entry_finder[task] = entry heappush(pq, entry) def remove_task(task): "Mark an existing task as REMOVED. Raise KeyError if not found." entry = entry_finder.pop(task) entry[-1] = REMOVED def pop_task(): "Remove and return the lowest priority task. Raise KeyError if empty." while pq: priority, count, task = heappop(pq) if task is not REMOVED: del entry_finder[task] return task raise KeyError("pop from an empty priority queue") def getInt(): return int(sys.stdin.readline().rstrip()) def getInts(): return map(int, sys.stdin.readline().rstrip().split(" ")) def getString(): return sys.stdin.readline().rstrip() def printOutput(ans): sys.stdout.write("%.15f" % (ans)) def findParent(a, parents): cur = a while parents[cur] != cur: cur = parents[cur] parents[a] = cur # reduction of search time on next search return cur def union(a, b, parents): parents[b] = a def solve(nodeList, edgeList, edgeHeap): parents = [i for i in range(nodeList)] minTreeEdges = [] totalEdges = defaultdict(int) # Get min spanning tree while edgeHeap: eVal, n1, n2 = heappop(edgeHeap) n1Parent = findParent(n1, parents) n2Parent = findParent(n2, parents) if n1Parent != n2Parent: union(n1Parent, n2Parent, parents) totalEdges[n1] += 1 totalEdges[n2] += 1 add_task(n1, totalEdges[n1]) add_task(n2, totalEdges[n2]) minTreeEdgeList[n1] = (n2, eVal) minTreeEdgeList[n2] = (n1, eVal) # prune min spanning tree starting from leaves def readinput(): heap = [] v, e = getInts() nodes = [0] + list(getInts()) mx = 0 for i in range(e): n1, n2, e = getInts() mx = max(mx, (nodes[n1] + nodes[n2]) / e) printOutput(mx) readinput() ```
output
1
44,938
13
89,877
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. DZY loves Physics, and he enjoys calculating density. Almost everything has density, even a graph. We define the density of a non-directed graph (nodes and edges of the graph have some values) as follows: <image> where v is the sum of the values of the nodes, e is the sum of the values of the edges. Once DZY got a graph G, now he wants to find a connected induced subgraph G' of the graph, such that the density of G' is as large as possible. An induced subgraph G'(V', E') of a graph G(V, E) is a graph that satisfies: * <image>; * edge <image> if and only if <image>, and edge <image>; * the value of an edge in G' is the same as the value of the corresponding edge in G, so as the value of a node. Help DZY to find the induced subgraph with maximum density. Note that the induced subgraph you choose must be connected. <image> Input The first line contains two space-separated integers n (1 ≤ n ≤ 500), <image>. Integer n represents the number of nodes of the graph G, m represents the number of edges. The second line contains n space-separated integers xi (1 ≤ xi ≤ 106), where xi represents the value of the i-th node. Consider the graph nodes are numbered from 1 to n. Each of the next m lines contains three space-separated integers ai, bi, ci (1 ≤ ai < bi ≤ n; 1 ≤ ci ≤ 103), denoting an edge between node ai and bi with value ci. The graph won't contain multiple edges. Output Output a real number denoting the answer, with an absolute or relative error of at most 10 - 9. Examples Input 1 0 1 Output 0.000000000000000 Input 2 1 1 2 1 2 1 Output 3.000000000000000 Input 5 6 13 56 73 98 17 1 2 56 1 3 29 1 4 42 2 3 95 2 4 88 3 4 63 Output 2.965517241379311 Note In the first sample, you can only choose an empty subgraph, or the subgraph containing only node 1. In the second sample, choosing the whole graph is optimal. Submitted Solution: ``` import sys def input(): return sys.stdin.readline().strip() n, m = map(int, input().split()) x = [int(i) for i in input().split()] edge = [] val = 0 for i in range(m): a, b, c = map(int, input().split()) val = max((x[a-1]+x[b-1])/c, val) print(val) ```
instruction
0
44,939
13
89,878
Yes
output
1
44,939
13
89,879