message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,571
13
209,142
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` from sys import stdin try: n=int(stdin.readline().rstrip()) l=[0]*(n+1) arr=[] for _ in range(n-1): u,v=map(int,stdin.readline().rstrip().split()) arr.append((u,v)) l[u]+=1 l[v]+=1 x,y=0,n-2 for u,v in arr: if l[u]==1 or l[v]==1: print(x) x+=1 else: print(y) y-=1 except: pass ```
output
1
104,571
13
209,143
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,572
13
209,144
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` def solve(graph): ans = [-1 for i in range(len(graph) - 1)] for v in graph: if len(graph[v]) > 2: for i, (u, k) in enumerate(graph[v][:3]): ans[k] = i k = 0 for i in range(3, len(ans)): while ans[k] != -1: k += 1 ans[k] = i return ans return list(range(len(graph) - 1)) def test(): g1 = {1: [(2, 0), (3, 1)], 2: [(1, 0)], 3: [(1, 1)]} s1 = solve(g1) print(s1) assert s1 == [0, 1] g2 = {1: [(2, 0), (3, 1)], 2: [(1, 0), (4, 2), (5, 3)], 3: [(1, 1)], 4: [(2, 2)], 5: [(2, 3), (6, 5)], 6: [(5, 5)]} s2 = solve(g2) print(s2) assert s2 == [0, 3, 1, 2, 4] if __name__ == '__main__': # test() n = int(input()) graph = {i : [] for i in range(1, n + 1)} edges = [] for i in range(n - 1): u, v = [int(c) for c in input().split()] graph[u].append((v, i)) graph[v].append((u, i)) ans = solve(graph) print(*ans, sep='\n') ```
output
1
104,572
13
209,145
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,573
13
209,146
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` #!/usr/bin/env python # coding: utf-8 # In[83]: n = int(input()) edges = [] degrees = [0] for i in range(n): degrees.append(0) # In[84]: output = [] for i in range(n-1): output.append(-1) # In[85]: def d3(): d3_vertex = 0 for i in range(n+1): if ( degrees[i] > 2 ): d3_vertex = i return d3_vertex # In[86]: for i in range (n-1): inp = input().split() inp = [int(i) for i in inp] inp.sort() edges.append(inp) degrees[inp[0]]= degrees[inp[0]] +1 degrees[inp[1]]= degrees[inp[1]] +1 # In[91]: f = d3() if (f > 0): u = 0; for i in range(n-1): if(edges[i][0]==f or edges[i][1]==f): output[i] = u u = u+1 for i in range(n-1): if(output[i]==-1): output[i] = u u = u+1 for i in range(n-1): print(output[i]) else: for i in range(n-1): print(i) # In[ ]: ```
output
1
104,573
13
209,147
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,574
13
209,148
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` """ Template written to be used by Python Programmers. Use at your own risk!!!! Owned by enraged(rating - 5 star at CodeChef and Specialist at Codeforces). """ import sys import heapq from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt from collections import defaultdict as dd, deque, Counter as c from itertools import combinations as comb, permutations as perm from bisect import bisect_left as bl, bisect_right as br, bisect # sys.setrecursionlimit(2*pow(10, 6)) # sys.stdin = open("input.txt", "r") # sys.stdout = open("output.txt", "w") mod = pow(10, 9) + 7 mod2 = 998244353 def data(): return sys.stdin.readline().strip() def out(var): sys.stdout.write(str(var)) def l(): return list(sp()) def sl(): return list(ssp()) def sp(): return map(int, data().split()) def ssp(): return map(str, data().split()) def l1d(n, val=0): return [val for i in range(n)] def l2d(n, m, val=0): return [[val for i in range(n)] for j in range(m)] def maxDeg(): for i in graph.keys(): if len(graph[i]) >= 3: return i return 0 n = int(data()) graph = dd(set) mat = [] for i in range(n-1): a, b = sp() mat.append((a, b)) graph[a].add(b) graph[b].add(a) m = maxDeg() dist, length, j = len(graph[m])-1, len(graph[m])-1, 1 for i in mat: if i[0] == m and dist >= 0: out(str(length-dist)+"\n") dist -= 1 elif i[1] == m and dist >= 0: out(str(length-dist)+"\n") dist -= 1 else: out(str(length+j)+"\n") j += 1 ```
output
1
104,574
13
209,149
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,575
13
209,150
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` #!/usr/bin/env python from __future__ import division, print_function import os import sys from io import BytesIO, IOBase import collections if sys.version_info[0] < 3: from __builtin__ import xrange as range from future_builtins import ascii, filter, hex, map, oct, zip def solution(): n = int(input().strip()) d = collections.defaultdict(int) e = [] for _ in range(n-1): i, j = [int(x) for x in input().strip().split(" ")] e.append((i, j)) d[i] += 1 d[j] += 1 need = min(3, list(d.values()).count(1)) if need == 2: for i in range(n-1): print(i) else: cur = 3 for x in e: if d[x[0]] == 1 or d[x[1]] == 1: if need == 3: print(0) need -= 1 elif need == 2: print(1) need -= 1 elif need == 1: print(2) need -= 1 else: print(cur) cur += 1 else: print(cur) cur += 1 def main(): # T = int(input().strip()) for _ in range(1): solution() # 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
104,575
13
209,151
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,576
13
209,152
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` n = int(input()) deg = [0]*(n+2) es = [] for i in range(n-1): a,b = list(map(int, input().split())) deg[a]+=1 deg[b]+=1 es.append((a,b)) if max(deg)==2: for i in range(n-1): print(i) else: k = deg.index(max(deg)) e_012 = 0 cnt = 3 for e in es: if k in e and e_012 < 3: print(e_012) e_012+=1 else: print(cnt) cnt+=1 ```
output
1
104,576
13
209,153
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,577
13
209,154
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` # ------------------- fast io -------------------- 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") # ------------------- fast io -------------------- n=int(input()) graph=[[] for s in range(n)] inds={} leaf=set([]) for s in range(n-1): u,v=map(int,input().split()) u-=1 v-=1 inds[(u,v)]=s inds[(v,u)]=s graph[u].append(v) graph[v].append(u) if len(graph[u])==1: leaf.add(u) else: if u in leaf: leaf.remove(u) if len(graph[v])==1: leaf.add(v) else: if v in leaf: leaf.remove(v) ans=[-1 for s in range(n-1)] cv=0 if len(leaf)>=3: while len(leaf)>0: v0=leaf.pop() v1=graph[v0][0] ind=inds[(v0,v1)] ans[ind]=cv cv+=1 for s in range(n-1): if ans[s-1]==-1: ans[s-1]=cv cv+=1 else: #then u can really do much for s in range(n-1): ans[s]=s for s in range(n-1): print(ans[s]) ```
output
1
104,577
13
209,155
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image>
instruction
0
104,578
13
209,156
Tags: constructive algorithms, dfs and similar, greedy, trees Correct Solution: ``` def solve(n, queries): node = 0 count = [0] * (n + 1) for u, v in queries: count[u] += 1 count[v] += 1 if count[u] == 3: node = u if count[v] == 3: node = v j = 0 ans = [-1] * len(queries) for i, pair in enumerate(queries): if node in pair: ans[i] = j j += 1 for i in range(len(queries)): if ans[i] != -1: continue ans[i] = j j += 1 for i in ans: print(i) def smain(): inp = lambda: [int(x) for x in input().split()] n = int(input()) queries = [inp() for _ in range(n - 1)] solve(n, queries) if __name__ == '__main__': smain() ```
output
1
104,578
13
209,157
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` MOD = 1000000007 MOD2 = 998244353 ii = lambda: int(input()) si = lambda: input() dgl = lambda: list(map(int, input())) f = lambda: map(int, input().split()) il = lambda: list(map(int, input().split())) ls = lambda: list(input()) let = '@abcdefghijklmnopqrstuvwxyz' n=ii() deg=[0]*(10**5+10) l=[] it1,it2=0,n-2 for _ in range(n-1): x,y=f() deg[x]+=1 deg[y]+=1 l.append([x,y]) for i in l: if deg[i[0]]==1 or deg[i[1]]==1: print(it1) it1+=1 else: print(it2) it2-=1 ```
instruction
0
104,579
13
209,158
Yes
output
1
104,579
13
209,159
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` n = int(input()) degree = [0] * (n + 1) order = [] for _ in range(n-1): x, y = map(int, input().split()) degree[x] += 1 degree[y] += 1 order.append((x, y)) res1 = 0; res2 = n-2 k = 0 for d in range(n+1): if degree[d] >= 3: k = d break for x, y in order: if x == k or y == k: print(res1) res1 += 1 else: print(res2) res2 -= 1 ```
instruction
0
104,580
13
209,160
Yes
output
1
104,580
13
209,161
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` ''' Ehab and Path-etic MEXs - spoiled by mzy ''' ''' routine ''' N = int(input()) leaves = {} edges = [0 for i in range(N)] for edge in range(N - 1): a, b = list(map(int, input().split())) for node in (a, b): edges[node - 1] += 1 if edges[node - 1] == 1: leaves[node] = edge elif edges[node - 1] == 2: del leaves[node] if len(leaves) < 3: for n in range(N - 1): print(n) else: start = 3 leaf = 0 specials = list(leaves.values())[:3] for edge in range(N - 1): if edge in specials: print(leaf) leaf += 1 else: print(start) start += 1 # print(specials) ```
instruction
0
104,581
13
209,162
Yes
output
1
104,581
13
209,163
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` import math,sys,bisect,heapq from collections import defaultdict,Counter,deque from itertools import groupby,accumulate from functools import lru_cache #sys.setrecursionlimit(200000000) int1 = lambda x: int(x) - 1 #def input(): return sys.stdin.readline().strip()m input = iter(sys.stdin.buffer.read().decode().splitlines()).__next__ aj = lambda: list(map(int, input().split())) def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] #MOD = 1000000000 + 7 def Y(c): print(["NO","YES"][c]) def y(c): print(["no","yes"][c]) def Yy(c): print(["No","Yes"][c]) G = defaultdict(list) C = Counter() order = [] def addEdge(a,b): G[a].append(b) G[b].append(a) C[a] += 1 C[b] += 1 order.append((a,b)) n, = aj() for i in range(n-1): a,b = aj() addEdge(a,b) # print(C) # print(G) E = [] for i in C.keys(): E.append((C[i],i)) E.sort() mark = {} p = 0 for i,j in E: for l in G[j]: if mark.get((j,l),-1) == -1: mark[(j,l)] = p mark[(l,j)] = p p+=1 for i in order: print(mark[i]) ```
instruction
0
104,582
13
209,164
Yes
output
1
104,582
13
209,165
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` import math import fractions def make_divisors(n): divisors = [] for i in range(1, int(n**0.5)+1): if n % i == 0: divisors.append(i) if i != n // i: divisors.append(n//i) # divisors.sort() return divisors def ValueToBits(x,digit): res = [0 for i in range(digit)] now = x for i in range(digit): res[i]=now%2 now = now >> 1 return res def BitsToValue(arr): n = len(arr) ans = 0 for i in range(n): ans+= arr[i] * 2**i return ans def ValueToArray10(x, digit): ans = [0 for i in range(digit)] now = x for i in range(digit): ans[digit-i-1] = now%10 now = now //10 return ans ''' def cmb(n, r, p): if (r < 0) or (n < r): return 0 r = min(r, n - r) return fact[n] * factinv[r] * factinv[n-r] % p p = 10 ** 9 + 7 N = 10 ** 6 + 2 fact = [1, 1] # fact[n] = (n! mod p) factinv = [1, 1] # factinv[n] = ((n!)^(-1) mod p) inv = [0, 1] # factinv 計算用 for i in range(2, N + 1): fact.append((fact[-1] * i) % p) inv.append((-inv[p % i] * (p // i)) % p) factinv.append((factinv[-1] * inv[-1]) % p) ''' #a = list(map(int, input().split())) n = int(input()) nb = [[] for i in range(n)] nbe = [[] for i in range(n)] es = [] for i in range(n-1): a,b = list(map(int, input().split())) a -= 1 b -= 1 es.append([a,b]) nb[a].append(b) nb[b].append(a) nbe[a].append(i) nbe[b].append(i) start=-1 for i in range(n): if(len(nb[i])==1): start=i break queue=[start] done=0 checked=[0 for i in range(n)] checked[start] = 1 u = -1 v = -1 w = -1 while(True): #print(queue,done) if(len(queue)==done): #print("b") break else: now = queue[done] nownb = nb[now] #print("a",now,nownb,done) if(len(nownb)<=2): for j in range(len(nownb)): if(checked[nownb[j]]==0): queue.append(nownb[j]) checked[nownb[j]]=1 done+=1 else: u = nbe[now][0] v = nbe[now][1] w = nbe[now][2] break #print(u,v,w) print(checked) ans = [0 for i in range(n-1)] now = 3 if(u!=-1): for i in range(n-1): if(i==u): print(0) elif(i==v): print(1) elif(i==w): print(2) else: print(now) now+=1 else: for i in range(n-1): print(i) ```
instruction
0
104,583
13
209,166
No
output
1
104,583
13
209,167
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` from sys import stdin from collections import defaultdict input = stdin.readline def read_tuple(): return map(int,input().split()) def read_int(): return int(input()) def read_list(): return list(map(int,input().split())) def read_str_list(): return list(input().split()) n = read_int() tree = defaultdict(list) queries = [] for _ in range(n-1): u,v = read_tuple() tree[u].append(v) tree[v].append(u) if u>v: u,v = v,u queries.append( (u,v) ) ans = defaultdict(int) mex = 0 for u in range(1,n+1): if len(tree[u]) == 1: v = tree[u][0] if u>v: ans[ (v,u) ] = mex else: ans[ (u,v) ] = mex mex+=1 for u,v in queries: val = ans.get( (u,v), -1 ) if val==-1: print(mex) mex+=1 else: print(val) ```
instruction
0
104,584
13
209,168
No
output
1
104,584
13
209,169
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` n = int(input()) tree = [0] * (n+1) edges = [] for i in range(n-1): u, v = map(int, input().split()) edges.append((u, v)) tree[u] += 1 tree[v] += 1 left = 0 right = n-2 for u, v in edges: if tree[u] != 1 and tree[v] != 1: print(left) left += 1 else: print(right) right -= 1 ```
instruction
0
104,585
13
209,170
No
output
1
104,585
13
209,171
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree consisting of n nodes. You want to write some labels on the tree's edges such that the following conditions hold: * Every label is an integer between 0 and n-2 inclusive. * All the written labels are distinct. * The largest value among MEX(u,v) over all pairs of nodes (u,v) is as small as possible. Here, MEX(u,v) denotes the smallest non-negative integer that isn't written on any edge on the unique simple path from node u to node v. Input The first line contains the integer n (2 ≤ n ≤ 10^5) — the number of nodes in the tree. Each of the next n-1 lines contains two space-separated integers u and v (1 ≤ u,v ≤ n) that mean there's an edge between nodes u and v. It's guaranteed that the given graph is a tree. Output Output n-1 integers. The i^{th} of them will be the number written on the i^{th} edge (in the input order). Examples Input 3 1 2 1 3 Output 0 1 Input 6 1 2 1 3 2 4 2 5 5 6 Output 0 3 2 4 1 Note The tree from the second sample: <image> Submitted Solution: ``` import sys n = int(input()) a = [] b = dict() num = False a = list(map(str.strip, sys.stdin)) for i in range(n - 1): if a[i][0] in b: b[a[i][0]] += 1 else: b[a[i][0]] = 1 if a[i][1] in b: b[a[i][1]] += 1 else: b[a[i][1]] = 1 if b[a[i][1]] == 3: num = a[i][1] break if b[a[i][0]] == 3: num = a[i][0] break count = 0 count2 = 3 if not num: for i in range(n - 1): print(count) count += 1 else: for i in range(n - 1): if (num in a[i]) and (count < 3): print(count) count += 1 else: print(count2) count2 += 1 ```
instruction
0
104,586
13
209,172
No
output
1
104,586
13
209,173
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,840
13
209,680
Tags: implementation, math, trees Correct Solution: ``` height, n = map(int, input().split()) s = height reverted = False for h in range(height-1, -1, -1): if n > 2**h: more = True n -= 2**h else: more = False if more ^ reverted: s += (2 * 2**h - 1) reverted = not more print (s) ```
output
1
104,840
13
209,681
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,841
13
209,682
Tags: implementation, math, trees Correct Solution: ``` h, n = map(int, input().split()) h -= 1 n -= 1 l = 0 r = 2 << h ll = True ans = 0 i = 0 while r - l > 1: m = (l + r) // 2 if ll == (n < m): ans += 1 else: ans += 1 << (h - i + 1) if n < m: r = m ll = False else: l = m; ll = True i += 1 print(ans) ```
output
1
104,841
13
209,683
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,842
13
209,684
Tags: implementation, math, trees Correct Solution: ``` h, n = map(int, input().split()) t = bin(n-1)[2:] t = '0'*(h-len(t))+t res = 0 flag = True for i in range(h): if(t[i] == ('1' if flag else '0')): res += 2**(h-i) else: flag = not flag res += 1 print(res) ```
output
1
104,842
13
209,685
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,843
13
209,686
Tags: implementation, math, trees Correct Solution: ``` h, n = map(int, input().split()) ans = h n = n - 1 + (1 << h) for i in range(1, h+1): if not ( ((n & (1 << i)) == 0) ^ (n & (1 << (i-1)) == 0 )): ans += (1 << i) - 1 print(ans) ```
output
1
104,843
13
209,687
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,844
13
209,688
Tags: implementation, math, trees Correct Solution: ``` H,n=map(int,input().split(" ")) res=0 s=0 for h in range(H,0,-1): res+=1 if s ^ ( n > 1 << (h-1) ): res+= (1 << h) - 1 else: s^=1 if n>1<<(h-1): n-=1<<(h-1) print(res) ```
output
1
104,844
13
209,689
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,845
13
209,690
Tags: implementation, math, trees Correct Solution: ``` h, N = tuple(int(i) for i in input().split()) L = 1 R = pow(2,h) mode = 0 level = 0 ans = 0 while(L!=R): M = (L+R)//2 if(N<=M): if(mode==0): mode = 1 ans+=1 else: ans+=pow(2,h-level) R = M else: if(mode==0): ans+=pow(2,h-level) else: mode = 0 ans+=1 L = M+1 level+=1 print(ans) ```
output
1
104,845
13
209,691
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,846
13
209,692
Tags: implementation, math, trees Correct Solution: ``` line = input().split() h = int(line[0]) n = int(line[1]) last = 1 th = 2 ** h ans = 1 l = 1 r = th while th > 0: mid = (l + r) // 2 if n <= mid: if last == 1: ans += 1 else: ans += th last = 0 r = mid else: if last == 0: ans += 1 else: ans += th last = 1 l = mid + 1 th = th // 2 print(str(ans - 2)) ```
output
1
104,846
13
209,693
Provide tags and a correct Python 3 solution for this coding contest problem. Amr bought a new video game "Guess Your Way Out!". The goal of the game is to find an exit from the maze that looks like a perfect binary tree of height h. The player is initially standing at the root of the tree and the exit from the tree is located at some leaf node. Let's index all the leaf nodes from the left to the right from 1 to 2h. The exit is located at some node n where 1 ≤ n ≤ 2h, the player doesn't know where the exit is so he has to guess his way out! Amr follows simple algorithm to choose the path. Let's consider infinite command string "LRLRLRLRL..." (consisting of alternating characters 'L' and 'R'). Amr sequentially executes the characters of the string using following rules: * Character 'L' means "go to the left child of the current node"; * Character 'R' means "go to the right child of the current node"; * If the destination node is already visited, Amr skips current command, otherwise he moves to the destination node; * If Amr skipped two consecutive commands, he goes back to the parent of the current node before executing next command; * If he reached a leaf node that is not the exit, he returns to the parent of the current node; * If he reaches an exit, the game is finished. Now Amr wonders, if he follows this algorithm, how many nodes he is going to visit before reaching the exit? Input Input consists of two integers h, n (1 ≤ h ≤ 50, 1 ≤ n ≤ 2h). Output Output a single integer representing the number of nodes (excluding the exit node) Amr is going to visit before reaching the exit by following this algorithm. Examples Input 1 2 Output 2 Input 2 3 Output 5 Input 3 6 Output 10 Input 10 1024 Output 2046 Note A perfect binary tree of height h is a binary tree consisting of h + 1 levels. Level 0 consists of a single node called root, level h consists of 2h nodes called leaves. Each node that is not a leaf has exactly two children, left and right one. Following picture illustrates the sample test number 3. Nodes are labeled according to the order of visit. <image>
instruction
0
104,847
13
209,694
Tags: implementation, math, trees Correct Solution: ``` def n_of_nodes(h): result = 0 for i in range(h): result += 2 ** i return result h, n = tuple(map(int, input().split())) way = "" t = h while t: if n % 2: way = "L" + way n //= 2 n += 1 else: way = "R" + way n //= 2 t -= 1 answer = 1 current = "L" t = h for i in way: if i == current: answer += 1 if current == "L": current = "R" else: current = "L" else: answer += n_of_nodes(t) + 1 t -= 1 print(answer - 1) ```
output
1
104,847
13
209,695
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
instruction
0
104,947
13
209,894
Tags: dfs and similar, dp, greedy, implementation, trees Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) memo = {} def path(t,s): ps = set() dt = list(d[t]) for k in dt: if k not in memo: continue if memo[k] in ps: d[k] -= set([t]) d[t] -= set([k]) ps.add(memo[k]) if s == -1 and len(ps) == 2: memo[t] = sum(ps) + 2 return memo[t] if len(ps) > 1: return -t if len(ps) == 0: memo[t] = 0 return 0 memo[t] = list(ps)[0] + 1 return memo[t] def _path(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] def _path2(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s or k in memo: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] t = _path(1,-1) if t < 0: t = _path2(-t,-1) if t > 0: while t%2 == 0: t//=2 return t return -1 print(main()) ```
output
1
104,947
13
209,895
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
instruction
0
104,948
13
209,896
Tags: dfs and similar, dp, greedy, implementation, trees Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) memo = {} def path(t,s): ps = set() dt = list(d[t]) for k in dt: if k not in memo: continue ps.add(memo[k]) if s == -1 and len(ps) == 2: memo[t] = sum(ps) + 2 return memo[t] if len(ps) > 1: return -t if len(ps) == 0: memo[t] = 0 return 0 memo[t] = list(ps)[0] + 1 return memo[t] def _path(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] def _path2(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s or k in memo: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] t = _path(1,-1) if t < 0: t = _path2(-t,-1) if t > 0: while t%2 == 0: t//=2 return t return -1 print(main()) ```
output
1
104,948
13
209,897
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
instruction
0
104,949
13
209,898
Tags: dfs and similar, dp, greedy, implementation, trees Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) memo = [-1] * (n+1) def path(t,s): ps = set() dt = list(d[t]) for k in dt: if memo[k] < 0: continue ps.add(memo[k]) if s == -1 and len(ps) == 2: memo[t] = sum(ps) + 2 return memo[t] if len(ps) > 1: return -t if len(ps) == 0: memo[t] = 0 return 0 memo[t] = list(ps)[0] + 1 return memo[t] def _path(tt,ss): f = [False] * (n+1) q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s or memo[k] >= 0: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] t = _path(1,-1) if t < 0: t = _path(-t,-1) if t > 0: while t%2 == 0: t//=2 return t return -1 print(main()) ```
output
1
104,949
13
209,899
Provide tags and a correct Python 3 solution for this coding contest problem. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path.
instruction
0
104,950
13
209,900
Tags: dfs and similar, dp, greedy, implementation, trees Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) memo = [-1] * (n+1) def path(t,s): ps = set() dt = list(d[t]) for k in dt: if memo[k] < 0: continue ps.add(memo[k]) if s == -1 and len(ps) == 2: memo[t] = sum(ps) + 2 return memo[t] if len(ps) > 1: return -t if len(ps) == 0: memo[t] = 0 return 0 memo[t] = list(ps)[0] + 1 return memo[t] def _path(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] def _path2(tt,ss): q = [(tt,ss)] tq = [] qi = 0 while len(q) > qi: t,s = q[qi] for k in d[t]: if k == s or memo[k] >= 0: continue q.append((k,t)) qi += 1 for t,s in q[::-1]: r = path(t,s) if r < 0: return r return memo[tt] t = _path(1,-1) if t < 0: t = _path2(-t,-1) if t > 0: while t%2 == 0: t//=2 return t return -1 print(main()) ```
output
1
104,950
13
209,901
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path. Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**6) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) tf = 54066 in d[44923] if tf: return d def path(t,s): ps = set() dt = list(d[t]) for k in dt: if k == s: continue f,pt = path(k,t) if f == False: return (False, pt) ps.add(pt) if s == -1 and len(ps) == 2: return (True, sum(ps) + 2) if len(ps) > 1: return (False, t) if len(ps) == 0: return (True, 0) return (True,list(ps)[0] + 1) if 54066 in d[44923]: try: print(1) f,t = path(1,-1) return (f,t) except: print(sys.exc_info()) return (1,2) return (1,2) f,t = path(1,-1) if f: while t%2 == 0: t//=2 return t f,t = path(t,-1) if f: while t%2 == 0: t//=2 return t return -1 print(main()) ```
instruction
0
104,951
13
209,902
No
output
1
104,951
13
209,903
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path. Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = {} for _ in range(n-1): a,b = LI() if a not in d: d[a] = [] if b not in d: d[b] = [] d[a].append(b) d[b].append(a) tf = 54066 in d[44923] def path(t,s): ps = set() for k in d[t]: if k == s: continue f,pt = path(k,t) if f == False: return (False, pt) ps.add(pt) if len(ps) > 2: return (False, t) if s == -1: if tf: return (True, 1) if len(ps) == 2: return (True, sum(list(ps)) + 2) if len(ps) == 1: return (True, list(ps)[0] + 1) if len(ps) > 1: return (False, t) if len(ps) == 0: return (True, 0) return (True,list(ps)[0] + 1) f,t = path(n//2+1,-1) if not f: f,t = path(t,-1) if f: if t == 0: return 0 while t%2 == 0: t//=2 return t return -1 try: print(main()) except: print("Unexpected error:", sys.exc_info()[0]) ```
instruction
0
104,952
13
209,904
No
output
1
104,952
13
209,905
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path. Submitted Solution: ``` import sys from collections import defaultdict from collections import Counter def debug(x, table): for name, val in table.items(): if x is val: print('DEBUG:{} -> {}'.format(name, val), file=sys.stderr) return None def solve(): n = int(input()) Adj = [[] for i in range(n)] for i in range(n - 1): u, v = map(int, input().split()) u, v = u - 1, v - 1 Adj[u].append(v) Adj[v].append(u) # debug(Adj, locals()) path_ls = defaultdict(Counter) trace_deg1(n, Adj, path_ls) # debug(path_ls, locals()) min_ = float('inf') for u in path_ls: if len(path_ls[u]) == 1: if path_ls[u][l] >= 2: min_ = min(min_, l) if min_ == float('inf'): ans = -1 else: ans = min_ print(ans) def trace_deg1(n, Adj, path_ls): for u in range(n): if len(Adj[u]) == 1: # debug(u, locals()) path_l = 2 v = Adj[u][0] while len(Adj[v]) == 2: path_l += 1 v, u = sum(Adj[v]) - u, v path_ls[v][path_l] += 1 return None if __name__ == '__main__': solve() ```
instruction
0
104,953
13
209,906
No
output
1
104,953
13
209,907
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vanya wants to minimize a tree. He can perform the following operation multiple times: choose a vertex v, and two disjoint (except for v) paths of equal length a0 = v, a1, ..., ak, and b0 = v, b1, ..., bk. Additionally, vertices a1, ..., ak, b1, ..., bk must not have any neighbours in the tree other than adjacent vertices of corresponding paths. After that, one of the paths may be merged into the other, that is, the vertices b1, ..., bk can be effectively erased: <image> Help Vanya determine if it possible to make the tree into a path via a sequence of described operations, and if the answer is positive, also determine the shortest length of such path. Input The first line of input contains the number of vertices n (2 ≤ n ≤ 2·105). Next n - 1 lines describe edges of the tree. Each of these lines contains two space-separated integers u and v (1 ≤ u, v ≤ n, u ≠ v) — indices of endpoints of the corresponding edge. It is guaranteed that the given graph is a tree. Output If it is impossible to obtain a path, print -1. Otherwise, print the minimum number of edges in a possible path. Examples Input 6 1 2 2 3 2 4 4 5 1 6 Output 3 Input 7 1 2 1 3 3 4 1 5 5 6 6 7 Output -1 Note In the first sample case, a path of three edges is obtained after merging paths 2 - 1 - 6 and 2 - 4 - 5. It is impossible to perform any operation in the second sample case. For example, it is impossible to merge paths 1 - 3 - 4 and 1 - 5 - 6, since vertex 6 additionally has a neighbour 7 that is not present in the corresponding path. Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return list(map(int, input().split())) def II(): return int(input()) def LS(): return input().split() def S(): return input() def main(): n = II() d = {} ds = [{}] for _ in range(n-1): a,b = LI() if a not in d: d[a] = [] if b not in d: d[b] = [] d[a].append(b) d[b].append(a) tf = 44923 in d and 54066 in d[44923] if tf: return max(d.keys()) def path(t,s): ps = set() for k in d[t]: if k == s: continue f,pt = path(k,t) if f == False: return (False, pt) if tf: ps.add(1) else: ps.add(pt) if len(ps) > 2: return (False, t) if s == -1: if tf: return (True, 1) if len(ps) == 2: return (True, sum(list(ps)) + 2) if len(ps) == 1: return (True, list(ps)[0] + 1) if len(ps) > 1: if tf: return (False, 1) return (False, t) if len(ps) == 0: return (True, 0) if tf: return (True, 1) return (True,list(ps)[0] + 1) f,t = path(n//2+1,-1) if not f: f,t = path(t,-1) if f: if t == 0: return 0 while t%2 == 0: t//=2 return t return -1 try: print(main()) except: print("Unexpected error:", sys.exc_info()[0]) ```
instruction
0
104,954
13
209,908
No
output
1
104,954
13
209,909
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a special connected undirected graph where each vertex belongs to at most one simple cycle. Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance. Input The first line of input contains two integers n and m (1 ≤ n ≤ 5⋅ 10^5), the number of nodes and the number of edges, respectively. Each of the following m lines contains two integers u and v (1 ≤ u,v ≤ n, u ≠ v), and represents an edge connecting the two nodes u and v. Each pair of nodes is connected by at most one edge. It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle. Output Print n space-separated integers, the i-th integer represents the maximum distance between node i and a leaf if the removed edges were chosen in a way that minimizes this distance. Examples Input 9 10 7 2 9 2 1 6 3 1 4 3 4 7 7 6 9 8 5 8 5 9 Output 5 3 5 4 5 4 3 5 4 Input 4 4 1 2 2 3 3 4 4 1 Output 2 2 2 2 Note In the first sample, a possible way to minimize the maximum distance from vertex 1 is by removing the marked edges in the following image: <image> Note that to minimize the answer for different nodes, you can remove different edges. Submitted Solution: ``` print("Hello") ```
instruction
0
105,025
13
210,050
No
output
1
105,025
13
210,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a special connected undirected graph where each vertex belongs to at most one simple cycle. Your task is to remove as many edges as needed to convert this graph into a tree (connected graph with no cycles). For each node, independently, output the maximum distance between it and a leaf in the resulting tree, assuming you were to remove the edges in a way that minimizes this distance. Input The first line of input contains two integers n and m (1 ≤ n ≤ 5⋅ 10^5), the number of nodes and the number of edges, respectively. Each of the following m lines contains two integers u and v (1 ≤ u,v ≤ n, u ≠ v), and represents an edge connecting the two nodes u and v. Each pair of nodes is connected by at most one edge. It is guaranteed that the given graph is connected and each vertex belongs to at most one simple cycle. Output Print n space-separated integers, the i-th integer represents the maximum distance between node i and a leaf if the removed edges were chosen in a way that minimizes this distance. Examples Input 9 10 7 2 9 2 1 6 3 1 4 3 4 7 7 6 9 8 5 8 5 9 Output 5 3 5 4 5 4 3 5 4 Input 4 4 1 2 2 3 3 4 4 1 Output 2 2 2 2 Note In the first sample, a possible way to minimize the maximum distance from vertex 1 is by removing the marked edges in the following image: <image> Note that to minimize the answer for different nodes, you can remove different edges. Submitted Solution: ``` print('5 3 5 4 5 4 3 5 4') ```
instruction
0
105,026
13
210,052
No
output
1
105,026
13
210,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree. Today he celebrates his birthday again! He found a directed graph without loops as a present from his parents. Since Sergey is a very curious boy, he immediately came up with a thing to do. He decided to find a set Q of vertices in this graph, such that no two vertices x, y ∈ Q are connected by an edge, and it is possible to reach any vertex z ∉ Q from some vertex of Q in no more than two moves. After a little thought, Sergey was able to solve this task. Can you solve it too? A vertex y is reachable from a vertex x in at most two moves if either there is a directed edge (x,y), or there exist two directed edges (x,z) and (z, y) for some vertex z. Input The first line of input contains two positive integers n and m (1 ≤ n ≤ 1 000 000, 1 ≤ m ≤ 1 000 000) — the number of vertices and the number of edges in the directed graph. Each of the following m lines describes a corresponding edge. Each one contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the beginning and the end of the i-th edge. The graph may contain multiple edges between the same pair of vertices. Output First print the number k — the number of selected vertices. Then print k distinct integers — the indices of the selected vertices. If multiple answers exist you can output any of them. In particular, you don't have to minimize the number of vertices in the set. It is guaranteed, that there is always at least one valid set. Examples Input 5 4 1 2 2 3 2 4 2 5 Output 4 1 3 4 5 Input 3 3 1 2 2 3 3 1 Output 1 3 Note In the first sample, the vertices 1, 3, 4, 5 are not connected. The vertex 2 is reachable from vertex 1 by one edge. In the second sample, it is possible to reach the vertex 1 in one move and the vertex 2 in two moves. The following pictures illustrate sample tests and their answers. <image> <image> Submitted Solution: ``` _input = input().split() n = int(_input[0]) m = int(_input[1]) present = [True for i in range(n)] save = [False for i in range(n)] adj = [[] for i in range(n)] for i in range(m): vertex = input().split() v = int(vertex[0]) w = int(vertex[1]) adj[v-1].append(w - 1) for i in range(n): if present[i]: save[i] = True for v in adj[i]: present[v] = False present[i] = False for i in range(n-1, -1, -1): if save[i]: for v in adj[i]: save[v] = False for i in range(n): if save[i]: print(i+1) ```
instruction
0
105,252
13
210,504
No
output
1
105,252
13
210,505
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sergey just turned five years old! When he was one year old, his parents gave him a number; when he was two years old, his parents gave him an array of integers. On his third birthday he received a string. When he was four, his mother woke him up in a quiet voice, wished him to be a good boy and gave him a rooted tree. Today he celebrates his birthday again! He found a directed graph without loops as a present from his parents. Since Sergey is a very curious boy, he immediately came up with a thing to do. He decided to find a set Q of vertices in this graph, such that no two vertices x, y ∈ Q are connected by an edge, and it is possible to reach any vertex z ∉ Q from some vertex of Q in no more than two moves. After a little thought, Sergey was able to solve this task. Can you solve it too? A vertex y is reachable from a vertex x in at most two moves if either there is a directed edge (x,y), or there exist two directed edges (x,z) and (z, y) for some vertex z. Input The first line of input contains two positive integers n and m (1 ≤ n ≤ 1 000 000, 1 ≤ m ≤ 1 000 000) — the number of vertices and the number of edges in the directed graph. Each of the following m lines describes a corresponding edge. Each one contains two integers a_i and b_i (1 ≤ a_i, b_i ≤ n, a_i ≠ b_i) — the beginning and the end of the i-th edge. The graph may contain multiple edges between the same pair of vertices. Output First print the number k — the number of selected vertices. Then print k distinct integers — the indices of the selected vertices. If multiple answers exist you can output any of them. In particular, you don't have to minimize the number of vertices in the set. It is guaranteed, that there is always at least one valid set. Examples Input 5 4 1 2 2 3 2 4 2 5 Output 4 1 3 4 5 Input 3 3 1 2 2 3 3 1 Output 1 3 Note In the first sample, the vertices 1, 3, 4, 5 are not connected. The vertex 2 is reachable from vertex 1 by one edge. In the second sample, it is possible to reach the vertex 1 in one move and the vertex 2 in two moves. The following pictures illustrate sample tests and their answers. <image> <image> Submitted Solution: ``` from sys import stdout from sys import stdin def print_fast(string): stdout.write(string + '\n') _input = input().split() n = int(_input[0]) m = int(_input[1]) count = 0 present = [] save = [] adj = [] saved = [] for i in range(n): present.append(True) save.append(False) adj.append([]) for i in range(m): vertex = stdin.readline().split() v = int(vertex[0]) w = int(vertex[1]) adj[v-1].append(w - 1) for i in range(n): if present[i]: save[i] = True saved.append(i) for v in adj[i]: present[v] = False present[i] = False ans = [] n = len(saved) for i in saved: if save[i]: count += 1 ans.append(str(i+1)) for v in adj[i]: save[v] = False print(count) print_fast(' '.join(ans)) ```
instruction
0
105,253
13
210,506
No
output
1
105,253
13
210,507
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,289
13
210,578
Tags: graphs Correct Solution: ``` import sys input = sys.stdin.readline class Unionfind: def __init__(self, n): self.par = [-1]*n self.rank = [1]*n def root(self, x): p = x while not self.par[p]<0: p = self.par[p] while x!=p: tmp = x x = self.par[x] self.par[tmp] = p return p def unite(self, x, y): rx, ry = self.root(x), self.root(y) if rx==ry: return False if self.rank[rx]<self.rank[ry]: rx, ry = ry, rx self.par[rx] += self.par[ry] self.par[ry] = rx if self.rank[rx]==self.rank[ry]: self.rank[rx] += 1 def is_same(self, x, y): return self.root(x)==self.root(y) def count(self, x): return -self.par[self.root(x)] n, m = map(int, input().split()) d = [0]*n adj_list = [[] for _ in range(n)] edges = [] ans = [] for _ in range(m): v, u = map(int, input().split()) d[v-1] += 1 d[u-1] += 1 adj_list[v-1].append(u-1) adj_list[u-1].append(v-1) edges.append((u-1, v-1)) uf = Unionfind(n) max_d = max(d) for i in range(n): if d[i]==max_d: for j in adj_list[i]: uf.unite(i, j) ans.append((i, j)) break for s, t in edges: if not uf.is_same(s, t): uf.unite(s, t) ans.append((s, t)) for s, t in ans: print(s+1, t+1) ```
output
1
105,289
13
210,579
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,290
13
210,580
Tags: graphs Correct Solution: ``` import math from collections import defaultdict as dd def printTree(s): q = [s] visited[s] = 1 while(q): cur = q.pop(-1) for i in graph[cur]: if visited[i] == 0: visited[i] = 1 print(cur, i) q.append(i) n, m = [int(i) for i in input().split()] graph = dd(list) visited = [0 for i in range(n + 1)] for _ in range(m): u, v = [int(i) for i in input().split()] graph[u].append(v) graph[v].append(u) max_deg_node = 0 mx = 0 for i in range(1, n + 1): cur = len(graph[i]) if cur > mx: mx = cur max_deg_node = i printTree(max_deg_node) ```
output
1
105,290
13
210,581
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,291
13
210,582
Tags: graphs Correct Solution: ``` from collections import deque n, m = map(int, input().split()) e = [] a = [[] for i in range(n)] for i in range(m): fr, to = map(int, input().split()) e.append((fr, to)) a[fr - 1].append(to - 1) a[to - 1].append(fr - 1) root = 0 maxPow = 0 for i in range(n): if len(a[i]) > maxPow: root = i maxPow = len(a[i]) visited = set() d = deque() d.append(root) visited.add(root) while len(d) != 0: cur = d.popleft() for adj in a[cur]: if adj not in visited: print(cur + 1, adj + 1) visited.add(adj) d.append(adj) ```
output
1
105,291
13
210,583
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,292
13
210,584
Tags: graphs Correct Solution: ``` n,m=[int(x) for x in input().split()] graph={} for i in range(m): a,b=[int(x) for x in input().split()] for a,b in (a,b),(b,a): if a not in graph: graph[a]=[b] else: graph[a].append(b) def tree(new): total=[] for v in new: for item in graph[v]: if item not in invite: total.append((v,item)) invite.add(item) new.append(item) return total index=max_rou=0 for v in graph: if len(graph[v])>max_rou: max_rou=len(graph[v]) index=v invite=set([index]) answer=(tree([index])) for i in range(n-1): print(*answer[i]) ```
output
1
105,292
13
210,585
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,293
13
210,586
Tags: graphs Correct Solution: ``` from collections import defaultdict,deque n,m,d = map(int, input().split()) g = defaultdict(list) for i in range(m): u,v = map(int,input().split()) g[u].append(v) g[v].append(u) init_set = set(g[1]) if d > len(g[1]): print('NO') exit() vis = set() vis.add(1) cluster = set() while init_set: node = init_set.pop() q = deque() q.append(node) vis.add(node) cluster.add(node) while q: u = q.popleft() for child in g[u]: if child not in vis: if child in init_set: init_set.remove(child) vis.add(child) q.append(child) if len(cluster) > d: print('NO') exit() q = deque() vis = set() vis.add(1) ans = [] for node in cluster: q.append(node) vis.add(node) ans.append((1,node)) cnt = d - len(cluster) for remain in g[1]: if cnt <= 0: break if remain not in cluster: q.append(remain) vis.add(remain) ans.append((1, remain)) cnt -= 1 while q: node = q.popleft() for child in g[node]: if child not in vis: vis.add(child) q.append(child) ans.append((node,child)) print('YES') for u,v in ans: print(u,v) ```
output
1
105,293
13
210,587
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,294
13
210,588
Tags: graphs Correct Solution: ``` import sys input = sys.stdin.readline n,m=map(int,input().split()) E=[list(map(int,input().split())) for i in range(m)] cost=[0]*(n+1) EDGELIST=[[] for i in range(n+1)] for x,y in E: cost[x]+=1 cost[y]+=1 EDGELIST[x].append(y) EDGELIST[y].append(x) x=cost.index(max(cost)) #print(x) from collections import deque QUE=deque([x]) check=[0]*(n+1) ANS=[] while QUE: x=QUE.popleft() check[x]=1 for to in EDGELIST[x]: if check[to]==0: ANS.append([x,to]) QUE.append(to) check[to]=1 #print(ANS) for x,y in ANS: print(x,y) ```
output
1
105,294
13
210,589
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,295
13
210,590
Tags: graphs Correct Solution: ``` n, m, d = map(int, input().split()) g = [[] for _ in range(n + 1)] haveOne = [False] * (n + 1) for i in range(m): u, v = map(int, input().split()) g[u].append(v) g[v].append(u) if u == 1: haveOne[v] = True if v == 1: haveOne[u] = True count = 0 group = [-1] * (n + 1) selectedOne = [] for i in range(2, n+1): if group[i] == -1: # bfs group[i] = count useOne = False if haveOne[i]: selectedOne.append(i) useOne = True if count >= d: count += 1 break incount = count + 1 qu = [] qu += g[i] while len(qu) > 0: c = qu.pop() if c != 1 and group[c] == -1: if haveOne[c] and not(useOne): selectedOne.append(c) useOne = True group[c] = count qu += g[c] count += 1 if count > d or d > len(g[1]): print('NO') else: diffOne = list(set(g[1]) - set(selectedOne)) diffOne = selectedOne + diffOne g[1] = diffOne[:d] visited = [False] * (n + 1) qVisit = [1] visited[1] = True print('YES') while len(qVisit) > 0: i = qVisit.pop() for j in g[i]: if not(visited[j]): print(i, j) visited[j] = True qVisit.append(j) ```
output
1
105,295
13
210,591
Provide tags and a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2.
instruction
0
105,296
13
210,592
Tags: graphs Correct Solution: ``` import sys import collections v, e = map(int, input().strip().split()) graph = collections.defaultdict(list) degree = [0 for i in range(v)] mx, src = 0, 0 for i in range(e): a, b = map(int, input().strip().split()) degree[a-1] += 1 graph[a].append(b) if degree[a-1] > mx: mx = degree[a-1] src = a degree[b-1] += 1 graph[b].append(a) if degree[b-1] > mx: mx = degree[b-1] src = b queue = collections.deque() queue.append(src) seen = set() seen.add(src) while queue: cur = queue.popleft() for i in graph[cur]: if i in seen: continue seen.add(i) queue.append(i) print(str(cur)+" " + str(i)+"\r") ```
output
1
105,296
13
210,593
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` def main(): n, m = map(int, input().split()) graph = [None] * n; center = (None, 0) for _ in range(m): u, v = map(int, input().split()) u -= 1; v -= 1 if graph[u]: graph[u].append(v) else: graph[u] = [v] if graph[v]: graph[v].append(u) else: graph[v] = [u] if len(graph[u]) > center[1]: center = (u, len(graph[u])) if len(graph[v]) > center[1]: center = (v, len(graph[v])) visited = {center[0]} to_do = [center[0]]; z = 0 while z < len(to_do): node = to_do[z] for conn in graph[node]: if conn in visited: continue visited.add(conn) to_do.append(conn) print(node + 1, conn + 1) z += 1 main() ```
instruction
0
105,297
13
210,594
Yes
output
1
105,297
13
210,595
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) d = defaultdict(list) contador = defaultdict(int) for i in range(m): a, b = map(int, input().split()) contador[a] += 1 contador[b] += 1 d[a].append(b) d[b].append(a) maxi = max(contador.values()) maxi_vertice = [v for v in d.keys() if contador[v] == maxi][0] ans = [] veri = [0] * (n + 1) veri[maxi_vertice] = 1 count = 0 q = [maxi_vertice] while count < n-1: x = q.pop() for v in d[x]: if veri[v]: continue else: ans.append((x, v)) veri[v] = 1 count += 1 q.append(v) for i in range(n-1): print(*ans[i]) ```
instruction
0
105,298
13
210,596
Yes
output
1
105,298
13
210,597
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` n, m = map(int, input().split()) dl = [0]*(n+1) cl = [] g = [list() for i in range(n+1)] for i in range(m): u, v = map(int, input().split()) g[u].append(v) g[v].append(u) dl[u]+=1 dl[v]+=1 cl.append((u, v)) pos = dl.index(max(dl)) dl = [0]*(n+1) queue = [] dl[pos] = 1 for u in g[pos]: print(pos, u) queue.append(u) dl[u] = 1 for u in queue: for v in g[u]: if dl[v]!=1: print(u, v) dl[v] = 1 queue.append(v) ```
instruction
0
105,299
13
210,598
Yes
output
1
105,299
13
210,599
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` # 1133F1 import collections def do(): graph = collections.defaultdict(list) nodes, edges = map(int, input().split(" ")) ind = [0] * (nodes + 1) for _ in range(edges): x, y = map(int, input().split(" ")) graph[x].append(y) graph[y].append(x) ind[x] += 1 ind[y] += 1 root = 1 mi = ind[1] for i in range(1, nodes + 1): if ind[i] > mi: mi = ind[i] root = i seen = [0] * (nodes + 1) seen[root] = 1 res = set() q = collections.deque() for nei in graph[root]: seen[nei] = 1 res.add((root, nei)) q.append(nei) while q: cur = q.popleft() for nei in graph[cur]: if not seen[nei]: seen[nei] = 1 res.add((cur, nei)) q.append(nei) for x, y in list(res): print(str(x) + " " + str(y)) return 0 do() ```
instruction
0
105,300
13
210,600
Yes
output
1
105,300
13
210,601
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` import sys input = sys.stdin.readline def factorial(x, m): val = 1 while x > 0: val = (val * x) % m x -= 1 return val def fact(x): val = 1 while x > 0: val *= x x -= 1 return val # swap_array function def swaparr(arr, a, b): temp = arr[a] arr[a] = arr[b] arr[b] = temp def gcd(a, b): if b == 0: return a return gcd(b, a % b) def nCr(n, k): if k > n: return 0 if (k > n - k): k = n - k res = 1 for i in range(k): res = res * (n - i) res = res / (i + 1) return int(res) ## prime factorization def primefs(n): primes = {} while (n % 2 == 0 and n > 0): primes[2] = primes.get(2, 0) + 1 n = n // 2 for i in range(3, int(n ** 0.5) + 2, 2): while (n % i == 0 and n > 0): primes[i] = primes.get(i, 0) + 1 n = n // i if n > 2: primes[n] = primes.get(n, 0) + 1 ## prime factoriazation of n is stored in dictionary ## primes and can be accesed. O(sqrt n) return primes ## MODULAR EXPONENTIATION FUNCTION def power(x, y, p): res = 1 x = x % p if (x == 0): return 0 while (y > 0): if ((y & 1) == 1): res = (res * x) % p y = y >> 1 x = (x * x) % p return res ## returns an array of boolean if primes or not USING SIEVE OF ERATOSTHANES def sieve(n): prime = [True for i in range(n + 1)] prime[0], prime[1] = False, False p = 2 while (p * p <= n): if (prime[p] == True): for i in range(p * p, n + 1, p): prime[i] = False p += 1 return prime def is_prime(n): if n == 0: return False if n == 1: return True for i in range(2, int(n ** (1 / 2)) + 1): if not n % i: return False return True #### PRIME FACTORIZATION IN O(log n) using Sieve #### MAXN = int(1e5 + 5) import math def spf_sieve(): spf[1] = 1 for i in range(2, MAXN): spf[i] = i for i in range(4, MAXN, 2): spf[i] = 2 for i in range(3, math.ceil(MAXN ** 0.5), 2): if spf[i] == i: for j in range(i * i, MAXN, i): if spf[j] == j: spf[j] = i spf = [0 for i in range(MAXN)] # spf_sieve(); def factoriazation(x): res = [] for i in range(2, int(x ** 0.5) + 1): while x % i == 0: res.append(i) x //= i if x != 1: res.append(x) return res def factors(n): res = [] for i in range(1, int(n ** 0.5) + 1): if n % i == 0: res.append(i) res.append(n // i) return list(set(res)) def int_array(): return list(map(int, input().strip().split())) def float_array(): return list(map(float, input().strip().split())) def str_array(): return input().strip().split() # defining a couple constants MOD = int(1e9) + 7 CMOD = 998244353 INF = float('inf') NINF = -float('inf') ################### ---------------- TEMPLATE ENDS HERE ---------------- ################### from itertools import permutations import math from bisect import bisect_left #for _ in range(int(input())): from collections import Counter # c=sorted((i,int(val))for i,val in enumerate(input().split())) import heapq # c=sorted((i,int(val))for i,val in enumerate(input().split())) # n = int(input()) # ls = list(map(int, input().split())) # n, k = map(int, input().split()) # n =int(input()) # arr=[(i,x) for i,x in enum] # arr.sort(key=lambda x:x[0]) # e=list(map(int, input().split())) from collections import Counter # print("\n".join(ls)) # print(os.path.commonprefix(ls[0:2])) # n=int(input()) from bisect import bisect_right # d=sorted(d,key=lambda x:(len(d[x]),-x)) d=dictionary d={x:set() for x in arr} # n=int(input()) # n,m,k= map(int, input().split()) import heapq # for _ in range(int(input())): # n,k=map(int, input().split()) #for _ in range(int(input())): #n = int(input()) # code here ;)) #n,k=map(int, input().split()) #arr = list(map(int, input().split())) #ls= list(map(int, input().split())) import math #n = int(input()) #n,k=map(int, input().split()) #for _ in range(int(input())): #n = int(input()) #n,l=map(int,input().split()) #for _ in range(int(input())): def divisors_seive(n): divisors=[10**6+6] for i in range(1,n+1): for j in range(i,n+1): divisors[j]+=1 #n=int(input()) #n=int(input()) import bisect from collections import deque ans=[] def dfs(s): vis[s]=1 for i in gg[s]: if vis[i]==0: ans.append([s+1,i+1]) dfs(i) def find(x): if par[x]==x: return x return find(par[x]) def union(x,y): xroot=find(x) yroot=find(y) if rank[xroot]>rank[yroot]: par[yroot]=xroot rank[xroot]+=rank[yroot] else: par[xroot] =yroot rank[yroot]+=rank[xroot] n,m,d=map(int,input().split()) vis=[0]*(n+1) rank=[1 for i in range(n)] par=[i for i in range(n)] q=[] vis=[0]*(n+1) g=[[] for i in range(n)] ind=[0]*n gg=[[] for i in range(n)] ind=0 for i in range(m): u,v= map(int, input().split()) g[u-1].append(v-1) g[v-1].append(u-1) if u!=1 and v!=1: union(u-1,v-1) gg[u-1].append(v-1) gg[v-1].append(u-1) else: ind+=1 component=0 for i in range(1,n): if par[i]==i: component+=1 gg[0].append(i) gg[i].append(0) if component>d or d>ind: print("NO") else: dfs(0) print("YES") for i in ans: print(*i) ```
instruction
0
105,301
13
210,602
No
output
1
105,301
13
210,603
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 unweighted connected graph consisting of n vertices and m edges. It is guaranteed that there are no self-loops or multiple edges in the given graph. Your task is to find any spanning tree of this graph such that the maximum degree over all vertices is maximum possible. Recall that the degree of a vertex is the number of edges incident to it. Input The first line contains two integers n and m (2 ≤ n ≤ 2 ⋅ 10^5, n - 1 ≤ m ≤ min(2 ⋅ 10^5, (n(n-1))/(2))) — the number of vertices and edges, respectively. The following m lines denote edges: edge i is represented by a pair of integers v_i, u_i (1 ≤ v_i, u_i ≤ n, u_i ≠ v_i), which are the indices of vertices connected by the edge. There are no loops or multiple edges in the given graph, i. e. for each pair (v_i, u_i) there are no other pairs (v_i, u_i) or (u_i, v_i) in the list of edges, and for each pair (v_i, u_i) the condition v_i ≠ u_i is satisfied. Output Print n-1 lines describing the edges of a spanning tree such that the maximum degree over all vertices is maximum possible. Make sure that the edges of the printed spanning tree form some subset of the input edges (order doesn't matter and edge (v, u) is considered the same as the edge (u, v)). If there are multiple possible answers, print any of them. Examples Input 5 5 1 2 2 3 3 5 4 3 1 5 Output 3 5 2 1 3 2 3 4 Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 4 1 1 2 1 3 Input 8 9 1 2 2 3 2 5 1 6 3 4 6 5 4 5 2 7 5 8 Output 3 2 2 5 8 5 6 1 2 7 1 2 3 4 Note Picture corresponding to the first example: <image> In this example the number of edges of spanning tree incident to the vertex 3 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the second example: <image> In this example the number of edges of spanning tree incident to the vertex 1 is 3. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. Picture corresponding to the third example: <image> In this example the number of edges of spanning tree incident to the vertex 2 is 4. It is the maximum degree over all vertices of the spanning tree. It is easy to see that we cannot obtain a better answer. But because this example is symmetric, we can choose almost the same spanning tree but with vertex 5 instead of 2. Submitted Solution: ``` def find(x): if(par[x]==x): return x par[x]=find(par[x]) return par[x] def union(a,b): xa=find(a) xb=find(b) if(xa==xb): return 0 if(size[xa]>size[xb]): xa,xb=xb,xa par[xa]=xb size[xb]+=size[xa] return 1 n,m,d=map(int,input().split()) par=[i for i in range(n+1)] size=[1 for i in range(n+1)] count=0 ans=0 last=[] arr=[] one_saver=[] for i in range(m): a,b=map(int,input().split()) if(a==1 or b==1): if(a==1): one_saver.append(b) else: one_saver.append(a) elif(union(a,b)): last.append([a,b]) dif_par=set() for i in range(2,n+1): par[i]=find(par[i]) if par[i] not in dif_par: dif_par.add(par[i]) flag=0 if(d>len(one_saver) or d<len(dif_par)): flag=1 print("NO") idntfy1=set() idntfy2=set() idntfy3=set() if(flag==0): print("YES") for i in one_saver: if par[i] not in idntfy1: print(1,i) idntfy1.add(par[i]) idntfy2.add(i) idntfy3.add(i) i=0 j=0 while(j<d-len(dif_par)): if one_saver[i] not in idntfy2: print(one_saver[i],1) j+=1 idntfy3.add(one_saver[i]) i+=1 for i in last: if i[0] not in idntfy3 or i[1] not in idntfy3: print(i[0],i[1]) ```
instruction
0
105,302
13
210,604
No
output
1
105,302
13
210,605