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 an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n. You have to process q queries of two types: * 1 v — among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; * 2 i — delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). Input The first line contains three integers n, m and q (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 3 ⋅ 10^5; 1 ≤ q ≤ 5 ⋅ 10^5). The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 ≤ p_i ≤ n). Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges. Then q lines follow, which describe the queries. Each line is given by one of the following formats: * 1 v — denotes a query of the first type with a vertex v (1 ≤ v ≤ n). * 2 i — denotes a query of the second type with an edge i (1 ≤ i ≤ m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. Output For every query of the first type, print the value of p_u written on the chosen vertex u. Example Input 5 4 6 1 2 5 4 3 1 2 2 3 1 3 4 5 1 1 2 1 2 3 1 1 1 2 1 2 Output 5 1 2 0 Submitted Solution: ``` n, m, q = map(int, input().split()) values_list = [0] + list(map(int, input().split())) values = {} for i in range(1, n + 1): values[i] = values_list[i] edges = {} for i in range(1, m + 1): x, y = map(int, input().split()) edges[i] = [x, y] for i in range(q): w, v = map(int, input().split()) if w == 1: marks = set([v]) result = values[v] deleted = v for i in range(2): for i in edges: x, y = edges[i] if (x in marks) or (y in marks): marks.add(x) marks.add(y) if values[x] > result: result = values[x] deleted = x if values[y] > result: result = values[y] deleted = y values[deleted] = 0 print(result) else: edges.pop(v) m -= 1 ```
instruction
0
58,218
13
116,436
No
output
1
58,218
13
116,437
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n. You have to process q queries of two types: * 1 v — among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; * 2 i — delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). Input The first line contains three integers n, m and q (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 3 ⋅ 10^5; 1 ≤ q ≤ 5 ⋅ 10^5). The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 ≤ p_i ≤ n). Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges. Then q lines follow, which describe the queries. Each line is given by one of the following formats: * 1 v — denotes a query of the first type with a vertex v (1 ≤ v ≤ n). * 2 i — denotes a query of the second type with an edge i (1 ≤ i ≤ m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. Output For every query of the first type, print the value of p_u written on the chosen vertex u. Example Input 5 4 6 1 2 5 4 3 1 2 2 3 1 3 4 5 1 1 2 1 2 3 1 1 1 2 1 2 Output 5 1 2 0 Submitted Solution: ``` import sys input = sys.stdin.buffer.readline class SegmentTree: def __init__(self, n, op, e): self.n = n self.op = op self.e = e self.size = 2 ** ((n - 1).bit_length()) self.node = [self.e] * (2 * self.size) def __getitem__(self, i): return self.node[i + self.size] def __setitem__(self, i, val): i += self.size self.node[i] = val while i > 1: i >>= 1 self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1]) def build(self, array): for i, val in enumerate(array, self.size): self.node[i] = val for i in range(self.size - 1, 0, -1): self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1]) def all_fold(self): return self.node[1] def fold(self, l, r): l, r = l + self.size, r + self.size vl, vr = self.e, self.e while l < r: if l & 1: vl = self.op(vl, self.node[l]) l += 1 if r & 1: r -= 1 vr = self.op(self.node[r], vr) l, r = l >> 1, r >> 1 return self.op(vl, vr) class UnionFind: def __init__(self, n): self.parent = [-1] * n self.n = n self.cnt = n def root(self, x): if self.parent[x] < 0: return x else: self.parent[x] = self.root(self.parent[x]) return self.parent[x] def merge(self, x, y): x = self.root(x) y = self.root(y) if x == y: return False if self.parent[x] > self.parent[y]: x, y = y, x self.parent[x] += self.parent[y] self.parent[y] = x self.cnt -= 1 return True def is_same(self, x, y): return self.root(x) == self.root(y) def size(self, x): return -self.parent[self.root(x)] def count(self): return self.cnt def groups(self): res = [[] for _ in range(self.n)] for i in range(self.n): res[self.root(i)].append(i) return [group for group in res if group] class Node: def __init__(self, val=None): self.l, self.r, self.p = [None, None, None] self.val = val self.dist = (0, 0) n, m, q = map(int, input().split()) p = list(map(int, input().split())) edges = [list(map(int, input().split())) for i in range(m)] queries = [list(map(int, input().split())) for i in range(q)] del_i = set() for flag, i in queries: if flag == 2: del_i.add(i - 1) uf = UnionFind(n) for i, (a, b) in enumerate(edges): if i in del_i: continue a -= 1 b -= 1 uf.merge(a, b) group = {} memo = {} rt_set = set() for i in range(n): rt = uf.root(i) if rt not in group: group[rt] = [] group[rt].append(i) if rt in memo: continue memo[rt] = Node(rt) rt_set.add(rt) q_stack = [] q2_stack = [] for flag, i in queries[::-1]: if flag == 1: q_stack.append(uf.root(i - 1)) if flag == 2: a, b = edges[i - 1] a -= 1 b -= 1 if uf.is_same(a, b): q2_stack.append(None) q2_stack.append(None) continue else: rt_a = uf.root(a) rt_b = uf.root(b) uf.merge(a, b) rt_new = uf.root(a) node = Node(rt_new) memo[rt_a].p = node memo[rt_b].p = node node.l = memo[rt_a] node.r = memo[rt_b] q2_stack.append(rt_new) q2_stack.append(memo[rt_new]) memo[rt_new] = node if rt_new == rt_a: rt_set.remove(rt_b) else: rt_set.remove(rt_a) def dfs1(root, l): stack2.append(memo[root]) stack = [memo[root]] while stack: nd = stack.pop() if nd is None: continue if nd.r is None and nd.l is None: array.append(nd.val) r = l + len(group[nd.val]) nd.dist = (l, r) l = r if nd.r is not None: stack.append(nd.r) stack2.append(nd.r) if nd.l is not None: stack.append(nd.l) stack2.append(nd.l) return l array = [] stack2 = [] l = 0 for rt in rt_set: l = dfs1(rt, l) while stack2: nd = stack2.pop() if nd.l is None: continue nd.dist = (nd.l.dist[0], nd.r.dist[1]) res = [] for i in array: for j in group[i]: res.append(j) for i in range(n): res[i] = p[res[i]] to_ind = [0] * (n + 1) for i in range(n): to_ind[res[i]] = i INF = 10 ** 6 st = SegmentTree(n, max, 0) st.build(res) for flag, i in queries: if flag == 1: rt = q_stack.pop() l, r = memo[rt].dist ans = st.fold(l, r) print(ans) st[to_ind[ans]] = 0 else: nd = q2_stack.pop() ind = q2_stack.pop() if nd is None: continue else: memo[ind] = nd ```
instruction
0
58,219
13
116,438
No
output
1
58,219
13
116,439
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph consisting of n vertices and m edges. Initially there is a single integer written on every vertex: the vertex i has p_i written on it. All p_i are distinct integers from 1 to n. You have to process q queries of two types: * 1 v — among all vertices reachable from the vertex v using the edges of the graph (including the vertex v itself), find a vertex u with the largest number p_u written on it, print p_u and replace p_u with 0; * 2 i — delete the i-th edge from the graph. Note that, in a query of the first type, it is possible that all vertices reachable from v have 0 written on them. In this case, u is not explicitly defined, but since the selection of u does not affect anything, you can choose any vertex reachable from v and print its value (which is 0). Input The first line contains three integers n, m and q (1 ≤ n ≤ 2 ⋅ 10^5; 1 ≤ m ≤ 3 ⋅ 10^5; 1 ≤ q ≤ 5 ⋅ 10^5). The second line contains n distinct integers p_1, p_2, ..., p_n, where p_i is the number initially written on vertex i (1 ≤ p_i ≤ n). Then m lines follow, the i-th of them contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) and means that the i-th edge connects vertices a_i and b_i. It is guaranteed that the graph does not contain multi-edges. Then q lines follow, which describe the queries. Each line is given by one of the following formats: * 1 v — denotes a query of the first type with a vertex v (1 ≤ v ≤ n). * 2 i — denotes a query of the second type with an edge i (1 ≤ i ≤ m). For each query of the second type, it is guaranteed that the corresponding edge is not deleted from the graph yet. Output For every query of the first type, print the value of p_u written on the chosen vertex u. Example Input 5 4 6 1 2 5 4 3 1 2 2 3 1 3 4 5 1 1 2 1 2 3 1 1 1 2 1 2 Output 5 1 2 0 Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() class SegmentTree(): def __init__(self, init, unitX, f): self.f = f # (X, X) -> X self.unitX = unitX self.f = f if type(init) == int: self.n = init self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * (self.n * 2) else: self.n = len(init) self.n = 1 << (self.n - 1).bit_length() self.X = [unitX] * self.n + init + [unitX] * (self.n - len(init)) for i in range(self.n-1, 0, -1): self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) def update(self, i, x): i += self.n self.X[i] = x i >>= 1 while i: self.X[i] = self.f(self.X[i*2], self.X[i*2|1]) i >>= 1 def getvalue(self, i): return self.X[i + self.n] def getrange(self, l, r): l += self.n r += self.n al = self.unitX ar = self.unitX while l < r: if l & 1: al = self.f(al, self.X[l]) l += 1 if r & 1: r -= 1 ar = self.f(self.X[r], ar) l >>= 1 r >>= 1 return self.f(al, ar) # Find r s.t. calc(l, ..., r-1) = True and calc(l, ..., r) = False def max_right(self, l, z): if l >= self.n: return self.n l += self.n s = self.unitX while 1: while l % 2 == 0: l >>= 1 if not z(self.f(s, self.X[l])): while l < self.n: l *= 2 if z(self.f(s, self.X[l])): s = self.f(s, self.X[l]) l += 1 return l - self.n s = self.f(s, self.X[l]) l += 1 if l & -l == l: break return self.n # Find l s.t. calc(l, ..., r-1) = True and calc(l-1, ..., r-1) = False def min_left(self, r, z): if r <= 0: return 0 r += self.n s = self.unitX while 1: r -= 1 while r > 1 and r % 2: r >>= 1 if not z(self.f(self.X[r], s)): while r < self.n: r = r * 2 + 1 if z(self.f(self.X[r], s)): s = self.f(self.X[r], s) r -= 1 return r + 1 - self.n s = self.f(self.X[r], s) if r & -r == r: break return 0 def check(self, randX): f = self.f unitX = self.unitX err = 0 for _ in range(100): x = randX() y = randX() z = randX() if not f(x, unitX) == f(unitX, x) == x: err = 1 print("!!!!! unitX Error !!!!!") print("unitX =", unitX) print("x =", x) print("f(x, unitX) =", f(x, unitX)) print("f(unitX, x) =", f(unitX, x)) if not f(f(x, y), z) == f(x, f(y, z)): err = 1 print("!!!!! Associativity Error X !!!!!") print("x, y, z, f(x, y), f(y, x) =", x, y, z, f(x, y), f(y, x)) print("f(f(x, y), z) =", f(f(x, y), z)) print("f(x, f(y, z)) =", f(x, f(y, z))) assert err == 0 print("Seg Tree Check OK!") def debug(self): print("debug") print([self.getvalue(i) for i in range(min(self.n, 20))]) def par(a): L = [] while P[a] >= 0: L.append(a) a = P[a] for l in L: P[l] = a return a def unite(a, b): if par(a) != par(b): if P[par(b)] >= P[par(a)]: NE[LA[par(a)]] = par(b) LA[par(a)] = LA[par(b)] P[par(a)] += P[par(b)] P[par(b)] = par(a) else: NE[LA[par(b)]] = par(a) LA[par(b)] = LA[par(a)] P[par(b)] += P[par(a)] P[par(a)] = par(b) N, M, q = map(int, input().split()) A = [int(a) for a in input().split()] NN = N P = [-1] * NN LA = [i for i in range(NN)] NE = [-1] * NN E = [] Q = [] D = set() for _ in range(M): a, b = map(int, input().split()) E.append((a-1, b-1)) for _ in range(q): t, i = map(int, input().split()) Q.append((t, i-1)) if t == 2: D.add(i-1) E0 = [e for i, e in enumerate(E) if i not in D] for a, b in E0: unite(a, b) T1 = [] for t, i in Q[::-1]: if t == 1: pi = par(i) T1.append((pi, -P[pi])) else: a, b = E[i] unite(a, b) T1 = T1[::-1] pp = [i for i in range(NN) if par(i) == i] for i in range(len(pp) - 1): NE[LA[pp[i]]] = pp[i+1] LL = [pp[0]] IL = [0] * NN for i in range(NN - 1): ne = NE[LL[-1]] IL[ne] = i + 1 LL.append(ne) f = max unit = 0 st = SegmentTree(N, unit, f) if False: from random import randrange randX = lambda: randrange(20) st.check(randX) # st.debug() for i, p in enumerate(A): st.update(IL[i], (p << 18) + IL[i]) mm = (1 << 18) - 1 for a, w in T1: l = IL[a] r = l + w ma = st.getrange(l, r) s, i = ma >> 18, ma & mm st.update(i, 0) print(s) # st.debug() ```
instruction
0
58,220
13
116,440
No
output
1
58,220
13
116,441
Provide tags and a correct Python 3 solution for this coding contest problem. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image>
instruction
0
58,269
13
116,538
Tags: bitmasks, brute force, data structures, dfs and similar, dsu, graphs, greedy, trees Correct Solution: ``` import sys from sys import stdin from collections import deque def uf_find(n,p): ufl = [] while p[n] != n: ufl.append(n) n = p[n] for i in ufl: p[i] = n return n def uf_union(a,b,p,rank): ap = uf_find(a,p) bp = uf_find(b,p) if ap == bp: return True else: if rank[ap] > rank[bp]: p[bp] = ap elif rank[ap] < rank[bp]: p[ap] = bp else: p[bp] = ap rank[ap] += 1 return False n,m = map(int,stdin.readline().split()) if n <= 1000: lis = [[0] * n for i in range(n)] wuv = [] XOR = 0 for i in range(m): u,v,w = map(int,stdin.readline().split()) u -= 1 v -= 1 wuv.append( (w,u,v) ) lis[u][v] = lis[v][u] = w XOR ^= w wuv.sort() p = [i for i in range(n)] rank = [0] * n edge = [] flag = False for i in range(n): for j in range(i): if lis[i][j] == 0: if uf_union(i,j,p,rank): flag = True else: edge.append( (i,j,0) ) nans = 0 for w,u,v in wuv: if uf_union(u,v,p,rank): pass else: nans += w edge.append((u,v,w)) if flag: print (nans) sys.exit() p = [i for i in range(n)] rank = [0] * n for i,j,w in edge: if w > 0: uf_union(i,j,p,rank) nplus = XOR for w,u,v in wuv: if uf_find(u,p) != uf_find(v,p): nplus = min(nplus,w) break elif w > nplus: break print (nans + nplus) else: lis = [ [] for i in range(n) ] wuv = [] for i in range(m): u,v,w = map(int,stdin.readline().split()) u -= 1 v -= 1 wuv.append((w,u,v)) lis[u].append( (v,w) ) lis[v].append( (u,w) ) able = [True] * n p = [i for i in range(n)] rank = [0] * n for st in range(n): if not able[st]: continue block = [0] * n cnt = 0 able[st] = False q = deque([st]) while q: while q: nv = q.popleft() cnt += 1 for u,w in lis[nv]: if able[u] and block[u] == cnt - 1: block[u] = cnt for i in range(n): if able[i] and block[i] != cnt: uf_union(i,st,p,rank) able[i] = False q.append(i) wuv.sort() ans = 0 for w,u,v in wuv: if not uf_union(u,v,p,rank): ans += w print (ans) ```
output
1
58,269
13
116,539
Provide tags and a correct Python 3 solution for this coding contest problem. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image>
instruction
0
58,270
13
116,540
Tags: bitmasks, brute force, data structures, dfs and similar, dsu, graphs, greedy, trees Correct Solution: ``` def divisors(M): d=[] i=1 while M>=i**2: if M%i==0: d.append(i) if i**2!=M: d.append(M//i) i=i+1 return d def popcount(x): x = x - ((x >> 1) & 0x55555555) x = (x & 0x33333333) + ((x >> 2) & 0x33333333) x = (x + (x >> 4)) & 0x0f0f0f0f x = x + (x >> 8) x = x + (x >> 16) return x & 0x0000007f def eratosthenes(n): res=[0 for i in range(n+1)] prime=set([]) for i in range(2,n+1): if not res[i]: prime.add(i) for j in range(1,n//i+1): res[i*j]=1 return prime def factorization(n): res=[] for p in prime: if n%p==0: while n%p==0: n//=p res.append(p) if n!=1: res.append(n) return res def euler_phi(n): res = n for x in range(2,n+1): if x ** 2 > n: break if n%x==0: res = res//x * (x-1) while n%x==0: n //= x if n!=1: res = res//n * (n-1) return res def ind(b,n): res=0 while n%b==0: res+=1 n//=b return res def isPrimeMR(n): if n==1: return 0 d = n - 1 d = d // (d & -d) L = [2, 3, 5, 7, 11, 13, 17] for a in L: t = d y = pow(a, t, n) if y == 1: continue while y != n - 1: y = (y * y) % n if y == 1 or t == n - 1: return 0 t <<= 1 return 1 def findFactorRho(n): from math import gcd m = 1 << n.bit_length() // 8 for c in range(1, 99): f = lambda x: (x * x + c) % n y, r, q, g = 2, 1, 1, 1 while g == 1: x = y for i in range(r): y = f(y) k = 0 while k < r and g == 1: ys = y for i in range(min(m, r - k)): y = f(y) q = q * abs(x - y) % n g = gcd(q, n) k += m r <<= 1 if g == n: g = 1 while g == 1: ys = f(ys) g = gcd(abs(x - ys), n) if g < n: if isPrimeMR(g): return g elif isPrimeMR(n // g): return n // g return findFactorRho(g) def primeFactor(n): i = 2 ret = {} rhoFlg = 0 while i*i <= n: k = 0 while n % i == 0: n //= i k += 1 if k: ret[i] = k i += 1 + i % 2 if i == 101 and n >= 2 ** 20: while n > 1: if isPrimeMR(n): ret[n], n = 1, 1 else: rhoFlg = 1 j = findFactorRho(n) k = 0 while n % j == 0: n //= j k += 1 ret[j] = k if n > 1: ret[n] = 1 if rhoFlg: ret = {x: ret[x] for x in sorted(ret)} return ret def divisors(n): res = [1] prime = primeFactor(n) for p in prime: newres = [] for d in res: for j in range(prime[p]+1): newres.append(d*p**j) res = newres res.sort() return res def xorfactorial(num):#排他的論理和の階乗 if num==0: return 0 elif num==1: return 1 elif num==2: return 3 elif num==3: return 0 else: x=baseorder(num) return (2**x)*((num-2**x+1)%2)+function(num-2**x) def xorconv(n,X,Y): if n==0: res=[(X[0]*Y[0])%mod] return res x=[digit[i]+X[i+2**(n-1)] for i in range(2**(n-1))] y=[Y[i]+Y[i+2**(n-1)] for i in range(2**(n-1))] z=[digit[i]-X[i+2**(n-1)] for i in range(2**(n-1))] w=[Y[i]-Y[i+2**(n-1)] for i in range(2**(n-1))] res1=xorconv(n-1,x,y) res2=xorconv(n-1,z,w) former=[(res1[i]+res2[i])*inv for i in range(2**(n-1))] latter=[(res1[i]-res2[i])*inv for i in range(2**(n-1))] former=list(map(lambda x:x%mod,former)) latter=list(map(lambda x:x%mod,latter)) return former+latter def merge_sort(A,B): pos_A,pos_B = 0,0 n,m = len(A),len(B) res = [] while pos_A < n and pos_B < m: a,b = A[pos_A],B[pos_B] if a < b: res.append(a) pos_A += 1 else: res.append(b) pos_B += 1 res += A[pos_A:] res += B[pos_B:] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) class WeightedUnionFind(): def __init__(self,N): self.parent = [i for i in range(N)] self.size = [1 for i in range(N)] self.val = [0 for i in range(N)] self.flag = True self.edge = [[] for i in range(N)] def dfs(self,v,pv): stack = [(v,pv)] new_parent = self.parent[pv] while stack: v,pv = stack.pop() self.parent[v] = new_parent for nv,w in self.edge[v]: if nv!=pv: self.val[nv] = self.val[v] + w stack.append((nv,v)) def unite(self,x,y,w): if not self.flag: return if self.parent[x]==self.parent[y]: self.flag = (self.val[x] - self.val[y] == w) return if self.size[self.parent[x]]>self.size[self.parent[y]]: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[x] += self.size[y] self.val[y] = self.val[x] - w self.dfs(y,x) else: self.edge[x].append((y,-w)) self.edge[y].append((x,w)) self.size[y] += self.size[x] self.val[x] = self.val[y] + w self.dfs(x,y) class Dijkstra(): class Edge(): def __init__(self, _to, _cost): self.to = _to self.cost = _cost def __init__(self, V): self.G = [[] for i in range(V)] self._E = 0 self._V = V @property def E(self): return self._E @property def V(self): return self._V def add_edge(self, _from, _to, _cost): self.G[_from].append(self.Edge(_to, _cost)) self._E += 1 def shortest_path(self, s): import heapq que = [] d = [10**15] * self.V d[s] = 0 heapq.heappush(que, (0, s)) while len(que) != 0: cost, v = heapq.heappop(que) if d[v] < cost: continue for i in range(len(self.G[v])): e = self.G[v][i] if d[e.to] > d[v] + e.cost: d[e.to] = d[v] + e.cost heapq.heappush(que, (d[e.to], e.to)) return d #Z[i]:length of the longest list starting from S[i] which is also a prefix of S #O(|S|) def Z_algorithm(s): N = len(s) Z_alg = [0]*N Z_alg[0] = N i = 1 j = 0 while i < N: while i+j < N and s[j] == s[i+j]: j += 1 Z_alg[i] = j if j == 0: i += 1 continue k = 1 while i+k < N and k + Z_alg[k]<j: Z_alg[i+k] = Z_alg[k] k += 1 i += k j -= k return Z_alg class BIT(): def __init__(self,n,mod=0): self.BIT = [0]*(n+1) self.num = n self.mod = mod def query(self,idx): res_sum = 0 mod = self.mod while idx > 0: res_sum += self.BIT[idx] if mod: res_sum %= mod idx -= idx&(-idx) return res_sum #Ai += x O(logN) def update(self,idx,x): mod = self.mod while idx <= self.num: self.BIT[idx] += x if mod: self.BIT[idx] %= mod idx += idx&(-idx) return class dancinglink(): def __init__(self,n,debug=False): self.n = n self.debug = debug self._left = [i-1 for i in range(n)] self._right = [i+1 for i in range(n)] self.exist = [True for i in range(n)] def pop(self,k): if self.debug: assert self.exist[k] L = self._left[k] R = self._right[k] if L!=-1: if R!=self.n: self._right[L],self._left[R] = R,L else: self._right[L] = self.n elif R!=self.n: self._left[R] = -1 self.exist[k] = False def left(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._left[res] if res==-1: break k -= 1 return res def right(self,idx,k=1): if self.debug: assert self.exist[idx] res = idx while k: res = self._right[res] if res==self.n: break k -= 1 return res class SparseTable(): def __init__(self,A,merge_func,ide_ele): N=len(A) n=N.bit_length() self.table=[[ide_ele for i in range(n)] for i in range(N)] self.merge_func=merge_func for i in range(N): self.table[i][0]=A[i] for j in range(1,n): for i in range(0,N-2**j+1): f=self.table[i][j-1] s=self.table[i+2**(j-1)][j-1] self.table[i][j]=self.merge_func(f,s) def query(self,s,t): b=t-s+1 m=b.bit_length()-1 return self.merge_func(self.table[s][m],self.table[t-2**m+1][m]) class BinaryTrie: class node: def __init__(self,val): self.left = None self.right = None self.max = val def __init__(self): self.root = self.node(-10**15) def append(self,key,val): pos = self.root for i in range(29,-1,-1): pos.max = max(pos.max,val) if key>>i & 1: if pos.right is None: pos.right = self.node(val) pos = pos.right else: pos = pos.right else: if pos.left is None: pos.left = self.node(val) pos = pos.left else: pos = pos.left pos.max = max(pos.max,val) def search(self,M,xor): res = -10**15 pos = self.root for i in range(29,-1,-1): if pos is None: break if M>>i & 1: if xor>>i & 1: if pos.right: res = max(res,pos.right.max) pos = pos.left else: if pos.left: res = max(res,pos.left.max) pos = pos.right else: if xor>>i & 1: pos = pos.right else: pos = pos.left if pos: res = max(res,pos.max) return res def solveequation(edge,ans,n,m): #edge=[[to,dire,id]...] x=[0]*m used=[False]*n for v in range(n): if used[v]: continue y = dfs(v) if y!=0: return False return x def dfs(v): used[v]=True r=ans[v] for to,dire,id in edge[v]: if used[to]: continue y=dfs(to) if dire==-1: x[id]=y else: x[id]=-y r+=y return r class Matrix(): mod=10**9+7 def set_mod(m): Matrix.mod=m def __init__(self,L): self.row=len(L) self.column=len(L[0]) self._matrix=L for i in range(self.row): for j in range(self.column): self._matridigit[i][j]%=Matrix.mod def __getitem__(self,item): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item return self._matridigit[i][j] def __setitem__(self,item,val): if type(item)==int: raise IndexError("you must specific row and column") elif len(item)!=2: raise IndexError("you must specific row and column") i,j=item self._matridigit[i][j]=val def __add__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matridigit[i][j]+other._matridigit[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __sub__(self,other): if (self.row,self.column)!=(other.row,other.column): raise SizeError("sizes of matrixes are different") res=[[0 for j in range(self.column)] for i in range(self.row)] for i in range(self.row): for j in range(self.column): res[i][j]=self._matridigit[i][j]-other._matridigit[i][j] res[i][j]%=Matrix.mod return Matrix(res) def __mul__(self,other): if type(other)!=int: if self.column!=other.row: raise SizeError("sizes of matrixes are different") res=[[0 for j in range(other.column)] for i in range(self.row)] for i in range(self.row): for j in range(other.column): temp=0 for k in range(self.column): temp+=self._matridigit[i][k]*other._matrix[k][j] res[i][j]=temp%Matrix.mod return Matrix(res) else: n=other res=[[(n*self._matridigit[i][j])%Matrix.mod for j in range(self.column)] for i in range(self.row)] return Matrix(res) def __pow__(self,m): if self.column!=self.row: raise MatrixPowError("the size of row must be the same as that of column") n=self.row res=Matrix([[int(i==j) for i in range(n)] for j in range(n)]) while m: if m%2==1: res=res*self self=self*self m//=2 return res def __str__(self): res=[] for i in range(self.row): for j in range(self.column): res.append(str(self._matridigit[i][j])) res.append(" ") res.append("\n") res=res[:len(res)-1] return "".join(res) import sys,random,bisect from collections import deque,defaultdict from heapq import heapify,heappop,heappush from itertools import permutations from math import gcd,log import io,os input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline mi = lambda :map(int,input().split()) li = lambda :list(mi()) n,m = mi() edge = [set([]) for i in range(n)] E = [] xor = 0 for _ in range(m): u,v,c = mi() edge[u-1].add(v-1) edge[v-1].add(u-1) E.append((u-1,v-1,c)) xor ^= c visited = [False for i in range(n)] rest = [i for i in range(n)] group = [] root = [] parent = [-1 for v in range(n)] for v in range(n): if not visited[v]: g = set([v]) root.append(v) visited[v] = True stack = [v] parent[v] = v while stack: u = stack.pop() for nv in rest: if nv==v: continue if nv not in edge[u] and not visited[nv]: visited[nv] = True g.add(nv) stack.append(nv) parent[nv] = v rest = [nv for nv in rest if not visited[nv]] group.append(g) uf = UnionFindVerSize(n) G = len(group) for i in range(G): p = root[i] for v in group[i]: uf.unite(p,v) E.sort(key=lambda x:x[2]) alt = [] use = [] res = xor for u,v,c in E: if not uf.is_same_group(u,v): res += c uf.unite(u,v) use.append((u,v)) else: alt.append((u,v,c)) #tree_check flag = True for i in range(G): size = len(group[i]) edge_cnt = size*(size-1) for v in group[i]: for nv in edge[v]: if nv in group[i]: edge_cnt -= 1 if edge_cnt//2!=size-1: flag = False #print(flag,group,res,xor) base = res-xor if not flag: print(base) else: tree = [[] for i in range(n)] for i in range(G): size = len(group[i]) edge_cnt = size*(size-1) for v in group[i]: for nv in group[i]: if nv not in edge[v] and nv!=v: tree[v].append((nv,1)) for u,v in use: tree[u].append((v,0)) tree[v].append((u,0)) deq = deque([0]) cnt = [0 for i in range(n)] tree_parent = [-1 for v in range(n)] depth = [0 for i in range(n)] while deq: v = deq.popleft() for nv,c in tree[v]: if tree_parent[nv]==-1 and nv: tree_parent[nv] = v depth[nv] = depth[v] + 1 cnt[nv] = cnt[v] + c deq.append(nv) N = n LV = (N-1).bit_length() def construct(prv): kprv = [prv] S = prv for k in range(LV): T = [0]*N for i in range(N): if S[i] is None: continue T[i] = S[S[i]] kprv.append(T) S = T return kprv kprv=construct(tree_parent) def lca(u, v): dd = depth[v] - depth[u] if dd < 0: u, v = v, u dd = -dd # assert depth[u] <= depth[v] for k in range(LV+1): if dd & 1: v = kprv[k][v] dd >>= 1 # assert depth[u] == depth[v] if u == v: return u for k in range(LV-1, -1, -1): pu = kprv[k][u]; pv = kprv[k][v] if pu != pv: u = pu; v = pv # assert kprv[0][u] == kprv[0][v] return kprv[0][u] plus = xor for u,v,c in alt: L = lca(u,v) t = cnt[u] + cnt[v] - 2 * cnt[L] assert t>=0 if parent[u]==parent[v]: assert t if t: plus = min(plus,c) print(base+plus) ```
output
1
58,270
13
116,541
Provide tags and a correct Python 3 solution for this coding contest problem. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image>
instruction
0
58,271
13
116,542
Tags: bitmasks, brute force, data structures, dfs and similar, dsu, graphs, greedy, trees Correct Solution: ``` import sys, os if os.environ['USERNAME']=='kissz': inp=open('in3.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def getp(i): L=[] while parent[i]>=0: L+=[i] i=parent[i] for j in L: parent[j]=i return i n,m=map(int,inp().split()) neighbors=[set() for _ in range(n)] G=[[] for _ in range(n)] E=[] xors=0 for _ in range(m): u,v,w=map(int,inp().split()) neighbors[u-1].add(v-1) neighbors[v-1].add(u-1) E+=[(w,v-1,u-1)] xors^=w s=0 parent=[-1]*n k=(n*(n-1))//2-m nodes=set(range(n)) conn=0 for p in range(n): if p not in nodes: continue nodes.remove(p) Q=[p] while Q: i=Q.pop() new_nodes=set() for j in nodes: if j not in neighbors[i]: parent[j]=p G[i].append((j,True)) G[j].append((i,True)) new_nodes.add(j) conn+=1 debug(i,j,0) k-=1 Q.append(j) nodes-=new_nodes debug(parent) if conn<n-1 or k==0: E.sort() for w,u,v in E: pu=getp(u) pv=getp(v) if pu!=pv: s+=w parent[pu]=pv G[u].append((v,False)) G[v].append((u,False)) conn+=1 debug(u,v,w) elif k==0 and w<xors: Q=[(u,False)] seen=[False]*n seen[u]=True while Q: i,new=Q.pop() for j,new_edge in G[i]: if not seen[j]: seen[j]=True new_edge |= new if j==v: Q=[] break else: Q.append((j,new_edge)) if new_edge: s+=w debug('corr ',u,v,w) k+=1; if conn>=n-1 and (k>0 or w>xors): break if k==0: s+=xors debug('no corr ', xors) print(s) ```
output
1
58,271
13
116,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image> Submitted Solution: ``` from sys import stdin from collections import defaultdict from heapq import * V, E = map(int, stdin.readline().split()) dic = defaultdict(lambda : {}) xor_sum = 0 for _ in range(E): u, v, w = map(int, stdin.readline().split()) u -= 1 v -= 1 dic[u][v] = w dic[v][u] = w xor_sum ^= w components = [] unvisited = set(range(V)) for src in range(V): if src not in unvisited: continue queue = [src] for u in queue: if u not in unvisited: continue unvisited.remove(u) to_remove = [] for v in unvisited: if v not in dic[u]: queue.append(v) components.append(queue) conv = dict() for i in range(len(components)): for u in components[i]: conv[u] = i BIG_V = len(components) big_dic = defaultdict(lambda : defaultdict(lambda : float('inf'))) for u in dic: for v in dic[u]: if conv[u] == conv[v]: continue big_dic[conv[u]][conv[v]] = min(big_dic[conv[u]][conv[v]], dic[u][v]) mst = 0 edges = list((big_dic[0][v], v) for v in big_dic[0]) heapify(edges) visited = set((0,)) while len(visited) < BIG_V: w, v = heappop(edges) if v in visited: continue visited.add(v) mst += w for vv in big_dic[v]: heappush(edges, (big_dic[v][vv], vv)) total_edges = V*(V-1)//2 if total_edges - (V-BIG_V) == E: print(mst + xor_sum) else: print(mst) ```
instruction
0
58,272
13
116,544
No
output
1
58,272
13
116,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image> Submitted Solution: ``` import time #start_time = time.time() #def TIME_(): print(time.time()-start_time) import os, sys from io import BytesIO, IOBase from types import GeneratorType from bisect import bisect_left, bisect_right from collections import defaultdict as dd, deque as dq, Counter as dc import math, string, heapq as h BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): import os self.os = os self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = self.os.read(self._fd, max(self.os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: self.os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def getInt(): return int(input()) def getStrs(): return input().split() def getInts(): return list(map(int,input().split())) def getStr(): return input() def listStr(): return list(input()) def getMat(n): return [getInts() for _ in range(n)] def getBin(): return list(map(int,list(input()))) def isInt(s): return '0' <= s[0] <= '9' def ceil_(a,b): return a//b + (a%b > 0) MOD = 10**9 + 7 """ Existing weights has XOR K So my new weights have XOR K I need to assign weights with XOR sum K such that the weight of the MST is minimised Obviously once I've assigned some with XOR sum K, the rest can be 0ed So I'm going to add exactly K to the total weights, somehow So the question is, how much of the graph can I connect using none of the existing edges Connect as many nodes as possible that way, then resort to existing edges. Remember that one of my edges must be K If we can form a spanning tree from all bar one of the missing edges, the answer is 0 Take the minimum spanning tree of edges that we have to use, beyond our allowed """ def solve(): def find(a): if a != p[a]: p[a] = find(p[a]) return p[a] def union(a, b): a, b = find(a), find(b) if a == b: return if size[a] > size[b]: a, b = b, a p[a] = b size[b] += size[a] return N, M = getInts() G = dd(set) X = 0 edges = [] for i in range(M): u, v, w = getInts() u -= 1 v -= 1 G[u].add(v) G[v].add(u) X ^= w h.heappush(edges,(w,u,v)) used = [0]*N cons = 0 p = [i for i in range(N)] size = [1]*N ans = 0 for i in range(N): for j in range(N): if cons == N*(N-1)//2 - M - 1: break if i != j and find(i) != find(j) and j not in G[i]: union(i,j) cons += 1 if cons == N-1: return 0 while cons < N-2: w, u, v = h.heappop(edges) if find(u) == find(v): continue union(u,v) cons += 1 ans += w if not edges: ans += X else: w, u, v = h.heappop(edges) ans += min(X,w) return ans #for _ in range(getInt()): print(solve()) #solve() #TIME_() ```
instruction
0
58,273
13
116,546
No
output
1
58,273
13
116,547
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image> Submitted Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() from heapq import heapify, heappush as hpush, heappop as hpop def dijkstra(n, E, i0=0): kk = 18 mm = (1 << kk) - 1 h = [i0] D = [-1] * n done = [0] * n D[i0] = 0 while h: x = hpop(h) d, i = x >> kk, x & mm # di = hpop(h) # d, i = unpack("d", pack("q", (di | mm) - mm))[0], di & mm if done[i]: continue done[i] = 1 for j, w in E[i]: nd = d + w if D[j] < 0 or D[j] > nd: if done[j] == 0: hpush(h, (nd << kk) + j) # hpush(h, (unpack("q", pack("d", nd))[0] | mm) - (mm - j)) D[j] = nd return D def dijkstra_all(n, E, i0=0): kk = 18 mm = (1 << kk) - 1 h = [i0] D = [-1] * n done = [0] * n D[i0] = 0 while h: x = hpop(h) d, i = x >> kk, x & mm # di = hpop(h) # d, i = unpack("d", pack("q", (di | mm) - mm))[0], di & mm if done[i]: continue done[i] = 1 for j, w in enumerate(E[i]): if j == i: continue nd = d + w if D[j] < 0 or D[j] > nd: if done[j] == 0: hpush(h, (nd << kk) + j) # hpush(h, (unpack("q", pack("d", nd))[0] | mm) - (mm - j)) D[j] = nd return D def mst(n, X): P = [-1 for i in range(n)] def par(a): L = [] while P[a] >= 0: L.append(a) a = P[a] for l in L: P[l] = a return a def unite(a, b): if par(a) != par(b): if P[par(b)] >= P[par(a)]: if P[par(b)] == P[par(a)]: P[par(a)] -= 1 P[par(b)] = par(a) else: P[par(a)] = par(b) c = n - 1 s = 0 for i, j, w in sorted(X, key = lambda x: x[2]): if par(i) != par(j): unite(i, j) c -= 1 s += w if not c: return(s) def mst_next(n, X): if n <= 1: return 0 P = [-1 for i in range(n)] def par(a): L = [] while P[a] >= 0: L.append(a) a = P[a] for l in L: P[l] = a return a def unite(a, b): if par(a) != par(b): if P[par(b)] >= P[par(a)]: if P[par(b)] == P[par(a)]: P[par(a)] -= 1 P[par(b)] = par(a) else: P[par(a)] = par(b) c = n - 1 s = 0 ss = 1 << 100 done = 0 miw = 1 << 50 for i, j, w in sorted(X, key = lambda x: x[2]): if par(i) != par(j): unite(i, j) c -= 1 s += w else: if miw == 1 << 50 and (i in SE or j in SE): miw = min(miw, w) if c <= 0: if miw < 1 << 50: return (min(s, ss), miw) if done: if w > 1: return (ss, w) else: ss = s done = 1 return (min(s, ss), 1 << 50) N, M = map(int, input().split()) if N <= 900: MM = N * (N - 1) // 2 - M # Unassigned Edge used = [[0] * i for i in range(N)] X = [] mi = 1 << 100 s = 0 C = [0] * N for _ in range(M): a, b, c = map(int, input().split()) mi = min(mi, c) s ^= c a -= 1 b -= 1 C[a] += 1 C[b] += 1 if a < b: a, b = b, a X.append((a, b, c << 10)) used[a][b] = 1 SE = set([a for a in range(N) if C[a] < N - 1]) for i in range(N): ui = used[i] for j in range(i): if not ui[j]: X.append((i, j, 1)) mc, ne = mst_next(N, X) ne >>= 10 # print("mc, ne, mc>>10", mc, ne, mc >> 10) ans = mc >> 10 c = mc & 1023 if c == MM: ans += min(s, ne) print(ans) else: # ttt = 0 # while 1: # ttt += 1 C = [0] * N Y = [] for _ in range(M): a, b, c = map(int, input().split()) a -= 1 b -= 1 C[a] += 1 C[b] += 1 Y.append((a, b, c)) # Y[a].append((b, c)) # Y[b].append((a, c)) # F = [] DC = {} cnt = 0 for i, c in enumerate(C): if c == N - 1: # F.append(i) cnt += 1 DC[i] = cnt X = [] NN = cnt + 1 for a, b, c in Y: da = DC[a] if a in DC else 0 db = DC[b] if b in DC else 0 if da and db: X.append((da, db, c)) elif da: X.append((0, da, c)) elif db: X.append((0, db, c)) print(mst(NN, X)) ```
instruction
0
58,274
13
116,548
No
output
1
58,274
13
116,549
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. As a teacher, Riko Hakozaki often needs to help her students with problems from various subjects. Today, she is asked a programming task which goes as follows. You are given an undirected complete graph with n nodes, where some edges are pre-assigned with a positive weight while the rest aren't. You need to assign all unassigned edges with non-negative weights so that in the resulting fully-assigned complete graph the [XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) sum of all weights would be equal to 0. Define the ugliness of a fully-assigned complete graph the weight of its [minimum spanning tree](https://en.wikipedia.org/wiki/Minimum_spanning_tree), where the weight of a spanning tree equals the sum of weights of its edges. You need to assign the weights so that the ugliness of the resulting graph is as small as possible. As a reminder, an undirected complete graph with n nodes contains all edges (u, v) with 1 ≤ u < v ≤ n; such a graph has (n(n-1))/(2) edges. She is not sure how to solve this problem, so she asks you to solve it for her. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, 0 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2) - 1)) — the number of nodes and the number of pre-assigned edges. The inputs are given so that there is at least one unassigned edge. The i-th of the following m lines contains three integers u_i, v_i, and w_i (1 ≤ u_i, v_i ≤ n, u ≠ v, 1 ≤ w_i < 2^{30}), representing the edge from u_i to v_i has been pre-assigned with the weight w_i. No edge appears in the input more than once. Output Print on one line one integer — the minimum ugliness among all weight assignments with XOR sum equal to 0. Examples Input 4 4 2 1 14 1 4 14 3 2 15 4 3 8 Output 15 Input 6 6 3 6 4 2 4 1 4 5 7 3 4 10 3 5 1 5 2 15 Output 0 Input 5 6 2 3 11 5 3 7 1 4 10 2 4 14 4 3 8 2 5 6 Output 6 Note The following image showcases the first test case. The black weights are pre-assigned from the statement, the red weights are assigned by us, and the minimum spanning tree is denoted by the blue edges. <image> Submitted Solution: ``` import sys, os if os.environ['USERNAME']=='kissz': inp=open('in.txt','r').readline def debug(*args): print(*args,file=sys.stderr) else: inp=sys.stdin.readline def debug(*args): pass # SCRIPT STARTS HERE def getp(i): L=[] while parent[i]>=0: L+=[i] i=parent[i] for j in L: parent[j]=i return i n,m=map(int,inp().split()) neighbors=[[] for _ in range(n)] E=[] deg=[0]*n xors=0 for _ in range(m): u,v,w=map(int,inp().split()) neighbors[u-1].append(v-1) neighbors[v-1].append(u-1) E+=[(w,v-1,u-1)] xors^=w s=0 parent=[-1]*n k=(n*(n-1))//2-m conn=0 for i in range(n): for j in range(n): if j in neighbors[i]: continue pj=getp(j) if i!=pj: parent[i]=pj conn+=1 debug(i,j,0) neighbors[j]+=[i] k-=1 break E.sort() if conn<n-1: for w,u,v in E: pu=getp(u) pv=getp(v) if pu!=pv: s+=w parent[u]=pv conn+=1 debug(u,v,w) if conn>=n-1: break if k==0: for w,u,v in E: if w>=xors: s+=xors debug('no corr ', xors) break else: pu=getp(u) pv=getp(v) if pu==pv: s+=w debug('corr ',u,v,w) break print(s) ```
instruction
0
58,275
13
116,550
No
output
1
58,275
13
116,551
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,276
13
116,552
Tags: constructive algorithms, interactive, trees Correct Solution: ``` res = [] n = int(input()) print('?', 1, flush=True) arr = list(map(int, input().split())) for v,d in enumerate(arr): if d==1: res.append([0,v]) one = [v for v,d in enumerate(arr) if d&1] two = [v for v,d in enumerate(arr) if v and not (d&1)] if len(one)>len(two): one, two = two, one for u in one: print('?', u+1, flush=True) arr = list(map(int, input().split())) for v,d in enumerate(arr): if d==1 and v: res.append([u,v]) print('!') for u, v in res: print(u+1, v+1) ```
output
1
58,276
13
116,553
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,277
13
116,554
Tags: constructive algorithms, interactive, trees Correct Solution: ``` import sys input = sys.stdin.readline flush = sys.stdout.flush def query(x): print('?', x) flush() return list(map(int, input().split())) n = int(input()) ans = set() A = query(1) X, Y = [], [] for i, a in enumerate(A, 1): if not a % 2: X.append(i) else: Y.append(i) if len(X) > len(Y): X, Y = Y, X for x in X: if x != 1: B = query(x) else: B = A for i, b in enumerate(B, 1): if b == 1: ans.add((x, i)) print('!') flush() for a in ans: print(*a) flush() ```
output
1
58,277
13
116,555
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,278
13
116,556
Tags: constructive algorithms, interactive, trees Correct Solution: ``` import sys import math #def get_ints(): # return map(int, sys.stdin.readline().strip().split()) def inpu(): return sys.stdin.readline() #lets = 'abcdefghijklmnopqrstuvwxyz' #letts = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' #key = {lets[i]:i for i in range(26)} #prime = [1,11,101,1009,10007,100003,1000003,10000019,100000007] #prime2 = [2,13,103,1013,10009,100019,1000033,10000169,100000049] #big = int(1e9 + 7) #def gcd(a, b): # while b: # a, b = b, a%b # return a """ primes = [] def primes_gen(n): for i in range(2,1+int(n**0.5)): g = True for j in primes: if i % j == 0: g = False break if g: primes.append(i) primes_gen(1e9 + 10) """ def Q(m): print('?',m+1) sys.stdout.flush() return map(int,input().split()) #T = int(input()) #for t in range(T): n = int(input()) #n,m = map(int,input().split()) #a = list(map(int,input().split())) #b = list(map(int,input().split())) #a = input() #a = list(input()) #q = int(input()) done = False if n == 2: print('!') print(1,2) else: stag = [0]*n st_v = [0]*n ed = set() r = Q(0) i = 0 for j in r: if not stag[j]: st_v[j] = {i} stag[j] += 1 st_v[j].add(i) i+=1 o = 0 oi = 0 e = 0 ei = 0 lstag = len(stag) for i in range(1,lstag): if i%2: o += stag[i] oi += 1 else: e += stag[i] ei += 1 if e<o: for i in st_v[1]: ed.add((1,i+1)) #print(stag,st_v) if o <= e: j0 = 1 else: j0 = 2 while j0 < n and stag[j0]: for i0 in st_v[j0]: r = Q(i0) iii = 1 for i in r: if i == 1: ed.add((i0+1,iii)) iii += 1 j0 += 2 print('!') for i in ed: print(i[0],i[1]) ```
output
1
58,278
13
116,557
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,279
13
116,558
Tags: constructive algorithms, interactive, trees Correct Solution: ``` import os, sys from io import BytesIO, IOBase from math import log2, ceil, sqrt, gcd from _collections import deque import heapq as hp from bisect import bisect_left, bisect_right BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") mod = 10 ** 9 + 7 def solve(a): for i in a: if i==1: continue print('?', i, flush=True) a1 = list(map(int, input().split())) for j, v in enumerate(a1): if v == 1: ans.add((max(i, j+1), min(i, j+1))) n = int(input()) print('?', 1, flush=True) a1 = list(map(int, input().split())) a = [] b = [] ans = set() for i, v in enumerate(a1): if v == 1: ans.add((i + 1, 1)) if v % 2: a.append(i + 1) else: b.append(i + 1) if len(a) < len(b): solve(a) else: solve(b) print('!', flush=True) for i in ans: print(*i, flush=True) ```
output
1
58,279
13
116,559
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,280
13
116,560
Tags: constructive algorithms, interactive, trees Correct Solution: ``` def readline(): return map(int, input().split()) def ask(r): assert r >= 0 print('?', r + 1) return list(readline()) def say(edges): print('!') for (a, b) in edges: print(a+1, b+1) def main(): n = int(input()) d0 = ask(0) cnt = [0, 0] for value in d0: cnt[value & 1] += 1 b = 1 if cnt[0] > cnt[1] else 0 edges = list() for (i, value) in enumerate(d0): if value & 1 == b: di = ask(i) if i != 0 else d0 edges.extend((i, j) for (j, vj) in enumerate(di) if vj == 1) say(edges) if __name__ == '__main__': main() ```
output
1
58,280
13
116,561
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,281
13
116,562
Tags: constructive algorithms, interactive, trees Correct Solution: ``` def query(node): print("?", node+1) return list(map(int, input().split())) n = int(input()) ans = query(0) # root at node 0 max_depth = max(ans) depths = [set() for _ in range(max_depth+1)] for node, depth in enumerate(ans): depths[depth].add(node) num_even_depths = sum(len(depths[i]) for i in range(2, len(depths), 2)) # not counting 0 num_odd_depths = sum(len(depths[i]) for i in range(1, len(depths), 2)) graph = {0: depths[1]} for node in depths[1]: graph[node] = set() for depth in range(2 if num_even_depths < num_odd_depths else 1, max_depth+1, 2): for node in depths[depth]: ans = query(node) neighbors = {i for i in range(n) if ans[i] == 1} parent = {i for i in neighbors if i in depths[depth-1]}.pop() graph[parent].add(node) neighbors.remove(parent) children = neighbors graph[node] = children for child in children: graph[child] = set() print("!") for node in graph: for child in graph[node]: print(node+1, child+1) ```
output
1
58,281
13
116,563
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,282
13
116,564
Tags: constructive algorithms, interactive, trees Correct Solution: ``` from collections import Counter import string import math import bisect #import random import sys # sys.setrecursionlimit(10**6) from fractions import Fraction def array_int(): return [int(i) for i in sys.stdin.readline().split()] def vary(arrber_of_variables): if arrber_of_variables==1: return int(sys.stdin.readline()) if arrber_of_variables>=2: return map(int,sys.stdin.readline().split()) def makedict(var): return dict(Counter(var)) testcases=1 for _ in range(testcases): n=vary(1) print('? 1',flush=True) dis=array_int() tree=[[] for i in range(n+1)] nodes=[1]*(n+1) for i in range(len(dis)): if dis[i]%2!=0: if dis[i]==1: tree[1].append(i+1) nodes[i+1]=0 else: nodes[i+1]=1 white=nodes.count(0) black=nodes.count(1)-1 if black<=white: for i in range(2,n+1): if nodes[i]==1: print('?',i,flush=True) dis=array_int() for j in range(len(dis)): if dis[j]==1: tree[i].append(j+1) else: for i in range(1,n+1): if nodes[i]==0: print('?',i,flush=True) dis=array_int() for j in range(len(dis)): if dis[j]==1: tree[i].append(j+1) print('!',flush=True) # print(tree) st=set() for i in range(1,n+1): for j in tree[i]: if (i,j) not in st and (j,i) not in st: print(i,j,flush=True) st.add((i,j)) st.add((j,i)) ```
output
1
58,282
13
116,565
Provide tags and a correct Python 3 solution for this coding contest problem. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0]
instruction
0
58,283
13
116,566
Tags: constructive algorithms, interactive, trees Correct Solution: ``` import sys from collections import deque def get(i): print("?", i+1) return list(map(int, input().split())) n = int(input()) e = set() c = 0 z = get(0) odd = 0 even = 0 for i, x in enumerate(z): if x == 0: continue if x & 1: odd += 1 else: even += 1 if x == 1: e.add((0, i)) if odd < even: for i, x in enumerate(z): if (x & 1) == 0: continue z2 = get(i) for j, y in enumerate(z2): if y == 1: e_ = (min(i, j), max(i, j)) e.add(e_) else: for i, x in enumerate(z): if (x & 1) == 1 or i == 0: continue z2 = get(i) for j, y in enumerate(z2): if y == 1: e_ = (min(i, j), max(i, j)) e.add(e_) print("!") for E in e: print(E[0] + 1, E[1] + 1) sys.stdout.flush() ```
output
1
58,283
13
116,567
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` from sys import stdin, stdout input = stdin.readline ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) edges = [] def add_edges(i, d): for j in range(len(d)): if d[j] == 1: edges.append((i,j + 1)) n = inp() print("? 1") stdout.flush() d = inlt() levels = [] for i in range(max(d) + 1): levels.append([]) for i in range(len(d)): levels[d[i]].append(i + 1) num_evens = 0 for i in range(0, len(levels), 2): num_evens += len(levels[i]) if num_evens <= n // 2: add_edges(1, d) for i in range(2, len(levels), 2): for j in levels[i]: print(f"? {j}") stdout.flush() d = inlt() add_edges(j, d) else: for i in range(1, len(levels), 2): for j in levels[i]: print(f"? {j}") stdout.flush() d = inlt() add_edges(j, d) print("!") for e in edges: print(f"{e[0]} {e[1]}") # Segfaults on cpp so we switched to the trusty python :) ```
instruction
0
58,284
13
116,568
Yes
output
1
58,284
13
116,569
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO, IOBase import math from collections import Counter def func(n): print(f"? {1}") sys.stdout.flush() result = [int(i) for i in parse_input().split()] even = set() odd = set() edges = set() for i, val in enumerate(result): if val == 1: edges.add((1, i + 1)) if val > 0 and val % 2 == 0: even.add(i + 1) if val % 2 == 1: odd.add(i + 1) if len(even) < len(odd): choose = even else: choose = odd while choose: node = choose.pop() print(f"? {node}") sys.stdout.flush() result = [int(i) for i in parse_input().split()] for i, val in enumerate(result): if val == 1: edges.add(tuple(sorted([node, i + 1]))) return edges def main(): n = int(parse_input()) edges = func(n) print("!") for val in edges: print(f"{val[0]} {val[1]}") sys.stdout.flush() # region fastio # BUFSIZE = 8192 # class FastIO(IOBase): # newlines = 0 # def __init__(self, file): # self._fd = file.fileno() # self.buffer = BytesIO() # self.writable = "x" in file.mode or "r" not in file.mode # self.write = self.buffer.write if self.writable else None # def read(self): # while True: # b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) # if not b: # break # ptr = self.buffer.tell() # self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) # self.newlines = 0 # return self.buffer.read() # def readline(self): # while self.newlines == 0: # b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) # self.newlines = b.count(b"\n") + (not b) # ptr = self.buffer.tell() # self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) # self.newlines -= 1 # return self.buffer.readline() # def flush(self): # if self.writable: # os.write(self._fd, self.buffer.getvalue()) # self.buffer.truncate(0), self.buffer.seek(0) # class IOWrapper(IOBase): # def __init__(self, file): # self.buffer = FastIO(file) # self.flush = self.buffer.flush # self.writable = self.buffer.writable # self.write = lambda s: self.buffer.write(s.encode("ascii")) # self.read = lambda: self.buffer.read().decode("ascii") # self.readline = lambda: self.buffer.readline().decode("ascii") # sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) parse_input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
instruction
0
58,285
13
116,570
Yes
output
1
58,285
13
116,571
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` # Author : nitish420 -------------------------------------------------------------------- import os import sys from io import BytesIO, IOBase def main(): n=int(input()) tree=[] odd=[] even=[] print("? 1",flush=True) arr=list(map(int,input().split())) for i,item in enumerate(arr): if item&1: odd.append(i+1) else: even.append(i+1) # print(odd) # print(even) if len(odd)<len(even): for i in odd: print(f'? {i}',flush=True) arr=list(map(int,input().split())) for j,item in enumerate(arr): if item==1: tree.append((i,j+1)) else: for i in even: if i!=1: print(f'? {i}',flush=True) arr=list(map(int,input().split())) for j,item in enumerate(arr): if item==1: tree.append((i,j+1)) # output print("!") for item in tree: print(*item) ''' 7 1: 0 1 1 2 3 3 4 2: 1 0 2 1 2 2 3 3: 1 2 0 3 4 4 5 5: 3 2 4 1 0 2 1 6: 3 2 4 1 2 0 3 7 ? 1 0 1 1 2 3 3 4 ? 4 2 1 3 0 1 1 2 ? 7 4 3 5 2 1 3 0 ''' #---------------------------------------------------------------------------------------- # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = 'x' in file.mode or 'r' not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b'\n') + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode('ascii')) self.read = lambda: self.buffer.read().decode('ascii') self.readline = lambda: self.buffer.readline().decode('ascii') sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip('\r\n') # endregion if __name__ == '__main__': main() ```
instruction
0
58,286
13
116,572
Yes
output
1
58,286
13
116,573
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` import sys from sys import stdout import io, os # input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline # input = sys.stdin.buffer.readline input = lambda: sys.stdin.readline().strip() P = lambda: list(map(int, input().split())) from math import factorial as f, gcd from collections import deque, defaultdict as dd, Counter as C from heapq import heapify, heappop, heappush, heappushpop, heapreplace, merge from random import randint, choice, sample import time mod = 10**9+7 a = ord('a') start = time.time() def fast_exp(x, exp): ans = 1 base = x while exp: if exp & 1: ans *= base base *= base base %= mod ans %= mod exp >>= 1 return ans def countBits(n): count = 0 while n: count += n & 1 n >>= 1 return count def submasks(n): #this is cool #https://cp-algorithms.com/algebra/all-submasks.html org = n while n: yield n n = (n-1) & org def query(i): print('?', i+1) stdout.flush() return P() def solve(): n = int(input()) mat = [[0]*n for _ in range(n)] start = query(0) for i, x in enumerate(start): if x == 1: mat[i][0] = 1 mat[0][i] = 1 odd = sum([i%2 for i in start[1:]]) even = n-1-odd if odd < even: for i, x in enumerate(start): if x % 2: temp = query(i) for j, y in enumerate(temp): if y == 1: mat[i][j] = 1 mat[j][i] = 1 else: for i, x in enumerate(start): if x % 2 == 0 and x: temp = query(i) for j, y in enumerate(temp): if y == 1: mat[i][j] = 1 mat[j][i] = 1 print("!") for i in range(n): for j in range(i+1, n): if mat[i][j]: print(i+1, j+1) # tc = int(input()) # for t in range(1, tc+1): # solve() solve() # print(time.time()-start) ```
instruction
0
58,287
13
116,574
Yes
output
1
58,287
13
116,575
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` import math import heapq import sys import bisect from collections import deque import time input = sys.stdin.readline mod=10**9+7 ############ ---- Input Functions ---- ############ def inp(): return(int(input())) def inlt(): return(list(map(int,input().split()))) def insr(): s = input() return(list(s[:len(s) - 1])) def invr(): return(map(int,input().split())) def hash(x,y,n): return(x+n*(y-1)) n=inp() x=[] edge={} e=1 v=[0]*n x=0 for i in range(math.ceil(n/2)): print("?",e,flush=1) l=inlt() d={} y=[] for i in range(n): heapq.heappush(y,(-1*l[i],i+1)) for i in range(n): d[i]=[] for i in range(n): d[l[i]].append(i+1) d[n]=[] for i in d: if i!=n-1 and i!=n: if len(d[i])==1 and not v[d[i][0]-1] and len(d[i+1])!=0: v[d[i][0]-1]=1 for j in d[i+1]: if hash(min(d[i][0],j),max(d[i][0],j),n) not in edge: x+=1 edge[hash(min(d[i][0],j),max(d[i][0],j),n)]=[min(d[i][0],j),max(d[i][0],j)] if x==n-1: break #for i in range(n): # l[i]=[l[i],i] #l.sort(reverse=1) for i in range(n): a=heapq.heappop(y) if not v[a[1]-1]: e=a[1] break if x!=n-1: print(x) print("!",flush=1) for i in edge: print(*edge[i],flush=1) ```
instruction
0
58,288
13
116,576
No
output
1
58,288
13
116,577
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` n = int(input()) print('?', 1) Ans = [] A = list(map(int, input().split())) B1 = [] B2 = [] for i in range(n): if A[i] % 2 == 0 and A[i] != 0: B1.append(i) else: B2.append(i) if len(B1) <= len(B2): for i in range(len(A)): if A[i] == 1: Ans.append((1, i + 1)) for i in range(len(B1)): print('?', B1[i] + 1) A = list(map(int, input().split())) for j in range(len(A)): if A[j] == 1: Ans.append((i + 1, j + 1)) else: for i in range(len(B2)): print('?', B2[i] + 1) A = list(map(int, input().split())) for j in range(len(A)): if A[j] == 1: Ans.append((i + 1, j + 1)) for i in range(len(Ans)): print(*Ans[i]) ```
instruction
0
58,289
13
116,578
No
output
1
58,289
13
116,579
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` import sys,os,io # input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline class SortedList: def __init__(self, iterable=[], _load=200): """Initialize sorted list instance.""" values = sorted(iterable) self._len = _len = len(values) self._load = _load self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)] self._list_lens = [len(_list) for _list in _lists] self._mins = [_list[0] for _list in _lists] self._fen_tree = [] self._rebuild = True def _fen_build(self): """Build a fenwick tree instance.""" self._fen_tree[:] = self._list_lens _fen_tree = self._fen_tree for i in range(len(_fen_tree)): if i | i + 1 < len(_fen_tree): _fen_tree[i | i + 1] += _fen_tree[i] self._rebuild = False def _fen_update(self, index, value): """Update `fen_tree[index] += value`.""" if not self._rebuild: _fen_tree = self._fen_tree while index < len(_fen_tree): _fen_tree[index] += value index |= index + 1 def _fen_query(self, end): """Return `sum(_fen_tree[:end])`.""" if self._rebuild: self._fen_build() _fen_tree = self._fen_tree x = 0 while end: x += _fen_tree[end - 1] end &= end - 1 return x def _fen_findkth(self, k): """Return a pair of (the largest `idx` such that `sum(_fen_tree[:idx]) <= k`, `k - sum(_fen_tree[:idx])`).""" _list_lens = self._list_lens if k < _list_lens[0]: return 0, k if k >= self._len - _list_lens[-1]: return len(_list_lens) - 1, k + _list_lens[-1] - self._len if self._rebuild: self._fen_build() _fen_tree = self._fen_tree idx = -1 for d in reversed(range(len(_fen_tree).bit_length())): right_idx = idx + (1 << d) if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]: idx = right_idx k -= _fen_tree[idx] return idx + 1, k def _delete(self, pos, idx): """Delete value at the given `(pos, idx)`.""" _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len -= 1 self._fen_update(pos, -1) del _lists[pos][idx] _list_lens[pos] -= 1 if _list_lens[pos]: _mins[pos] = _lists[pos][0] else: del _lists[pos] del _list_lens[pos] del _mins[pos] self._rebuild = True def _loc_left(self, value): """Return an index pair that corresponds to the first position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins lo, pos = -1, len(_lists) - 1 while lo + 1 < pos: mi = (lo + pos) >> 1 if value <= _mins[mi]: pos = mi else: lo = mi if pos and value <= _lists[pos - 1][-1]: pos -= 1 _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value <= _list[mi]: idx = mi else: lo = mi return pos, idx def _loc_right(self, value): """Return an index pair that corresponds to the last position of `value` in the sorted list.""" if not self._len: return 0, 0 _lists = self._lists _mins = self._mins pos, hi = 0, len(_lists) while pos + 1 < hi: mi = (pos + hi) >> 1 if value < _mins[mi]: hi = mi else: pos = mi _list = _lists[pos] lo, idx = -1, len(_list) while lo + 1 < idx: mi = (lo + idx) >> 1 if value < _list[mi]: idx = mi else: lo = mi return pos, idx def add(self, value): """Add `value` to sorted list.""" _load = self._load _lists = self._lists _mins = self._mins _list_lens = self._list_lens self._len += 1 if _lists: pos, idx = self._loc_right(value) self._fen_update(pos, 1) _list = _lists[pos] _list.insert(idx, value) _list_lens[pos] += 1 _mins[pos] = _list[0] if _load + _load < len(_list): _lists.insert(pos + 1, _list[_load:]) _list_lens.insert(pos + 1, len(_list) - _load) _mins.insert(pos + 1, _list[_load]) _list_lens[pos] = _load del _list[_load:] self._rebuild = True else: _lists.append([value]) _mins.append(value) _list_lens.append(1) self._rebuild = True def discard(self, value): """Remove `value` from sorted list if it is a member.""" _lists = self._lists if _lists: pos, idx = self._loc_right(value) if idx and _lists[pos][idx - 1] == value: self._delete(pos, idx - 1) def remove(self, value): """Remove `value` from sorted list; `value` must be a member.""" _len = self._len self.discard(value) if _len == self._len: raise ValueError('{0!r} not in list'.format(value)) def pop(self, index=-1): """Remove and return value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) value = self._lists[pos][idx] self._delete(pos, idx) return value def bisect_left(self, value): """Return the first index to insert `value` in the sorted list.""" pos, idx = self._loc_left(value) return self._fen_query(pos) + idx def bisect_right(self, value): """Return the last index to insert `value` in the sorted list.""" pos, idx = self._loc_right(value) return self._fen_query(pos) + idx def count(self, value): """Return number of occurrences of `value` in the sorted list.""" return self.bisect_right(value) - self.bisect_left(value) def __len__(self): """Return the size of the sorted list.""" return self._len def __getitem__(self, index): """Lookup value at `index` in sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) return self._lists[pos][idx] def __delitem__(self, index): """Remove value at `index` from sorted list.""" pos, idx = self._fen_findkth(self._len + index if index < 0 else index) self._delete(pos, idx) def __contains__(self, value): """Return true if `value` is an element of the sorted list.""" _lists = self._lists if _lists: pos, idx = self._loc_left(value) return idx < len(_lists[pos]) and _lists[pos][idx] == value return False def __iter__(self): """Return an iterator over the sorted list.""" return (value for _list in self._lists for value in _list) def __reversed__(self): """Return a reverse iterator over the sorted list.""" return (value for _list in reversed(self._lists) for value in reversed(_list)) def __repr__(self): """Return string representation of sorted list.""" return 'SortedList({0})'.format(list(self)) n = int(input()) rem = [i+1 for i in range (n)] edges = set() so = SortedList() found = [0]*(n+1) for i in range (1,n+1): so.add((found[i], i)) while(len(edges)<n-1): f = so[0][1] print('?',f,flush=1) d = [int(i) for i in input().split()] one = d.count(1) if one == 1: ione = d.index(1) if (f,ione+1) not in edges and (ione+1, f) not in edges: edges.add((f, ione+1)) so.remove((found[f], f)) so.remove((found[ione+1], ione+1)) found[f]+=1 found[ione+1]+=1 so.add((found[f], f)) so.add((found[ione+1], ione+1)) itwo = [] for i in range (len(d)): if d[i]==2: itwo.append(i+1) for i in range (len(itwo)): if (ione+1,itwo[i]) not in edges and (itwo[i], ione+1) not in edges: edges.add((ione+1, itwo[i])) so.remove((found[ione+1], ione+1)) so.remove((found[itwo[i]], itwo[i])) found[ione+1]+=1 found[itwo[i]]+=1 so.add((found[itwo[i]], itwo[i])) so.add((found[ione+1], ione+1)) else: ind = [] for i in range (len(d)): if d[i]==1: ind.append(i+1) for i in range (len(ind)): if (f,ind[i]) not in edges and (ind[i], f) not in edges: edges.add((f, ind[i])) so.remove((found[f], f)) so.remove((found[ind[i]], ind[i])) found[f]+=1 found[ind[i]]+=1 so.add((found[f], f)) so.add((found[ind[i]], ind[i])) print('!', flush=1) for i in edges: print(*i, flush=1) ```
instruction
0
58,290
13
116,580
No
output
1
58,290
13
116,581
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. Little Dormi was faced with an awkward problem at the carnival: he has to guess the edges of an unweighted tree of n nodes! The nodes of the tree are numbered from 1 to n. The game master only allows him to ask one type of question: * Little Dormi picks a node r (1 ≤ r ≤ n), and the game master will reply with an array d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, for all 1 ≤ i ≤ n. Additionally, to make the game unfair challenge Little Dormi the game master will allow at most ⌈n/2⌉ questions, where ⌈ x ⌉ denotes the smallest integer greater than or equal to x. Faced with the stomach-churning possibility of not being able to guess the tree, Little Dormi needs your help to devise a winning strategy! Note that the game master creates the tree before the game starts, and does not change it during the game. Input The first line of input contains the integer n (2 ≤ n ≤ 2 000), the number of nodes in the tree. You will then begin interaction. Output When your program has found the tree, first output a line consisting of a single "!" followed by n-1 lines each with two space separated integers a and b, denoting an edge connecting nodes a and b (1 ≤ a, b ≤ n). Once you are done, terminate your program normally immediately after flushing the output stream. You may output the edges in any order and an edge (a,b) is considered the same as an edge (b,a). Answering is not considered as a query. Interaction After taking input, you may make at most ⌈n/2⌉ queries. Each query is made in the format "? r", where r is an integer 1 ≤ r ≤ n that denotes the node you want to pick for that query. You will then receive n space separated integers d_1, d_2, …, d_n, where d_i is the length of the shortest path from node r to i, followed by a newline. 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. If at any point you make an invalid query or try to make more than ⌈ n/2 ⌉ queries, the interaction will terminate immediately and you will receive a Wrong Answer verdict. Hacks To hack a solution, use the following format. The first line contains the integer n (2 ≤ n ≤ 2 000). The next n−1 lines contain two integers u and v (1 ≤ u,v ≤ n) denoting an edge between u and v (u ≠ v). These n-1 edges must form a tree. Examples Input 4 0 1 2 2 1 0 1 1 Output ? 1 ? 2 ! 4 2 1 2 2 3 Input 5 2 2 1 1 0 Output ? 5 ! 4 5 3 5 2 4 1 3 Note Here is the tree from the first example. <image> Notice that the edges can be output in any order. Additionally, here are the answers for querying every single node in example 1: * 1: [0,1,2,2] * 2: [1,0,1,1] * 3: [2,1,0,2] * 4: [2,1,2,0] Below is the tree from the second example interaction. <image> Lastly, here are the answers for querying every single node in example 2: * 1: [0,4,1,3,2] * 2: [4,0,3,1,2] * 3: [1,3,0,2,1] * 4: [3,1,2,0,1] * 5: [2,2,1,1,0] Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") ########################################################## from collections import Counter, defaultdict import math sys.setrecursionlimit(10**3) def dfs(s): coming_val=arr[s] vis[s]=1 ind=ls.index(coming_val) if vis[ind]==0: dfs(ind) for _ in range(1): n=int(input()) #s=input() #a,b=map(int, input().split()) #arr =list(map(int, input().split())) #ls= list(map(int, input().split())) print("?", 1) sys.stdout.flush() arr = list(map(int, input().split())) g=[set() for i in range(1+n)] child=1 cnt=0 cc=1 for j in range(n): if arr[j]==1: g[1].add(j+1) cnt+=1 child=j+1 dis=2 next=-1 while cnt==1 and dis<2005: cnt=0 for j in range(n): if arr[j]==dis: g[child].add(j+1) cnt+=1 next=j+1 if cnt>0: child=next dis+=1 print(g) while cc<(n+1)//2: print("?",child) sys.stdout.flush() arr = list(map(int, input().split())) dis = 1 cnt=1 next=-1 while cnt == 1 and dis < 2005: cnt = 0 for j in range(n): if arr[j] == dis: g[child].add(j + 1) cnt += 1 next = j + 1 if cnt>0: child=next dis += 1 cc+=1 print("!") print(g) vis=[0]*(n+2) for i in range(1,n+1): for j in g[i]: if vis[j]==0: print(i, j) vis[i]=1 ```
instruction
0
58,291
13
116,582
No
output
1
58,291
13
116,583
Provide tags and a correct Python 3 solution for this coding contest problem. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
instruction
0
58,581
13
117,162
Tags: constructive algorithms, data structures, dfs and similar, dp, graphs Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline import sys import heapq INF=10**9 def Dijkstra(graph, start,m): dist=[INF]*len(graph) parent=[INF]*len(graph) queue=[(0, start)] while queue: path_len, v=heapq.heappop(queue) if dist[v]==INF: dist[v]=path_len for w in graph[v]: if dist[w[0]]==INF: parent[w[0]]=[v,w[1]] heapq.heappush(queue, (dist[v]+1, w[0])) return (dist,parent) n,m=map(int,input().split()) d=list(map(int,input().split())) graph=[] for i in range(n): graph.append([]) for i in range(m): u,v=map(int,input().split()) graph[u-1].append([v-1,i]) graph[v-1].append([u-1,i]) count=0 flag=0 for i in range(n): if d[i]==1: count+=1 elif d[i]==-1: flag=1 if count%2==1 and flag==0: print(-1) sys.exit() if count%2==1: for i in range(n): if d[i]==-1 and flag==1: d[i]=1 flag=0 elif d[i]==-1: d[i]=0 else: for i in range(n): if d[i]==-1: d[i]=0 dist,parent=Dijkstra(graph,0,m) actualused=[0]*m children=[0]*n actualchildren=[0]*n for i in range(1,n): children[parent[i][0]]+=1 stack=[] for i in range(n): if children[i]==actualchildren[i]: stack.append(i) while stack: curr=stack.pop() if curr==0: break p=parent[curr] k=p[0] if d[curr]==1: actualused[p[1]]=1 d[k]=1-d[k] actualchildren[k]+=1 if actualchildren[k]==children[k]: stack.append(k) ans=[] for i in range(m): if actualused[i]: ans.append(str(i+1)) print(len(ans)) print(' '.join(ans)) ```
output
1
58,581
13
117,163
Provide tags and a correct Python 3 solution for this coding contest problem. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
instruction
0
58,582
13
117,164
Tags: constructive algorithms, data structures, dfs and similar, dp, graphs Correct Solution: ``` # https://codeforces.com/problemset/problem/840/B # TLE import sys input=sys.stdin.readline n, m = map(int, input().split()) d = list(map(int, input().split())) g={} def push(g, u, v, i): if u not in g: g[u]=[] if v not in g: g[v]=[] g[u].append([v, i+1]) g[v].append([u, i+1]) for i in range(m): u, v = map(int, input().split()) push(g, u-1, v-1, i) def solve(d, g): pos = [] S = 0 for i, x in enumerate(d): if x==-1: pos.append(i) else: S+=x if S%2==1: if len(pos)==0: return False, None d[pos[0]]=1 for x in pos[1:]: d[x]=0 else: for x in pos: d[x]=0 root=0 S = [root] edge = [-1] used = [0]*n used[root]=1 p=[None]*n i=0 while i<len(S): u=S[i] if u in g: for v, edge_ in g[u]: if v==p[u] or used[v]==1: continue p[v]=u used[v]=1 S.append(v) edge.append(edge_) i+=1 ans=[] r=[0]*n for v, edge_ in zip(S[1:][::-1], edge[1:][::-1]): if r[v]^d[v]==1: u=p[v] r[u]=1-r[u] ans.append(str(edge_)) return True, ans flg, ans =solve(d, g) if flg==False: print(-1) else: print(len(ans)) print('\n'.join(ans)) ```
output
1
58,582
13
117,165
Provide tags and a correct Python 3 solution for this coding contest problem. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1.
instruction
0
58,583
13
117,166
Tags: constructive algorithms, data structures, dfs and similar, dp, graphs Correct Solution: ``` import sys n, m = map(int, sys.stdin.readline().split()) d = list(map(int, sys.stdin.readline().split())) gph = [[] for _ in range(n)] for _ in range(m): u, v = map(int, sys.stdin.readline().split()) u -= 1 v -= 1 gph[u].append((v, _)) gph[v].append((u, _)) t = -1 if d.count(1) % 2 == 1: if -1 not in d: print(-1) exit(0) t = d.index(-1) ans = [False] * m vis = [False] * n ed = [(-1, -1)] * n rets = [(d[u] == 1) or (u == t) for u in range(n)] stk = [[0, iter(gph[0])]] while len(stk) > 0: u = stk[-1][0] vis[u] = True try: while True: v, i = next(stk[-1][1]) if not vis[v]: ed[v] = (u, i) stk.append([v, iter(gph[v])]) break except StopIteration: p, e = ed[u] if p >= 0 and rets[u]: rets[p] = not rets[p] ans[e] = True stk.pop() pass print(ans.count(True)) print("\n".join([str(i+1) for i in range(m) if ans[i]])) #1231 ```
output
1
58,583
13
117,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. Submitted Solution: ``` import math as mt import sys,string input=sys.stdin.readline from collections import defaultdict L=lambda : list(map(int,input().split())) Ls=lambda : list(input().split()) M=lambda : map(int,input().split()) I=lambda :int(input()) n,m=M() l=L() if(m==0): if(l.count(1)==0): print(0) exit() else: print(-1) exit() else: if(l.count(1)==0): print(0) exit() else: x=[] y=defaultdict(list) h=defaultdict(list) v=defaultdict(int) for i in range(m): a,b=M() if(l[a-1]!=1 and l[b-1]!=1): if(v[(a,b)]==0): x.append((a,b,i)) v[(a,b)]=1 p=[l[a-1]%2,l[b-1]%2] p.sort() if(p==[1,1] or p==[-1,-1] or p==[-1,1]): print(1) print(i+1) exit() if(p==[0,1]): if(l[a-1]==0): y[a].append(i+1) if(len(y[a])==2): print(2) print(*y[a]) exit() else: y[b].append(i+1) if(len(y[b])==2): print(2) print(*y[b]) if(p==[-1,0]): if(l[a-1]==0): y[a].append(i+1) if(len(y[a])==2): print(2) print(*y[a]) exit() else: y[b].append(i+1) if(len(y[b])==2): print(2) print(*y[b]) exit() if(p==[0,0]): j=[a,b] j.sort() h[j[0]].append(i+1) if(len(h[j[0]])==2): print(2) print(*h[j[0]]) exit() else: print(-1) ```
instruction
0
58,584
13
117,168
No
output
1
58,584
13
117,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. Submitted Solution: ``` # https://codeforces.com/problemset/problem/840/B n, m = map(int, input().split()) d = list(map(int, input().split())) g={} def push(g, u, v, i): if u not in g: g[u]=[] if v not in g: g[v]=[] g[u].append([v, i+1]) g[v].append([u, i+1]) for i in range(m): u, v = map(int, input().split()) push(g, u-1, v-1, i) def solve(d, g): pos = [] S = 0 for i, x in enumerate(d): if x==-1: pos.append(i) else: S+=x if S%2==1: if len(pos)==0: return False, None d[pos[0]]=1 for x in pos[1:]: d[x]=0 root=0 S = [root] edge = [-1] used = [0]*n used[root]=1 p=[None]*n i=0 while i<len(S): u=S[i] if u in g: for v, edge_ in g[u]: if v==p[u] or used[v]==1: continue p[v]=u used[v]=1 S.append(v) edge.append(edge_) i+=1 ans=[] for v, edge_ in zip(S[1:][::-1], edge[1:][::-1]): if d[v]==1: u = p[v] d[u]=1-d[u] ans.append(str(edge_)) return True, ans flg, ans =solve(d, g) if flg==False: print(-1) else: print(len(ans)) print('\n'.join(ans)) ```
instruction
0
58,585
13
117,170
No
output
1
58,585
13
117,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. Submitted Solution: ``` import sys import operator n,m=map(int,input().split()) a=list(map(int,input().split())) b=[] for i in range(n): if a[i]==-1 or a[i]==1: b.append(1) else: b.append(0) ans=[0] for i in range(m): k1,k2=map(int,input().split()) if b[k1-1]==1 and b[k2-1]==1: ans.append(i+1) if n==1: print(-1) else: if len(ans)==1: print(len(ans)-1) else: print(len(ans)-1) print(" ".join(str(i) for i in ans[1:])) ```
instruction
0
58,586
13
117,172
No
output
1
58,586
13
117,173
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha plays a computer game, where is on each level is given a connected graph with n vertices and m edges. Graph can contain multiple edges, but can not contain self loops. Each vertex has an integer di, which can be equal to 0, 1 or - 1. To pass the level, he needs to find a «good» subset of edges of the graph or say, that it doesn't exist. Subset is called «good», if by by leaving only edges from this subset in the original graph, we obtain the following: for every vertex i, di = - 1 or it's degree modulo 2 is equal to di. Leha wants to pass the game as soon as possible and ask you to help him. In case of multiple correct answers, print any of them. Input The first line contains two integers n, m (1 ≤ n ≤ 3·105, n - 1 ≤ m ≤ 3·105) — number of vertices and edges. The second line contains n integers d1, d2, ..., dn ( - 1 ≤ di ≤ 1) — numbers on the vertices. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) — edges. It's guaranteed, that graph in the input is connected. Output Print - 1 in a single line, if solution doesn't exist. Otherwise in the first line k — number of edges in a subset. In the next k lines indexes of edges. Edges are numerated in order as they are given in the input, starting from 1. Examples Input 1 0 1 Output -1 Input 4 5 0 0 0 -1 1 2 2 3 3 4 1 4 2 4 Output 0 Input 2 1 1 1 1 2 Output 1 1 Input 3 3 0 -1 1 1 2 2 3 1 3 Output 1 2 Note In the first sample we have single vertex without edges. It's degree is 0 and we can not get 1. Submitted Solution: ``` # ```
instruction
0
58,587
13
117,174
No
output
1
58,587
13
117,175
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph with N vertices and M edges. The vertices are numbered 1, 2, ..., N, and the edges are numbered 1, 2, ..., M. Edge i points from Vertex a_i to Vertex b_i. For each edge, determine whether the reversion of that edge would change the number of the strongly connected components in the graph. Here, the reversion of Edge i means deleting Edge i and then adding a new edge that points from Vertex b_i to Vertex a_i. Constraints * 2 \leq N \leq 1000 * 1 \leq M \leq 200,000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * If i \neq j, then a_i \neq a_j or b_i \neq b_j. Input Input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output Print M lines. In the i-th line, if the reversion of Edge i would change the number of the strongly connected components in the graph, print `diff`; if it would not, print `same`. Examples Input 3 3 1 2 1 3 2 3 Output same diff same Input 2 2 1 2 2 1 Output diff diff Input 5 9 3 2 3 1 4 1 4 2 3 5 5 3 3 4 1 2 2 5 Output same same same same same diff diff diff diff Submitted Solution: ``` import numpy as np def main(): n = int(input()) a = [int(x) for x in input().split()] best, solution = int(-1e10), [] for p in range(2): c = a.copy() indexes = list(range(p, n, 2)) if len(indexes) == 0: continue maks = max([c[i] for i in indexes]) pick = next((i for i in indexes if c[i] == maks)) chosen = set([pick] if maks <= 0 else [i for i in indexes if c[i] > 0]) is_chosen = [(i in chosen) for i in range(n)] tot, res = sum([c[i] for i in chosen]), [] for i in reversed(range(n)): if not is_chosen[i]: if i == 0 or i + 1 == len(c): res += [i] del c[i], is_chosen[i] elif is_chosen[i - 1] == is_chosen[i + 1]: res += [i] c[i - 1] += c[i + 1] del c[i + 1], c[i], is_chosen[i + 1], is_chosen[i] for end in [0, -1]: while len(c) > 1 and not is_chosen[end]: res += [end] del c[end], is_chosen[end] if tot > best: best, solution = tot, np.array(res) + 1 print(best, len(solution), *solution, sep='\n') if __name__ == '__main__': main() ```
instruction
0
58,731
13
117,462
No
output
1
58,731
13
117,463
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph with N vertices and M edges. The vertices are numbered 1, 2, ..., N, and the edges are numbered 1, 2, ..., M. Edge i points from Vertex a_i to Vertex b_i. For each edge, determine whether the reversion of that edge would change the number of the strongly connected components in the graph. Here, the reversion of Edge i means deleting Edge i and then adding a new edge that points from Vertex b_i to Vertex a_i. Constraints * 2 \leq N \leq 1000 * 1 \leq M \leq 200,000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * If i \neq j, then a_i \neq a_j or b_i \neq b_j. Input Input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output Print M lines. In the i-th line, if the reversion of Edge i would change the number of the strongly connected components in the graph, print `diff`; if it would not, print `same`. Examples Input 3 3 1 2 1 3 2 3 Output same diff same Input 2 2 1 2 2 1 Output diff diff Input 5 9 3 2 3 1 4 1 4 2 3 5 5 3 3 4 1 2 2 5 Output same same same same same diff diff diff diff Submitted Solution: ``` #!/usr/bin/env python3 class UnionFind(): def __init__(self, size): self.table = [-1] * size def find(self, x): while 0 <= self.table[x]: x = self.table[x] return x def unite(self, x, y): rx = self.find(x) ry = self.find(y) if rx != ry: dx = -self.table[rx] dy = -self.table[ry] if dx != dy: if dx < dy: self.table[rx] = ry else: self.table[ry] = rx else: self.table[rx] -= 1 self.table[ry] = rx return e = None re = None post = None rev = None cc = None scc = None t = 1 def dfs0(u, r): global post, rev, t global cc cc.unite(u, r) post[u] = 1 # dummy for w in e[u]: if post[w] == 0: dfs0(w, r) post[u] = t rev[t] = u t += 1 def dfs1(u, r, cr, visited): global scc scc.unite(u, r) visited[u] = True for w in re[u]: if cc.find(w) != cr: continue if not visited[w]: dfs1(w, r, cr, visited) def dfs2(u, r, first, rs, visited): visited[u] = True for w in e[u]: if not visited[w]: dfs2(w, r, first, rs, visited) elif w != r and w != first: rs.add((r, w)) def traverse(n, s, rs): visited = [False] * (n + 1) visited[s] = True for w in e[s]: visited[w] = True for w in e[s]: dfs2(w, s, w, rs, visited) def solve(n, m, edges): global post, rev global cc, scc post = [0] * (n + 1) rev = [0] * (n + 1) cc = UnionFind(n + 1) scc = UnionFind(n + 1) visited = [False] * (n + 1) for r in range(1, n + 1): if post[r] == 0: cur = t dfs0(r, r) for v in range(t - 1, cur - 1, -1): r1 = rev[v] if not visited[r1]: cr = cc.find(r1) dfs1(r1, r1, cr, visited) visited = [False] * (n + 1) path_exists = set() for a, b in edges: if not visited[a]: visited[a] = True traverse(n, a, path_exists) for a, b in edges: scc_a = scc.find(a) scc_b = scc.find(b) exist = (a, b) in path_exists print('diff' if (scc_a == scc_b) ^ exist else 'same') def main(): global e, re n, m = input().split() n = int(n) m = int(m) edges = [] e = [[] for _ in range(n + 1)] re = [[] for _ in range(n + 1)] for i in range(m): a, b = input().split() a = int(a) b = int(b) edges.append((a, b)) e[a].append(b) re[b].append(a) solve(n, m, edges) if __name__ == '__main__': main() ```
instruction
0
58,732
13
117,464
No
output
1
58,732
13
117,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph with N vertices and M edges. The vertices are numbered 1, 2, ..., N, and the edges are numbered 1, 2, ..., M. Edge i points from Vertex a_i to Vertex b_i. For each edge, determine whether the reversion of that edge would change the number of the strongly connected components in the graph. Here, the reversion of Edge i means deleting Edge i and then adding a new edge that points from Vertex b_i to Vertex a_i. Constraints * 2 \leq N \leq 1000 * 1 \leq M \leq 200,000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * If i \neq j, then a_i \neq a_j or b_i \neq b_j. Input Input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output Print M lines. In the i-th line, if the reversion of Edge i would change the number of the strongly connected components in the graph, print `diff`; if it would not, print `same`. Examples Input 3 3 1 2 1 3 2 3 Output same diff same Input 2 2 1 2 2 1 Output diff diff Input 5 9 3 2 3 1 4 1 4 2 3 5 5 3 3 4 1 2 2 5 Output same same same same same diff diff diff diff Submitted Solution: ``` #!/usr/bin/env python3 class UnionFind(): def __init__(self, size): self.table = [-1] * size def find(self, x): while 0 <= self.table[x]: x = self.table[x] return x def unite(self, x, y): rx = self.find(x) ry = self.find(y) if rx != ry: dx = -self.table[rx] dy = -self.table[ry] if dx != dy: if dx < dy: self.table[rx] = ry else: self.table[ry] = rx else: self.table[rx] -= 1 self.table[ry] = rx return e = None re = None post = None rev = None cc = None scc = None t = 1 def dfs0(u, r): global post, rev, t global cc cc.unite(u, r) post[u] = 1 # dummy for w in e[u]: if post[w] == 0: dfs0(w, r) post[u] = t rev[t] = u t += 1 def dfs1(u, r, cr, visited): global scc scc.unite(u, r) visited[u] = True for w in re[u]: if cc.find(w) != cr: continue if not visited[w]: dfs1(w, r, cr, visited) def dfs2(u, r, rs, visited): visited[u] = True for w in e[u]: if w != r and not w in rs: rs.add(w) if not visited[w]: dfs2(w, r, rs, visited) def find_another_paths(n, s, rs): for w in e[s]: visited = [False] * (n + 1) visited[s] = True dfs2(w, w, rs, visited) def solve(n, m, edges): global post, rev global cc, scc post = [0] * (n + 1) rev = [0] * (n + 1) cc = UnionFind(n + 1) scc = UnionFind(n + 1) visited = [False] * (n + 1) for r in range(1, n + 1): if post[r] == 0: cur = t dfs0(r, r) for v in range(t - 1, cur - 1, -1): r1 = rev[v] if not visited[r1]: cr = cc.find(r1) dfs1(r1, r1, cr, visited) another_paths = [None] * (n + 1) for a, b in edges: if another_paths[a] is None: another_paths[a] = set() find_another_paths(n, a, another_paths[a]) for a, b in edges: scc_a = scc.find(a) scc_b = scc.find(b) exist = b in another_paths[a] print('diff' if (scc_a == scc_b) ^ exist else 'same') def main(): global e, re n, m = input().split() n = int(n) m = int(m) edges = [] e = [[] for _ in range(n + 1)] re = [[] for _ in range(n + 1)] for i in range(m): a, b = input().split() a = int(a) b = int(b) edges.append((a, b)) e[a].append(b) re[b].append(a) solve(n, m, edges) if __name__ == '__main__': main() ```
instruction
0
58,733
13
117,466
No
output
1
58,733
13
117,467
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph with N vertices and M edges. The vertices are numbered 1, 2, ..., N, and the edges are numbered 1, 2, ..., M. Edge i points from Vertex a_i to Vertex b_i. For each edge, determine whether the reversion of that edge would change the number of the strongly connected components in the graph. Here, the reversion of Edge i means deleting Edge i and then adding a new edge that points from Vertex b_i to Vertex a_i. Constraints * 2 \leq N \leq 1000 * 1 \leq M \leq 200,000 * 1 \leq a_i, b_i \leq N * a_i \neq b_i * If i \neq j, then a_i \neq a_j or b_i \neq b_j. Input Input is given from Standard Input in the following format: N M a_1 b_1 a_2 b_2 : a_M b_M Output Print M lines. In the i-th line, if the reversion of Edge i would change the number of the strongly connected components in the graph, print `diff`; if it would not, print `same`. Examples Input 3 3 1 2 1 3 2 3 Output same diff same Input 2 2 1 2 2 1 Output diff diff Input 5 9 3 2 3 1 4 1 4 2 3 5 5 3 3 4 1 2 2 5 Output same same same same same diff diff diff diff Submitted Solution: ``` import numpy as np def main(): n = int(input()) a = [int(x) for x in input().split()] best, solution = int(-1e10), [] for p in range(2): c = a.copy() indexes = list(range(p, n, 2)) if len(indexes) == 0: continue maks = max([c[i] for i in indexes]) pick = next((i for i in indexes if c[i] == maks)) chosen = set([pick] if maks <= 0 else [i for i in indexes if c[i] > 0]) is_chosen = [(i in chosen) for i in range(n)] tot, res = sum([c[i] for i in chosen]), [] for i in reversed(range(n)): if not is_chosen[i]: if i == 0 or i + 1 == len(c): res += [i] del c[i], is_chosen[i] elif is_chosen[i - 1] == is_chosen[i + 1]: res += [i] c[i - 1] += c[i + 1] del c[i + 1], c[i], is_chosen[i + 1], is_chosen[i] for end in [0]: while len(c) > 1 and not is_chosen[end]: res += [end] del c[end], is_chosen[end] if tot > best: best, solution = tot, np.array(res) + 1 print(best, len(solution), *solution, sep='\n') if __name__ == '__main__': main() ```
instruction
0
58,734
13
117,468
No
output
1
58,734
13
117,469
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,812
13
117,624
"Correct Solution: ``` def main(): INF = float('inf') V, E = map(int, input().split()) G = [[INF for i in range(V)] for j in range(V)] for i in range(V): G[i][i] = 0 for i in range(E): s, t = map(int, input().split()) G[s][t] = -1 for k in range(V): for i in range(V): for j in range(V): G[i][j] = min(G[i][j], G[i][k] + G[k][j]) for i in range(V): if G[i][i]: print(1) break else: print(0) if __name__ == '__main__': main() ```
output
1
58,812
13
117,625
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,813
13
117,626
"Correct Solution: ``` nv,ne = [int(i) for i in input().split()] g = [[] for i in range(nv)] for i in range(ne): s,t = [int(j) for j in input().split()] g[s].append(t) visited = [] f = 0 def pursue_from(index, origin): if visited[index]: return visited[index] = True for next_index in g[index]: if next_index == origin: global f f = 1 return pursue_from(next_index, origin) for i in range(nv): visited = [False for i in range(nv)] pursue_from(i, i) if f == 1: break print(f) ```
output
1
58,813
13
117,627
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,814
13
117,628
"Correct Solution: ``` import sys; v,e=map(int, input().split()); v_l=[0]*v; e_b=[0]*e; e_l=[0]*e; result=0; for i in range(v): v_l[i] = 0; for i in range(e): e_b[i], e_l[i] = map(int, input().split()); def DFS(u): global result global v_l v_l[u] = 1 for i in range(e): if(e_b[i] == u): if(v_l[e_l[i]] == 0): DFS(e_l[i]) if(v_l[e_l[i]] == 1): result=1 v_l[u] = 2 for i in range(v): DFS(i) print(result) ```
output
1
58,814
13
117,629
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,815
13
117,630
"Correct Solution: ``` def is_contain_cycle(g, v): visited = set() for i in range(v): if i in visited: continue #route = Stack([None]) route = [None] dfs_stack = [(i, None)] while dfs_stack: u, prev = dfs_stack.pop() while route[-1] != prev: route.pop() if u in route: return True if u in visited: continue visited |= {u} dfs_stack.extend((v, u) for v in g[u]) route.append(u) return False from sys import stdin from collections import defaultdict readline = stdin.readline v, e = map(int, readline().split()) g = defaultdict(set) for i in range(e): s, t = map(int, readline().split()) g[s] |= {t} print(1 if is_contain_cycle(g, v) else 0) ```
output
1
58,815
13
117,631
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,816
13
117,632
"Correct Solution: ``` def solve(V, E, G): done = [False] * V def dfs(i, path): path.add(i) for j in G[i]: if j in path: return True if not done[j] and dfs(j, path): return True path.remove(i) done[i] = True return False for i in range(V): if not done[i] and dfs(i, set()): return 1 return 0 v,e=map(int,input().split()) g=[set() for _ in range(v)] for _ in range(e): s,t=map(int,input().split()) g[s].add(t) #閉路を持つ場合1,持たない場合0 print(solve(v,e,g)) ```
output
1
58,816
13
117,633
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,817
13
117,634
"Correct Solution: ``` def main(): v,e = map(int,input().split()) E = [[] for _ in range(v)] for _ in range(e): s,t = map(int,input().split()) E[s].append(t) res = False visited = [False]*v checked = [False]*v def dfs(u): if visited[u]: nonlocal res res = True return visited[u] = True for nu in E[u]: if not checked[nu]:dfs(nu) visited[u] = False checked[u] = True for i in range(v): for j in range(v):visited[j] = False if not checked[i]:dfs(i) print (1 if res else 0) if __name__ == '__main__': main() ```
output
1
58,817
13
117,635
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,818
13
117,636
"Correct Solution: ``` import sys sys.setrecursionlimit(200000) def dfs(root: int, add_duplicated=True) -> bool: global edges, visited, duplicated def body(i: int) -> bool: visited[i] = True for edge in edges[i]: if visited[edge]: if edge == root: return True if add_duplicated: duplicated.add(edge) continue if body(edge): return True return False return body(root) if __name__ == "__main__": n, m = map(int, input().split()) edges = [set() for _ in range(n)] # type: ignore for _ in range(m): s, t = map(lambda x: int(x), input().split()) edges[s].add(t) visited = [False] * n duplicated = set() # type: ignore for i in range(n): if not visited[i]: if dfs(i): print(1) exit(0) else: for i in duplicated: visited = [False] * n if dfs(i, False): print(1) exit(0) else: print(0) ```
output
1
58,818
13
117,637
Provide a correct Python 3 solution for this coding contest problem. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1
instruction
0
58,819
13
117,638
"Correct Solution: ``` #Detectando Ciclos en un grafo #Se puede mejorar a un mas from collections import deque import sys def dfs(G,u): n = len(G) vis=[-1]*n stackV = [] pila = deque() pila.append(u) vis[u]=1 stackV.append(u) while(pila): w = pila.pop() for v in G[w]: if(vis[v]==-1): vis[v]=1 pila.append(v) stackV.append(v) elif(vis[v]==1 and v==u): return True return False def main(): G =[] val = [int(x) for x in sys.stdin.readline().strip().split()] for i in range(val[0]): G.append([]) for i in range(val[1]): L = [int(x) for x in sys.stdin.readline().strip().split()] G[L[0]].append(L[1]) veri=[] for i in range(val[0]): veri.append(dfs(G,i)) if(True in veri):print(1) else:print(0) main() ```
output
1
58,819
13
117,639
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` from collections import deque, defaultdict def topological_sort(V, E): ''' Kahn's Algorithm (O(|V| + |E|) time) Input: V = [0, 1, ..., N-1]: a list of vertices of the digraph E: the adjacency list of the digraph (dict) Output: If the input digraph is acyclic, then return a topological sorting of the digraph. Else, return None. ''' indeg = {v: 0 for v in V} for ends in E.values(): for v in ends: indeg[v] += 1 q = deque([v for v in V if indeg[v] == 0]) top_sorted = [] while q: v = q.popleft() top_sorted.append(v) for u in E[v]: indeg[u] -= 1 if indeg[u] == 0: q.append(u) if len(top_sorted) == len(V): # The input digraph is acyclic. return top_sorted else: # There is a directed cycle in the digraph. return None N, M = map(int, input().split()) V = range(N) E = defaultdict(list) for _ in range(M): s, t = map(int, input().split()) E[s].append(t) print(1 if topological_sort(V, E) is None else 0) ```
instruction
0
58,820
13
117,640
Yes
output
1
58,820
13
117,641
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` from collections import deque # sts -> start topological sort def sts(): for i in g: for j in i: incnt[j]+=1 for i in range(v): if incnt[i]==0: q.append(i) # Now start deleting elements while q: e=q.popleft() ans.append(e) for i in g[e]: incnt[i]-=1 if incnt[i]==0: q.append(i) if len(ans)==v: print(0) else: print(1) v,e=map(int,input().split()) g=[[] for i in range(v)] # incnt -> no of indirected edges to a vertex incnt=[0]*v # q -> queue containing nodes with 0 indirected edges q=deque() # ans -> topological sorted array ans=[] for i in range(e): x,y=map(int,input().split()) g[x].append(y) sts() ```
instruction
0
58,821
13
117,642
Yes
output
1
58,821
13
117,643
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` #!/usr/bin/env python3 # N,M = map(int,sys.stdin.readline().split()) # a = tuple(map(int,sys.stdin.readline().split())) # single line with multi param # a = tuple(int(sys.stdin.readline()) for _ in range(N)) # multi line with single param # a = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(N)) # multi line with multi param # s = sys.stdin.readline().rstrip() # N = int(sys.stdin.readline()) # INF = float("inf") import sys,collections sys.setrecursionlimit(100000) INF = float("inf") V,E = map(int,sys.stdin.readline().split()) st = tuple(tuple(map(int,sys.stdin.readline().rstrip().split())) for _ in range(E)) # multi line with multi param #st = [[0,1],[0,2],[1,2],[2,3]] G = {i:[] for i in range(V)} for s,t in st: G[s].append(t) def dfs_cycle(s): act.add(s) visited.add(s) #print(s,act,visited,G) if not s in G: act.remove(s) return for e in G[s]: #print(s,e,act) if e in act: global bad bad = True return elif not e in visited: dfs_cycle(e) act.remove(s) bad = False visited = set() act = set() for s,_ in st: if not s in visited: dfs_cycle(s) if bad: print(1)#has cycle else: print(0) ```
instruction
0
58,822
13
117,644
Yes
output
1
58,822
13
117,645
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` from collections import deque v,e = map(int,input().split()) ins = [0]*v outs = [[] for i in range(v)] ans = [] for i in range(e): a,b = map(int,input().split()) outs[a].append(b) ins[b] += 1 Q = deque([]) for i in range(v): if ins[i] == 0: Q.append(i) while len(Q) > 0: cur = Q.popleft() ans.append(cur) for e in outs[cur]: ins[e] -= 1 if ins[e] == 0: Q.append(e) if len(ans) == v: print(0) else: print(1) ```
instruction
0
58,823
13
117,646
Yes
output
1
58,823
13
117,647
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find a cycle in a directed graph G(V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * si ≠ ti Input A directed graph G is given in the following format: |V| |E| s0 t0 s1 t1 : s|E|-1 t|E|-1 |V| is the number of nodes and |E| is the number of edges in the graph. The graph nodes are named with the numbers 0, 1,..., |V|-1 respectively. si and ti represent source and target nodes of i-th edge (directed). Output Print 1 if G has cycle(s), 0 otherwise. Examples Input 3 3 0 1 0 2 1 2 Output 0 Input 3 3 0 1 1 2 2 0 Output 1 Submitted Solution: ``` def is_contain_cycle(g, v): visited = set() for i in range(v): if i in visited: continue route = [None] dfs_stack = [(i, None)] while dfs_stack: u, prev = dfs_stack.pop() while route[-1] != prev: route.pop() visited |= {u} if u in route: return True dfs_stack.extend((v, u) for v in g[u]) route.append(u) return False from sys import stdin from collections import defaultdict readline = stdin.readline v, e = map(int, readline().split()) g = defaultdict(set) for i in range(e): s, t = map(int, readline().split()) g[s] |= {t} print(1 if is_contain_cycle(g, v) else 0) ```
instruction
0
58,824
13
117,648
No
output
1
58,824
13
117,649