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 directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,493
13
168,986
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from collections import deque def cyc(n,path): visi,poi = [2]+[0]*(n-1),[0]*n inf = [] multi = [] st = [0] while len(st): x,y = st[-1],poi[st[-1]] if y == len(path[x]): visi[st.pop()] = 1 else: z = path[x][y] if visi[z] == 2: inf.append(z) poi[x] += 1 continue if visi[z] == 1: multi.append(z) poi[x] += 1 continue st.append(z) poi[x] += 1 visi[z] = 2 ans = [1]*n for i in range(n): if not visi[i]: ans[i] = 0 curr = deque(multi) vv = [0]*n for i in multi: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = 2 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) curr = deque(inf) vv = [0]*n for i in inf: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = -1 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) return ans def main(): for _ in range(int(input())): input() n,m = map(int,input().split()) path = [[] for _ in range(n)] for _ in range(m): aa,bb = map(int,input().split()) path[aa-1].append(bb-1) print(*cyc(n,path)) # Fast IO Region 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") if __name__ == "__main__": main() ```
output
1
84,493
13
168,987
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,494
13
168,988
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO,IOBase from collections import deque def cyc(n,path): visi,poi = [2]+[0]*(n-1),[0]*n inf = [] multi = [] st = [0] while len(st): x,y = st[-1],poi[st[-1]] if y == len(path[x]): visi[st.pop()] = 1 else: z = path[x][y] if visi[z] == 2: inf.append(z) poi[x] += 1 continue if visi[z] == 1: multi.append(z) poi[x] += 1 continue st.append(z) poi[x] += 1 visi[z] = 2 ans = [1]*n for i in range(n): if not visi[i]: ans[i] = 0 curr = deque(multi) vv = [0]*n for i in multi: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = 2 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) curr = deque(inf) vv = [0]*n for i in inf: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = -1 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) return ans def main(): for _ in range(int(input())): input() n,m = map(int,input().split()) path = [[] for _ in range(n)] for _ in range(m): aa,bb = map(int,input().split()) path[aa-1].append(bb-1) print(*cyc(n,path)) # region fastio BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self,file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) self.newlines = b.count(b"\n")+(not b) ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd,self.buffer.getvalue()) self.buffer.truncate(0),self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self,file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s:self.buffer.write(s.encode("ascii")) self.read = lambda:self.buffer.read().decode("ascii") self.readline = lambda:self.buffer.readline().decode("ascii") sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout) input = lambda:sys.stdin.readline().rstrip("\r\n") # endregion if __name__ == "__main__": main() ```
output
1
84,494
13
168,989
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,495
13
168,990
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys sys.stderr = sys.stdout from collections import deque def solve(n, m, E): D = [[] for _ in range(n)] for u, v in E: D[u].append(v) P = [None] * n K = [0] * n V = [0] * n V[0] = 1 A = {0} i = 0 while i is not None: k = K[i] K[i] += 1 if k < len(D[i]): j = D[i][k] if V[j] == 0: P[j] = i V[j] = 1 A.add(j) i = j elif j in A: V[j] = -1 elif V[j] == 1: V[j] = 2 else: A.remove(i) i = P[i] Q = deque(i for i in range(n) if V[i] == -1) while Q: i = Q.pop() for j in D[i]: if V[j] != -1: V[j] = -1 Q.append(j) Q = deque(i for i in range(n) if V[i] == 2) while Q: i = Q.pop() for j in D[i]: if V[j] == 1: V[j] = 2 Q.append(j) return V def reade(): u, v = readinti() return u-1, v-1 def case(): input() n, m = readinti() E = [reade() for _ in range(m)] return lstr(solve(n, m, E)) def main(): t = readint() print('\n'.join(case() for _ in range(t))) ########## def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintt(): return tuple(readinti()) def readintl(): return list(readinti()) def readinttl(k): return [readintt() for _ in range(k)] def readintll(k): return [readintl() for _ in range(k)] def lstr(l): return ' '.join(map(str, l)) def llstr(ll): return '\n'.join(map(lstr, ll)) def log(*args, **kwargs): print(*args, **kwargs, file=sys.__stderr__) if __name__ == '__main__': main() ```
output
1
84,495
13
168,991
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,496
13
168,992
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): x = input() n,m = map(int,input().split()) # kosaraju's algorithm to find sccs and create compressed graph adj = [[] for i in range(n+1)] radj = [[] for i in range(n+1)] # setup adj and radj for i in range(m): a,b = map(int,input().split()) adj[a].append(b) radj[b].append(a) toposort = [] vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1,n+1): if not vis[c]: vis[c] = 1 s = [c] while s: c = s[-1] if idx[c] < len(adj[c]): ne = adj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: toposort.append(c) s.pop() scc = [0]*(n+1) sccs = [[]] while toposort: c = toposort.pop() if scc[c] == 0: sccs.append([]) s = [c] while s: c = s.pop() if scc[c] == 0: scc[c] = len(sccs)-1 sccs[-1].append(c) for ne in radj[c]: if scc[ne] == 0: s.append(ne) compressed_adj = [[] for i in range(len(sccs))] compressed_radj = [[] for i in range(len(sccs))] cycle = [0] * len(sccs) for a in range(1,n+1): for b in adj[a]: if scc[a] != scc[b]: compressed_adj[scc[a]].append(scc[b]) compressed_radj[scc[b]].append(scc[a]) else: # size > 1 of self loop cycle[scc[a]] = 1 # begin to compute answer ans = [0]*(n+1) for i in range(1,len(sccs)): if 1 in sccs[i]: start = i # find the reachable nodes and put them in reachable cycles reachable_cycles = [] s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: reachable_cycles.append(c) else: # reachable, but set ans as 1 for now # ans could become -1 if a reachable cycle from 1 can reach it or 2 if not, but > 1 path from 1 for i in sccs[c]: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() # find the reachable nodes from the cycles reachable from 1 # these have ans = -1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in reachable_cycles: s = [c] while s: c = s[-1] if not vis[c]: vis[c] = 1 for i in sccs[c]: ans[i] = -1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() # find the # of paths via dp on the dag to see if remaining nodes with ans = 1 are 1 or 2 paths = [0]*(n+1) paths[start] = 1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 if not vis[scc[c]]: vis[scc[c]] = 1 s = [scc[c]] while s: c = s[-1] if len(sccs[c]) > 1: raise RuntimeError if idx[c] < len(compressed_radj[c]): ne = compressed_radj[c][idx[c]] if not cycle[ne] and not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: for ne in compressed_adj[c]: if not cycle[ne]: paths[ne] += paths[c] s.pop() for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 ans[c] = 2 if paths[scc[c]] > 1 else 1 # yay answer print(*ans[1:]) ```
output
1
84,496
13
168,993
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,497
13
168,994
Tags: dfs and similar, dp, graphs, 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 -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] for _ in range(int(input()) if True else 1): empty = input() n, m = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() graph = [[] for __ in range(n + 1)] self = [False] * (n + 1) for i in range(m): x, y = map(int, input().split()) if x == y: self[x] = True graph[x] += [y] visited = [False] * (n + 1) multiple = [False] * (n + 1) queue = [1] visited[1] = True while queue: x = queue.pop() for y in graph[x]: if not visited[y]: visited[y] = True queue += [y] else: if not multiple[y]: multiple[y] = True queue += [y] infinite = [False] * (n + 1) for comp in find_SCC(graph): if len(comp) > 1 or (len(comp) == 1 and self[comp[0]]): if not infinite[comp[0]] and visited[comp[0]]: queue = comp for x in queue: infinite[x] = True while queue: x = queue.pop() for y in graph[x]: if not infinite[y]: infinite[y] = True queue += [y] ans = [] for i in range(1, n + 1): if infinite[i] and multiple[i]: ans += [-1] elif multiple[i]: ans += [2] elif visited[i]: ans += [1] else: ans += [0] print(*ans) ```
output
1
84,497
13
168,995
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,498
13
168,996
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): x = input() n,m = map(int,input().split()) # kosaraju's algorithm to find sccs and create compressed graph adj = [[] for i in range(n+1)] radj = [[] for i in range(n+1)] # setup graph (adj, radj) for i in range(m): a,b = map(int,input().split()) adj[a].append(b) radj[b].append(a) toposort = [] vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1,n+1): if not vis[c]: vis[c] = 1 s = [c] while s: c = s[-1] if idx[c] < len(adj[c]): ne = adj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: toposort.append(c) s.pop() scc = [0]*(n+1) sccs = [[]] while toposort: c = toposort.pop() if scc[c] == 0: sccs.append([]) s = [c] while s: c = s.pop() if scc[c] == 0: scc[c] = len(sccs)-1 sccs[-1].append(c) for ne in radj[c]: if scc[ne] == 0: s.append(ne) # set up compressed graph (compressed_adj, compressed_radj) compressed_adj = [[] for i in range(len(sccs))] compressed_radj = [[] for i in range(len(sccs))] cycle = [0] * len(sccs) for a in range(1,n+1): for b in adj[a]: if scc[a] != scc[b]: compressed_adj[scc[a]].append(scc[b]) compressed_radj[scc[b]].append(scc[a]) else: # size > 1 of self loop cycle[scc[a]] = 1 # begin to compute answer ans = [0]*(n+1) # everything from here will be done on the compressed graph for i in range(1,len(sccs)): if 1 in sccs[i]: start = i # find the reachable nodes from 1 and determine if they are reachable cycles reachable_cycles = [] s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: reachable_cycles.append(c) else: # reachable, but set ans as 1 for now # ans could become -1 if a reachable cycle from 1 can reach it or 2 if not, but > 1 path from 1 for i in sccs[c]: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() # find the reachable nodes from the cycles reachable from 1 # set their ans = -1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in reachable_cycles: s = [c] while s: c = s[-1] if not vis[c]: vis[c] = 1 for i in sccs[c]: ans[i] = -1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() # find the # of paths via dp on the dag to see if remaining nodes with ans = 1 are 1 or 2 paths = [0]*(n+1) paths[start] = 1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 if not vis[scc[c]]: vis[scc[c]] = 1 s = [scc[c]] while s: c = s[-1] if len(sccs[c]) > 1: raise RuntimeError if idx[c] < len(compressed_radj[c]): ne = compressed_radj[c][idx[c]] if not cycle[ne] and not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: for ne in compressed_adj[c]: if not cycle[ne]: paths[ne] += paths[c] s.pop() for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 ans[c] = 2 if paths[scc[c]] > 1 else 1 # yay answer print(*ans[1:]) ```
output
1
84,498
13
168,997
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,499
13
168,998
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` #!/usr/bin/env python import os import sys from io import BytesIO,IOBase from collections import deque def cyc(n,path): visi,poi = [2]+[0]*(n-1),[0]*n inf = [] multi = [] st = [0] while len(st): x,y = st[-1],poi[st[-1]] if y == len(path[x]): visi[st.pop()] = 1 else: z = path[x][y] if visi[z] == 2: inf.append(z) poi[x] += 1 continue if visi[z] == 1: multi.append(z) poi[x] += 1 continue st.append(z) poi[x] += 1 visi[z] = 2 ans = [1]*n for i in range(n): if not visi[i]: ans[i] = 0 curr = deque(multi) vv = [0]*n for i in multi: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = 2 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) curr = deque(inf) vv = [0]*n for i in inf: vv[i] = 1 while len(curr): x = curr.popleft() ans[x] = -1 for y in path[x]: if not vv[y]: vv[y] = 1 curr.append(y) return ans def main(): for _ in range(int(input())): input() n,m = map(int,input().split()) path = [[] for _ in range(n)] for _ in range(m): aa,bb = map(int,input().split()) path[aa-1].append(bb-1) print(*cyc(n,path)) if __name__ == "__main__": main() ```
output
1
84,499
13
168,999
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` def naiveSolve(): return from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def main(): t=int(input()) allans=[] for _ in range(t): input() n,m=readIntArr() adj=[[] for __ in range(n+1)] for __ in range(m): u,v=readIntArr() adj[u].append(v) visitCnts=[0]*(n+1) revisitedNodeCyc=set() revisitedNodeNonCyc=set() path=set() @bootstrap def dfs1(node): for nex in adj[node]: if visitCnts[nex]==1: if nex in path: revisitedNodeCyc.add(nex) else: revisitedNodeNonCyc.add(nex) else: visitCnts[nex]+=1 path.add(nex) yield dfs1(nex) path.remove(nex) yield None path.add(1) visitCnts[1]=1 dfs1(1) @bootstrap def dfsCyc(node): for nex in adj[node]: if visitCnts[nex]==1: visitCnts[nex]=-1 yield dfsCyc(nex) yield None for cycNode in revisitedNodeCyc: if visitCnts[cycNode]==1: visitCnts[cycNode]=-1 dfsCyc(cycNode) @bootstrap def dfsNonCyc(node): for nex in adj[node]: if visitCnts[nex]==1: visitCnts[nex]=2 yield dfsNonCyc(nex) yield None for nonCycNode in revisitedNodeNonCyc: if visitCnts[nonCycNode]==1: visitCnts[nonCycNode]=2 dfsNonCyc(nonCycNode) visitCnts.pop(0) allans.append(visitCnts) multiLineArrayOfArraysPrint(allans) return import sys input=sys.stdin.buffer.readline #FOR READING PURE INTEGER INPUTS (space separation ok) # input=lambda: sys.stdin.readline().rstrip("\r\n") #FOR READING STRING/TEXT INPUTS. def oneLineArrayPrint(arr): print(' '.join([str(x) for x in arr])) def multiLineArrayPrint(arr): print('\n'.join([str(x) for x in arr])) def multiLineArrayOfArraysPrint(arr): print('\n'.join([' '.join([str(x) for x in y]) for y in arr])) def readIntArr(): return [int(x) for x in input().split()] # def readFloatArr(): # return [float(x) for x in input().split()] def makeArr(defaultValFactory,dimensionArr): # eg. makeArr(lambda:0,[n,m]) dv=defaultValFactory;da=dimensionArr if len(da)==1:return [dv() for _ in range(da[0])] else:return [makeArr(dv,da[1:]) for _ in range(da[0])] def queryInteractive(x): print('{}'.format(x)) sys.stdout.flush() return int(input()) def answerInteractive(ans): print('! {}'.format(ans)) sys.stdout.flush() inf=float('inf') # MOD=10**9+7 MOD=998244353 from math import gcd,floor,ceil # from math import floor,ceil # for Python2 for _abc in range(1): main() ```
instruction
0
84,500
13
169,000
Yes
output
1
84,500
13
169,001
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] for _ in range (int(input())): input() n,m = [int(i) for i in input().split()] g = [[] for i in range (n)] scc = [] for i in range (m): u,v = [int(i)-1 for i in input().split()] g[u].append(v) if u==v: scc.append([u]) s1 = find_SCC(g) for i in s1: if len(i)>1: scc.append(i[:]) infinite = [0]*n for i in scc: for j in i: infinite[j]=-1 vis = [0]*n stack = [0] vis[0]=1 if infinite[0]: vis[0]=-1 stack1 = [0] while(len(stack1)): curr1 = stack1.pop() for i1 in g[curr1]: if vis[i1]!=-1: vis[i1]=-1 stack1.append(i1) while(stack): curr = stack.pop() for i in g[curr]: if not vis[i]: stack.append(i) vis[i]=1 if infinite[i]: vis[i]=-1 stack1 = [i] while(len(stack1)): curr1 = stack1.pop() for i1 in g[curr1]: if vis[i1]!=-1: vis[i1]=-1 stack1.append(i1) elif vis[i]==1: vis[i]+=1 stack.append(i) print(*vis) ```
instruction
0
84,501
13
169,002
Yes
output
1
84,501
13
169,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` #!/usr/bin/env python3 import sys import getpass # not available on codechef from collections import Counter, defaultdict, deque input = sys.stdin.readline # to read input quickly # available on Google, AtCoder Python3, not available on Codeforces # import numpy as np # import scipy M9 = 10**9 + 7 # 998244353 yes, no = "YES", "NO" # d4 = [(1,0),(0,1),(-1,0),(0,-1)] # d8 = [(1,0),(1,1),(0,1),(-1,1),(-1,0),(-1,-1),(0,-1),(1,-1)] # d6 = [(2,0),(1,1),(-1,1),(-2,0),(-1,-1),(1,-1)] # hexagonal layout MAXINT = sys.maxsize # if testing locally, print to terminal with a different color OFFLINE_TEST = getpass.getuser() == "hkmac" # OFFLINE_TEST = False # codechef does not allow getpass def log(*args): if OFFLINE_TEST: print('\033[36m', *args, '\033[0m', file=sys.stderr) def solve(*args): # screen input if OFFLINE_TEST: log("----- solving ------") log(*args) log("----- ------- ------") return solve_(*args) def read_matrix(rows): return [list(map(int,input().split())) for _ in range(rows)] def read_strings(rows): return [input().strip() for _ in range(rows)] def minus_one(arr): return [x-1 for x in arr] def minus_one_matrix(mrr): return [[x-1 for x in row] for row in mrr] # ---------------------------- template ends here ---------------------------- # https://codeforces.com/blog/entry/80158?locale=en from types import GeneratorType def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: if stack: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc def solve_(n, edges): # your solution here parents = set() visitable = set() cycles = set() duals = set() g = defaultdict(set) for a,b in edges: # if a == b: # cycles.add(a) # continue g[a].add(b) @bootstrap def dfs(cur): visitable.add(cur) parents.add(cur) for nex in g[cur]: if nex in parents: cycles.add(nex) continue if nex in visitable: duals.add(nex) continue yield dfs(nex) parents.discard(cur) yield dfs(0) stack = list(duals) while stack: cur = stack.pop() for nex in g[cur]: if nex in duals: continue duals.add(nex) stack.append(nex) stack = list(cycles) while stack: cur = stack.pop() for nex in g[cur]: if nex in cycles: continue cycles.add(nex) stack.append(nex) # log(visitable) # log(cycles) # log(duals) res = [0]*n for i in range(n): if i in cycles: res[i] = -1 continue if i in duals: res[i] = 2 continue if i in visitable: res[i] = 1 continue return res res_lst = [] # for case_num in [0]: # no loop over test case # for case_num in range(100): # if the number of test cases is specified for case_num in range(int(input())): # read line as an integer # k = int(input()) # read line as a string srr = input().strip() # read one line and parse each word as a string # lst = input().split() # read one line and parse each word as an integer n,m = list(map(int,input().split())) # lst = list(map(int,input().split())) # lst = minus_one(lst) # read multiple rows # arr = read_strings(k) # and return as a list of str edges = read_matrix(m) # and return as a list of list of int edges = minus_one_matrix(edges) res = solve(n, edges) # include input here # print length if applicable # print(len(res)) # parse result res = " ".join(str(x) for x in res) # res = "\n".join(str(x) for x in res) # res = "\n".join(" ".join(str(x) for x in row) for row in res) res_lst.append(res) # print result # print("Case #{}: {}".format(case_num+1, res)) # Google and Facebook - case number required print("\n".join(res_lst)) ```
instruction
0
84,502
13
169,004
Yes
output
1
84,502
13
169,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] for _ in range (int(input())): input() n,m = [int(i) for i in input().split()] g = [[] for i in range (n)] scc = [] for i in range (m): u,v = [int(i)-1 for i in input().split()] g[u].append(v) if u==v: scc.append([u]) s1 = find_SCC(g) for i in s1: if len(i)>1: scc.append(i[:]) infinite = [0]*n for i in scc: for j in i: infinite[j]=-1 vis = [0]*n stack = [0] vis[0]=1 if infinite[0]: vis[0]=-1 stack1 = [0] while(len(stack1)): curr1 = stack1.pop() for i1 in g[curr1]: if vis[i1]!=-1: vis[i1]=-1 stack1.append(i1) while(stack): curr = stack.pop() for i in g[curr]: if not vis[i]: stack.append(i) vis[i]=1 if infinite[i]: vis[i]=-1 stack1 = [i] while(len(stack1)): curr1 = stack1.pop() for i1 in g[curr1]: if vis[i1]!=-1: vis[i1]=-1 stack1.append(i1) elif vis[i]==1: vis[i]+=1 stack.append(i) print(*vis) ```
instruction
0
84,503
13
169,006
Yes
output
1
84,503
13
169,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): x = input() n,m = map(int,input().split()) adj = [[] for i in range(n+1)] radj = [[] for i in range(n+1)] # setup adj and radj for i in range(m): a,b = map(int,input().split()) adj[a].append(b) radj[b].append(a) toposort = [] vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1,n+1): if not vis[c]: vis[c] = 1 s = [c] while s: c = s[-1] if idx[c] < len(adj[c]): ne = adj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: toposort.append(c) s.pop() scc = [0]*(n+1) sccs = [[]] while toposort: c = toposort.pop() if scc[c] == 0: sccs.append([]) s = [c] while s: c = s.pop() if scc[c] == 0: scc[c] = len(sccs)-1 sccs[-1].append(c) for ne in radj[c]: if scc[ne] == 0: s.append(ne) compressed_adj = [[] for i in range(len(sccs))] compressed_radj = [[] for i in range(len(sccs))] cycle = [0] * len(sccs) for a in range(1,n+1): for b in adj[a]: if scc[a] != scc[b]: compressed_adj[scc[a]].append(scc[b]) compressed_radj[scc[b]].append(scc[a]) else: # size > 1 of self loop cycle[scc[a]] = 1 ans = [0]*(n+1) for i in range(1,len(sccs)): if 1 in sccs[i]: start = i s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) cycle_on_path = 0 #infinite now while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: cycle_on_path += 1 for i in sccs[c]: if cycle_on_path: ans[i] = -1 else: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] s.append(ne) idx[c] += 1 else: if cycle[c]: cycle_on_path -= 1 s.pop() paths = [0]*(n+1) paths[1] = 1 vis[1] = 1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 if not vis[scc[c]]: vis[scc[c]] = 1 s = [scc[c]] while s: c = s[-1] if idx[c] < len(compressed_radj[c]): ne = compressed_radj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: for ne in compressed_adj[c]: paths[ne] += paths[c] s.pop() for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 ans[c] = 2 if paths[scc[c]] > 1 else 1 print(*ans[1:]) ```
instruction
0
84,504
13
169,008
No
output
1
84,504
13
169,009
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted 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 -------------------- from math import ceil def prod(a, mod=10 ** 9 + 7): ans = 1 for each in a: ans = (ans * each) % mod return ans def gcd(x, y): while y: x, y = y, x % y return x def lcm(a, b): return a * b // gcd(a, b) def binary(x, length=16): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y """ Given a directed graph, find_SCC returns a list of lists containing the strongly connected components in topological order. Note that this implementation can be also be used to check if a directed graph is a DAG, and in that case it can be used to find the topological ordering of the nodes. """ def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] for _ in range(int(input()) if True else 1): e = (input()) n, m = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() graph = [[] for i in range(n + 1)] for i in range(m): x, y = map(int, input().split()) graph[x] += [y] from collections import deque def bfs(graph, alpha=1): """Breadth first search on a graph!""" n = len(graph) q = deque([alpha]) ans = [0] * n used = [False] * n used[alpha] = True dist, parents = [10**6] * n, [-1] * n dist[alpha] = 0 while q: v = q.popleft() if ans[v] == -1 or ans[v] == 2:continue if parents[v] != -1 and ans[parents[v]] == -1: ans[v] = -1 else: ans[v] += 1 for u in graph[v]: if dist[u] < dist[v] or u == v: ans[v] = -1 q.append(u) dist[u] = min(dist[u], dist[v] + 1) parents[u] = v return ans def shortest_path(graph, alpha, omega): """Returns the shortest path between two vertices!""" used, dist, parents = bfs(graph, alpha) if not used[omega]: return [] path = [omega] v = omega while parents[v] != -1: path += [parents[v]] v = parents[v] return path[::-1] ans = bfs(graph, 1) print(*ans[1:]) ```
instruction
0
84,505
13
169,010
No
output
1
84,505
13
169,011
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): x = input() n,m = map(int,input().split()) adj = [[] for i in range(n+1)] radj = [[] for i in range(n+1)] # setup adj and radj for i in range(m): a,b = map(int,input().split()) adj[a].append(b) radj[b].append(a) toposort = [] vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1,n+1): if not vis[c]: vis[c] = 1 s = [c] while s: c = s[-1] if idx[c] < len(adj[c]): ne = adj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: toposort.append(c) s.pop() scc = [0]*(n+1) sccs = [[]] while toposort: c = toposort.pop() if scc[c] == 0: sccs.append([]) s = [c] while s: c = s.pop() if scc[c] == 0: scc[c] = len(sccs)-1 sccs[-1].append(c) for ne in radj[c]: if scc[ne] == 0: s.append(ne) compressed_adj = [[] for i in range(len(sccs))] compressed_radj = [[] for i in range(len(sccs))] cycle = [0] * len(sccs) for a in range(1,n+1): for b in adj[a]: if scc[a] != scc[b]: compressed_adj[scc[a]].append(scc[b]) compressed_radj[scc[b]].append(scc[a]) else: # size > 1 of self loop cycle[scc[a]] = 1 ans = [0]*(n+1) for i in range(1,len(sccs)): if 1 in sccs[i]: start = i s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) cycle_on_path = 0 #infinite now while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: cycle_on_path += 1 for i in sccs[c]: if cycle_on_path: ans[i] = -1 else: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] s.append(ne) idx[c] += 1 else: if cycle[c]: cycle_on_path -= 1 s.pop() paths = [0]*(n+1) paths[1] = 1 vis[1] = 1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 if not vis[scc[c]]: vis[scc[c]] = 1 s = [scc[c]] while s: c = s[-1] if len(sccs[c]) < 1: raise RuntimeError if idx[c] < len(compressed_radj[c]): ne = compressed_radj[c][idx[c]] if ans[ne] == 1 and not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: for ne in compressed_adj[c]: paths[ne] += paths[c] s.pop() for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 ans[c] = 2 if paths[scc[c]] > 1 else 1 print(*ans[1:]) ```
instruction
0
84,506
13
169,012
No
output
1
84,506
13
169,013
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1 Submitted Solution: ``` import sys,os,io input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] return SCC[::-1] for _ in range (int(input())): input() n,m = [int(i) for i in input().split()] g = [[] for i in range (n)] scc = [] for i in range (m): u,v = [int(i)-1 for i in input().split()] g[u].append(v) if u==v: scc.append([u]) s1 = find_SCC(g) for i in s1: if len(i)>1: scc.append(i[:]) infinite = [0]*n for i in scc: stack = [i[0]] while(stack): curr = stack.pop() for j in g[curr]: if not infinite[j]: infinite[j] = -1 stack.append(j) vis = infinite[:] stack = [0] if not vis[0]: vis[0]=1 while(stack): curr = stack.pop() for i in g[curr]: if not vis[i]: stack.append(i) vis[i]=1 elif vis[i]!=-1: vis[i]+=1 print(*vis) ```
instruction
0
84,507
13
169,014
No
output
1
84,507
13
169,015
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. <image> Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra. Input The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n. Output If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them. Examples Input 9 12 2 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 8 7 9 1 Output YES 4 1 5 6 9 3 2 Input 7 10 3 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 Output NO Note The first sample is depicted on the picture below: <image> Submitted Solution: ``` from collections import OrderedDict n, m, h, t = map(int, input().split()) nodes = [set() for i in range(0, n+1, 1)] def output(i, j, set1, set2): print("YES") print(i, j) set1.remove(j) set2.remove(i) for x in set1: print(x, end=" ") print("") for x in set2: print(x, end=" ") def is_hydra(set1, set2, i, j): global h, t if j not in set1: return False if not set1.isdisjoint(set2): return False if len(set1)==h+1 and len(set2)==t+1: output(i, j, set1, set2) return True if len(set2)==h+1 and len(set1)==t+1: output(j, i, set2, set1) return True return False for i in range(m): n1, n2 = map(int, input().split()) nodes[n1].add(n2) nodes[n2].add(n1) for i in range(1, n+1, 1): for j in range(i+1, n+1, 1): if is_hydra(nodes[i], nodes[j], i, j): exit() print("NO") ```
instruction
0
84,508
13
169,016
No
output
1
84,508
13
169,017
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. <image> Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra. Input The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n. Output If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them. Examples Input 9 12 2 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 8 7 9 1 Output YES 4 1 5 6 9 3 2 Input 7 10 3 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 Output NO Note The first sample is depicted on the picture below: <image> Submitted Solution: ``` n, m, h, t = list(map(int,input().split())) edges = [] degre = [0 for _ in range(n+1)] voisins = [ [] for _ in range(n+1)] for i in range(m) : a,b = list(map(int,input().split())) edges.append((a,b)) degre[a]+=1 voisins[a].append(b) degre[b]+=1 voisins[b].append(a) #Il faut trouver un couple de sommets voisins de degrés respectivement h+1 et t+1 candidats_t = [] candidats_h = [] for i in range(n) : if degre[i] == t+1 : candidats_t.append(i) elif degre[i] == h+1 : candidats_h.append(i) i_t = -1 i_h = -1 paires = [] for i in candidats_h : for j in voisins[i] : if j in candidats_t : paires.append((i,j)) for (i,j) in paires : test_disjoins = True for v_i in voisins[i] : if v_i in voisins[j] : test_disjoins = False if test_disjoins : i_t = j i_h = i break if i_t == -1 : print("NO") else : print("YES") print(i_h, i_t) s = "" for i in voisins[i_h] : if i != i_t : s+= str(i) + " " print(s) s = "" for i in voisins[i_t] : if i != i_h : s+= str(i) + " " print(s) ```
instruction
0
84,509
13
169,018
No
output
1
84,509
13
169,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. <image> Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra. Input The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n. Output If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them. Examples Input 9 12 2 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 8 7 9 1 Output YES 4 1 5 6 9 3 2 Input 7 10 3 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 Output NO Note The first sample is depicted on the picture below: <image> Submitted Solution: ``` ## https://codeforces.com/contest/244/problem/D n, m, h, t = map(int, input().split()) g = {} e = [] for _ in range(m): u, v = map(int, input().split()) if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) e.append([u, v]) def pr(a): print(' '.join([str(x) for x in a])) def check(u, v, h, t, g): max_ht = max(h, t) min_ht = min(h, t) max_uv = max(len(g[u]), len(g[v])) - 1 min_uv = min(len(g[u]), len(g[v])) - 1 if min_uv < min_ht: return False, [], [] elif max_uv >= h+t: big = u if len(g[u]) - 1 == max_uv else v small = v if len(g[v]) - 1 == min_uv else u s = [] b = [] used = {} while len(s) < min_ht: for x in g[small]: if x == big:continue s.append(x) used[x] = True while len(b) < max_ht: for x in g[big]: if x == small:continue if x not in used: b.append(x) return True, [small, big], [s, b] else: big = u if len(g[u]) - 1 == max_uv else v small = v if len(g[v]) - 1 == min_uv else u #print(u, v) #print(g[u], g[v]) b = {x:True for x in g[big]} del b[small] s = {} common = [] for x in g[small]: if x == big:continue if x in b: del b[x] common.append(x) else: s[x] = True if len(s) < min_ht: while len(s) < min_ht and len(common) > 0: s[common.pop()] = True if len(b) < max_ht: while len(b) < max_ht and len(common) > 0: b[common.pop()] = True if len(s) < min_ht or len(b) < max_ht: return False, [], [] return True, [small, big], [list(s.keys())[:min_ht], list(b.keys())[:max_ht]] flag = False for u, v in e: flg, sb, sb_list = check(u, v, h, t, g) if flg == True: flag = True print('YES') if h == len(sb_list[0]): pr(sb) pr(sb_list[0]) pr(sb_list[1]) else: print(sb[1], sb[0]) pr(sb_list[1]) pr(sb_list[0]) break if flag == False: print('NO') #9 12 2 3 #1 2 #2 3 #1 3 #1 4 #2 5 #4 5 #4 6 #6 5 #6 7 #7 5 #8 7 #9 1 ```
instruction
0
84,510
13
169,020
No
output
1
84,510
13
169,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. One day Petya got a birthday present from his mom: a book called "The Legends and Myths of Graph Theory". From this book Petya learned about a hydra graph. A non-oriented graph is a hydra, if it has a structure, shown on the figure below. Namely, there are two nodes u and v connected by an edge, they are the hydra's chest and stomach, correspondingly. The chest is connected with h nodes, which are the hydra's heads. The stomach is connected with t nodes, which are the hydra's tails. Note that the hydra is a tree, consisting of h + t + 2 nodes. <image> Also, Petya's got a non-directed graph G, consisting of n nodes and m edges. Petya got this graph as a last year birthday present from his mom. Graph G contains no self-loops or multiple edges. Now Petya wants to find a hydra in graph G. Or else, to make sure that the graph doesn't have a hydra. Input The first line contains four integers n, m, h, t (1 ≤ n, m ≤ 105, 1 ≤ h, t ≤ 100) — the number of nodes and edges in graph G, and the number of a hydra's heads and tails. Next m lines contain the description of the edges of graph G. The i-th of these lines contains two integers ai and bi (1 ≤ ai, bi ≤ n, a ≠ b) — the numbers of the nodes, connected by the i-th edge. It is guaranteed that graph G contains no self-loops and multiple edges. Consider the nodes of graph G numbered with integers from 1 to n. Output If graph G has no hydra, print "NO" (without the quotes). Otherwise, in the first line print "YES" (without the quotes). In the second line print two integers — the numbers of nodes u and v. In the third line print h numbers — the numbers of the nodes that are the heads. In the fourth line print t numbers — the numbers of the nodes that are the tails. All printed numbers should be distinct. If there are multiple possible answers, you are allowed to print any of them. Examples Input 9 12 2 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 8 7 9 1 Output YES 4 1 5 6 9 3 2 Input 7 10 3 3 1 2 2 3 1 3 1 4 2 5 4 5 4 6 6 5 6 7 7 5 Output NO Note The first sample is depicted on the picture below: <image> Submitted Solution: ``` token = input().split() n = int(token[0]) m = int(token[1]) h = int(token[2]) t = int(token[3]) g = [[] for x in range(n)] for i in range(m): token = [int(x) - 1 for x in input().split()] g[token[0]].append(token[1]) g[token[1]].append(token[0]) posible_u = list(filter(lambda x: len(g[x]) > h, range(n))) pu_set = set(posible_u) posible_v = set(filter(lambda x: len(g[x]) > t, range(n))) def hyd(): for x in posible_u: for y in g[x]: if (y in posible_v): if len(set(g[x]) & set(g[y])) == 0: print("YES") print(x+1,y+1) s = "" for i in g[x]: if (i != y): s += str(i+1) + " " print(s) s = "" for i in g[y]: if (i != x): s += str(i+1) + " " print(s) return True return False if not hyd(): print("NO") ```
instruction
0
84,511
13
169,022
No
output
1
84,511
13
169,023
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 × T_2 in a following way. Let V be the set of vertices in T_1 and U be the set of vertices in T_2. Then the set of vertices of graph T_1 × T_2 is V × U, that is, a set of ordered pairs of vertices, where the first vertex in pair is from V and the second — from U. Let's draw the following edges: * Between (v, u_1) and (v, u_2) there is an undirected edge, if u_1 and u_2 are adjacent in U. * Similarly, between (v_1, u) and (v_2, u) there is an undirected edge, if v_1 and v_2 are adjacent in V. Please see the notes section for the pictures of products of trees in the sample tests. Let's examine the graph T_1 × T_2. How much cycles (not necessarily simple) of length k it contains? Since this number can be very large, print it modulo 998244353. The sequence of vertices w_1, w_2, ..., w_k, where w_i ∈ V × U called cycle, if any neighboring vertices are adjacent and w_1 is adjacent to w_k. Cycles that differ only by the cyclic shift or direction of traversal are still considered different. Input First line of input contains three integers — n_1, n_2 and k (2 ≤ n_1, n_2 ≤ 4000, 2 ≤ k ≤ 75) — number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively. Then follow n_1 - 1 lines describing the first tree. Each of this lines contains two integers — v_i, u_i (1 ≤ v_i, u_i ≤ n_1), which define edges of the first tree. Then follow n_2 - 1 lines, which describe the second tree in the same format. It is guaranteed, that given graphs are trees. Output Print one integer — number of cycles modulo 998244353. Examples Input 2 2 2 1 2 1 2 Output 8 Input 2 2 4 1 2 1 2 Output 32 Input 2 3 4 1 2 1 2 1 3 Output 70 Input 4 2 2 1 2 1 3 1 4 1 2 Output 20 Note The following three pictures illustrate graph, which are products of the trees from sample tests. In the first example, the list of cycles of length 2 is as follows: * «AB», «BA» * «BC», «CB» * «AD», «DA» * «CD», «DC» <image> <image> <image> Submitted Solution: ``` print("big pddooppkhu") ```
instruction
0
84,798
13
169,596
No
output
1
84,798
13
169,597
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 × T_2 in a following way. Let V be the set of vertices in T_1 and U be the set of vertices in T_2. Then the set of vertices of graph T_1 × T_2 is V × U, that is, a set of ordered pairs of vertices, where the first vertex in pair is from V and the second — from U. Let's draw the following edges: * Between (v, u_1) and (v, u_2) there is an undirected edge, if u_1 and u_2 are adjacent in U. * Similarly, between (v_1, u) and (v_2, u) there is an undirected edge, if v_1 and v_2 are adjacent in V. Please see the notes section for the pictures of products of trees in the sample tests. Let's examine the graph T_1 × T_2. How much cycles (not necessarily simple) of length k it contains? Since this number can be very large, print it modulo 998244353. The sequence of vertices w_1, w_2, ..., w_k, where w_i ∈ V × U called cycle, if any neighboring vertices are adjacent and w_1 is adjacent to w_k. Cycles that differ only by the cyclic shift or direction of traversal are still considered different. Input First line of input contains three integers — n_1, n_2 and k (2 ≤ n_1, n_2 ≤ 4000, 2 ≤ k ≤ 75) — number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively. Then follow n_1 - 1 lines describing the first tree. Each of this lines contains two integers — v_i, u_i (1 ≤ v_i, u_i ≤ n_1), which define edges of the first tree. Then follow n_2 - 1 lines, which describe the second tree in the same format. It is guaranteed, that given graphs are trees. Output Print one integer — number of cycles modulo 998244353. Examples Input 2 2 2 1 2 1 2 Output 8 Input 2 2 4 1 2 1 2 Output 32 Input 2 3 4 1 2 1 2 1 3 Output 70 Input 4 2 2 1 2 1 3 1 4 1 2 Output 20 Note The following three pictures illustrate graph, which are products of the trees from sample tests. In the first example, the list of cycles of length 2 is as follows: * «AB», «BA» * «BC», «CB» * «AD», «DA» * «CD», «DC» <image> <image> <image> Submitted Solution: ``` print("big pddoopp") ```
instruction
0
84,799
13
169,598
No
output
1
84,799
13
169,599
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 × T_2 in a following way. Let V be the set of vertices in T_1 and U be the set of vertices in T_2. Then the set of vertices of graph T_1 × T_2 is V × U, that is, a set of ordered pairs of vertices, where the first vertex in pair is from V and the second — from U. Let's draw the following edges: * Between (v, u_1) and (v, u_2) there is an undirected edge, if u_1 and u_2 are adjacent in U. * Similarly, between (v_1, u) and (v_2, u) there is an undirected edge, if v_1 and v_2 are adjacent in V. Please see the notes section for the pictures of products of trees in the sample tests. Let's examine the graph T_1 × T_2. How much cycles (not necessarily simple) of length k it contains? Since this number can be very large, print it modulo 998244353. The sequence of vertices w_1, w_2, ..., w_k, where w_i ∈ V × U called cycle, if any neighboring vertices are adjacent and w_1 is adjacent to w_k. Cycles that differ only by the cyclic shift or direction of traversal are still considered different. Input First line of input contains three integers — n_1, n_2 and k (2 ≤ n_1, n_2 ≤ 4000, 2 ≤ k ≤ 75) — number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively. Then follow n_1 - 1 lines describing the first tree. Each of this lines contains two integers — v_i, u_i (1 ≤ v_i, u_i ≤ n_1), which define edges of the first tree. Then follow n_2 - 1 lines, which describe the second tree in the same format. It is guaranteed, that given graphs are trees. Output Print one integer — number of cycles modulo 998244353. Examples Input 2 2 2 1 2 1 2 Output 8 Input 2 2 4 1 2 1 2 Output 32 Input 2 3 4 1 2 1 2 1 3 Output 70 Input 4 2 2 1 2 1 3 1 4 1 2 Output 20 Note The following three pictures illustrate graph, which are products of the trees from sample tests. In the first example, the list of cycles of length 2 is as follows: * «AB», «BA» * «BC», «CB» * «AD», «DA» * «CD», «DC» <image> <image> <image> Submitted Solution: ``` print("big ppp") ```
instruction
0
84,800
13
169,600
No
output
1
84,800
13
169,601
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider a tree (that is, an undirected connected graph without loops) T_1 and a tree T_2. Let's define their cartesian product T_1 × T_2 in a following way. Let V be the set of vertices in T_1 and U be the set of vertices in T_2. Then the set of vertices of graph T_1 × T_2 is V × U, that is, a set of ordered pairs of vertices, where the first vertex in pair is from V and the second — from U. Let's draw the following edges: * Between (v, u_1) and (v, u_2) there is an undirected edge, if u_1 and u_2 are adjacent in U. * Similarly, between (v_1, u) and (v_2, u) there is an undirected edge, if v_1 and v_2 are adjacent in V. Please see the notes section for the pictures of products of trees in the sample tests. Let's examine the graph T_1 × T_2. How much cycles (not necessarily simple) of length k it contains? Since this number can be very large, print it modulo 998244353. The sequence of vertices w_1, w_2, ..., w_k, where w_i ∈ V × U called cycle, if any neighboring vertices are adjacent and w_1 is adjacent to w_k. Cycles that differ only by the cyclic shift or direction of traversal are still considered different. Input First line of input contains three integers — n_1, n_2 and k (2 ≤ n_1, n_2 ≤ 4000, 2 ≤ k ≤ 75) — number of vertices in the first tree, number of vertices in the second tree and the cycle length respectively. Then follow n_1 - 1 lines describing the first tree. Each of this lines contains two integers — v_i, u_i (1 ≤ v_i, u_i ≤ n_1), which define edges of the first tree. Then follow n_2 - 1 lines, which describe the second tree in the same format. It is guaranteed, that given graphs are trees. Output Print one integer — number of cycles modulo 998244353. Examples Input 2 2 2 1 2 1 2 Output 8 Input 2 2 4 1 2 1 2 Output 32 Input 2 3 4 1 2 1 2 1 3 Output 70 Input 4 2 2 1 2 1 3 1 4 1 2 Output 20 Note The following three pictures illustrate graph, which are products of the trees from sample tests. In the first example, the list of cycles of length 2 is as follows: * «AB», «BA» * «BC», «CB» * «AD», «DA» * «CD», «DC» <image> <image> <image> Submitted Solution: ``` print("big pp") ```
instruction
0
84,801
13
169,602
No
output
1
84,801
13
169,603
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,894
13
169,788
"Correct Solution: ``` import sys n = int(sys.stdin.buffer.readline()) mp = map(int, sys.stdin.buffer.read().split()) links = [set() for _ in range(n)] for x, y in zip(mp, mp): x -= 1 y -= 1 links[x].add(y) links[y].add(x) stack = [(0, -2)] grundy = [0] * n while stack: v, p = stack.pop() if p == -1: g = 0 # second visit (aggregate children and calculate self grundy) for u in links[v]: g ^= grundy[u] + 1 grundy[v] = g else: # first visit (stack children and remove parent) links[v].discard(p) stack.append((v, -1)) for u in links[v]: stack.append((u, v)) if grundy[0] == 0: print('Bob') else: print('Alice') ```
output
1
84,894
13
169,789
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,895
13
169,790
"Correct Solution: ``` class Tree(): def __init__(self, n, decrement=1): self.n = n self.edges = [[] for _ in range(n)] self.root = None self.depth = [-1]*n self.size = [1]*n # 部分木のノードの数 self.decrement = decrement def add_edge(self, u, v): u, v = u-self.decrement, v-self.decrement self.edges[u].append(v) self.edges[v].append(u) def add_edges(self, edges): for u, v in edges: u, v = u-self.decrement, v-self.decrement self.edges[u].append(v) self.edges[v].append(u) def set_root(self, root): root -= self.decrement self.root = root self.par = [-1]*self.n self.depth[root] = 0 self.order = [root] # 帰りがけに使う next_set = [root] while next_set: p = next_set.pop() for q in self.edges[p]: if self.depth[q] != -1: continue self.par[q] = p self.depth[q] = self.depth[p]+1 self.order.append(q) next_set.append(q) for p in self.order[::-1]: for q in self.edges[p]: if self.par[p] == q: continue self.size[p] += self.size[q] ######################################################################################################### import sys input = sys.stdin.readline N = int(input()) T = Tree(N, decrement=1) for _ in range(N-1): x, y = map(int, input().split()) T.add_edge(x, y) T.set_root(1) grundy = [0]*N for p in T.order[::-1]: for q in T.edges[p]: if T.par[p]==q: continue grundy[p]^=grundy[q]+1 print("Alice" if grundy[0]!=0 else "Bob") ```
output
1
84,895
13
169,791
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,896
13
169,792
"Correct Solution: ``` #!usr/bin/env python3 from collections import defaultdict, deque from heapq import heappush, heappop from itertools import permutations, accumulate import sys import math import bisect def LI(): return [int(x) for x in sys.stdin.buffer.readline().split()] def I(): return int(sys.stdin.buffer.readline()) def LS():return [list(x) for x in sys.stdin.readline().split()] def S(): res = list(sys.stdin.readline()) if res[-1] == "\n": return res[:-1] return res def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] sys.setrecursionlimit(1000000) mod = 1000000007 def solve(): n = I() v = [[] for i in range(n)] for i in range(n-1): a,b = LI() a -= 1 b -= 1 v[a].append(b) v[b].append(a) q = [0] q2 = [] g = [0]*n bfs = [1]*n bfs[0] = 0 d = [0]*n while q: x = q.pop() for y in v[x]: if bfs[y]: bfs[y] = 0 d[x] += 1 q.append(y) q2.append((x,y)) while q2: x,y = q2.pop() g[x] ^= g[y]+1 ans = g[0] if ans: print("Alice") else: print("Bob") return #Solve if __name__ == "__main__": solve() ```
output
1
84,896
13
169,793
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,897
13
169,794
"Correct Solution: ``` import sys sys.setrecursionlimit(9**9) n=int(input()) T=[[]for _ in"_"*(n+1)] for _ in range(n-1):a,b=map(int,input().split());T[a]+=b,;T[b]+=a, def d(v,p): r=0 for s in T[v]: if s!=p:r^=d(s,v)+1 return r print("ABloibc e"[d(1,1)<1::2]) ```
output
1
84,897
13
169,795
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,898
13
169,796
"Correct Solution: ``` import sys sys.setrecursionlimit(10**6) n = int(input()) adj = [[] for _ in range(n)] for _ in range(n-1): x, y = map(int, input().split()) adj[x-1].append(y-1) adj[y-1].append(x-1) visited = [False for _ in range(n)] def dfs(x): global visited nim = 0 for v in adj[x]: if visited[v] == False: visited[v] = True nim ^= dfs(v)+1 return nim visited[0] = True if dfs(0) == 0: print("Bob") else: print("Alice") ```
output
1
84,898
13
169,797
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,899
13
169,798
"Correct Solution: ``` import sys input = lambda: sys.stdin.readline().rstrip() from collections import deque N = int(input()) X = [[] for i in range(N)] for i in range(N-1): x, y = map(int, input().split()) X[x-1].append(y-1) X[y-1].append(x-1) P = [-1] * N Q = deque([0]) R = [] while Q: i = deque.popleft(Q) R.append(i) for a in X[i]: if a != P[i]: P[a] = i X[a].remove(i) deque.append(Q, a) G = [0] * N for i in R[::-1]: s = 0 for j in X[i]: s ^= G[j] G[i] = s + 1 print("Bob" if G[0] == 1 else "Alice") ```
output
1
84,899
13
169,799
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,900
13
169,800
"Correct Solution: ``` import sys import itertools # import numpy as np import time import math import heapq from collections import defaultdict sys.setrecursionlimit(10 ** 7) INF = 10 ** 18 MOD = 10 ** 9 + 7 read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines # map(int, input().split()) N = int(input()) adj = [[] for _ in range(N)] for i in range(N - 1): x, y = map(int, input().split()) x -= 1 y -= 1 adj[x].append(y) adj[y].append(x) def dfs(v, p): nim = 0 for u in adj[v]: if u == p: continue nim ^= dfs(u, v) if p == -1: return nim nim += 1 return nim res = dfs(0, -1) if res: print("Alice") else: print("Bob") ```
output
1
84,900
13
169,801
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob
instruction
0
84,901
13
169,802
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) N = int(input()) graph = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) checked = [False]*N def dfs(p): checked[p] = True g = 0 for np in graph[p]: if not checked[np]: g ^= dfs(np)+1 return g if dfs(0) == 0: print("Bob") else: print("Alice") ```
output
1
84,901
13
169,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` class Tree(): def __init__(self, n, edge, indexed=1): self.n = n self.tree = [[] for _ in range(n)] for e in edge: self.tree[e[0] - indexed].append(e[1] - indexed) self.tree[e[1] - indexed].append(e[0] - indexed) def setroot(self, root): self.root = root self.parent = [None for _ in range(self.n)] self.parent[root] = -1 self.order = [] self.order.append(root) stack = [root] while stack: node = stack.pop() for adj in self.tree[node]: if self.parent[adj] is None: self.parent[adj] = node self.order.append(adj) stack.append(adj) N = int(input()) edge = [tuple(map(int, input().split())) for _ in range(N - 1)] tree = Tree(N, edge) tree.setroot(0) grundy = [0 for _ in range(N)] for node in tree.order[::-1]: for adj in tree.tree[node]: if tree.parent[node] == adj: continue grundy[node] ^= grundy[adj] + 1 print('Alice' if grundy[0] != 0 else 'Bob') ```
instruction
0
84,902
13
169,804
Yes
output
1
84,902
13
169,805
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ```
instruction
0
84,903
13
169,806
Yes
output
1
84,903
13
169,807
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` from collections import deque import heapq N = int(input()) gr = [None] * N child = [0] * N dic = {} q = [] for i in range(N-1): x,y = map(int,input().split()) x -= 1 y -= 1 if x not in dic: dic[x] = [] if y not in dic: dic[y] = [] dic[x].append(y) dic[y].append(x) child[x] += 1 child[y] += 1 dep = [float("inf")] * N dep[0] = 0 dq = deque([0]) while len(dq) > 0: n = dq.popleft() for i in dic[n]: if dep[i] > dep[n] + 1: dep[i] = dep[n] + 1 for i in range(N): if child[i] == 1: child[i] = 0 gr[i] = 0 heapq.heappush(q,[-1 * dep[i] , i]) while len(q) > 0: ngr = 0 no = heapq.heappop(q) now = no[1] for i in dic[now]: if gr[i] != None: ngr ^= (gr[i] + 1) else: child[i] -= 1 if child[i] <= 1 and gr[i] == None: heapq.heappush(q,[-1 * dep[i] , i]) gr[now] = ngr #print (gr) if gr[0] == 0: print ("Bob") else: print ("Alice") ```
instruction
0
84,904
13
169,808
Yes
output
1
84,904
13
169,809
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 deg[1] += 1 dp = [[] for i in range(n+1)] mark = [0]*(n+1) stack = [] for i in range(1,n+1): if deg[i] == 1: stack.append(i) mark[i] = 1 while stack: x = stack.pop() if dp[x]: t = 0 for z in dp[x]: t ^= z mark[x] = t+1 if x == 1: break for y in graph[x]: if deg[y] > 1: dp[y].append(mark[x]) deg[y] -= 1 if deg[y] == 1: stack.append(y) if mark[1] == 1: print("Bob") else: print("Alice") ```
instruction
0
84,905
13
169,810
Yes
output
1
84,905
13
169,811
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() e = collections.defaultdict(set) for _ in range(n-1): x,y = LI() e[x].add(y) e[y].add(x) def search(s): d = collections.defaultdict(lambda: inf) d[s] = 0 q = [] heapq.heappush(q, (0, s)) v = collections.defaultdict(bool) while len(q): k, u = heapq.heappop(q) if v[u]: continue v[u] = True for uv in e[u]: ud = 1 if v[uv]: continue vd = k + ud if d[uv] > vd: d[uv] = vd heapq.heappush(q, (vd, uv)) return d d = search(1) dd = collections.defaultdict(int) for i in range(2,n+1): dd[d[i]] += 1 if dd[1] == 1: return 'Alice' k = 0 for i,c in dd.items(): if c % 2 == 1: return 'Alice' if k % 2 == 1: return 'Alice' return 'Bob' print(main()) ```
instruction
0
84,906
13
169,812
No
output
1
84,906
13
169,813
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ```
instruction
0
84,907
13
169,814
No
output
1
84,907
13
169,815
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` N=int(input()) g = [[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) a -= 1 b -= 1 g[a].append(b) g[b].append(a) nim = [-1 for i in range(N)] def dfs(cur,par): val = 0 for dst in g[cur]: if dst == par: continue val ^= dfs(dst,cur) + 1 nim[cur] = val return val dfs(0 , -1) #print(nim) if nim[0] == 0: print('Bob') else: print('Alice') ```
instruction
0
84,908
13
169,816
No
output
1
84,908
13
169,817
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1, 2, ..., N. The edges of the tree are denoted by (x_i, y_i). On this tree, Alice and Bob play a game against each other. Starting from Alice, they alternately perform the following operation: * Select an existing edge and remove it from the tree, disconnecting it into two separate connected components. Then, remove the component that does not contain Vertex 1. A player loses the game when he/she is unable to perform the operation. Determine the winner of the game assuming that both players play optimally. Constraints * 2 \leq N \leq 100000 * 1 \leq x_i, y_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N x_1 y_1 x_2 y_2 : x_{N-1} y_{N-1} Output Print `Alice` if Alice wins; print `Bob` if Bob wins. Examples Input 5 1 2 2 3 2 4 4 5 Output Alice Input 5 1 2 2 3 1 4 4 5 Output Bob Input 6 1 2 2 4 5 1 6 3 3 2 Output Alice Input 7 1 2 3 7 4 6 2 3 2 4 1 5 Output Bob Submitted Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(1000000) N=int(input()) edge=[[] for i in range(N)] for i in range(N-1): x,y=map(int,input().split()) edge[x-1].append(y-1) edge[y-1].append(x-1) def dfs(v,pv): if v==0: if len(edge[v])%2==1: return True else: ans=0 for nv in edge[v]: ans+=int(dfs(nv,v)) return ans%2==1 else: if len(edge[v])%2==0: return True else: ans=0 for nv in edge[v]: if nv!=pv: ans+=int(dfs(nv,v)) else: continue return ans%2==1 answer=dfs(0,-1) if answer: print("Alice") else: print("Bob") ```
instruction
0
84,909
13
169,818
No
output
1
84,909
13
169,819
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,))
instruction
0
84,946
13
169,892
"Correct Solution: ``` # AOJ 1001: Binary Tree Intersection And Union # Python3 2018.7.5 bal4u def parse(p, i): global sz node[i][2] += 1 del p[0] if p[0] != ',': if node[i][0] == 0: node[i][0] = sz sz += 1 parse(p, node[i][0]) del p[0] if p[0] != ')': if node[i][1] == 0: node[i][1] = sz sz += 1 parse(p, node[i][1]) del p[0] def act(i, k): global ans if node[i][2] < k: return ans += '(' if node[i][0] > 0: act(node[i][0], k) ans += ',' if node[i][1] > 0: act(node[i][1], k) ans += ')' while True: try: op, a, b = input().split() except: break sz = 1 node = [[0 for j in range(3)] for i in range(210)] parse(list(a), 0) parse(list(b), 0) ans = '' act(0, 2 if op== 'i' else 1) print(ans) ```
output
1
84,946
13
169,893
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,))
instruction
0
84,947
13
169,894
"Correct Solution: ``` class Node: def __init__(self, left, right): self.left = left self.right = right self.val = '' @classmethod def fromString(cls, s): pos = 1 if s[pos] == '(': e = getEnd(s, 1) left = cls.fromString(s[1:e+1]) pos = e + 2 else: left = None pos += 1 if s[pos] == '(': e = getEnd(s, pos) right = Node.fromString(s[pos:e+1]) else: right = None return cls(left, right) def __str__(self): lstr = "" if self.left == None else str(self.left) rstr = "" if self.right == None else str(self.right) return "({},{})".format(lstr, rstr) def getEnd(s, pos): count = 0 while True: if s[pos] == '(': count += 1 elif s[pos] == ')': count -= 1 if count == 0: break pos += 1 return pos def intersection(root1, root2): if root1.left == None or root2.left == None: root1.left = None else: intersection(root1.left, root2.left) if root1.right == None or root2.right == None: root1.right = None else: intersection(root1.right, root2.right) def union(root1, root2): if root1.left == None and root2.left == None: pass elif root1.left != None and root2.left == None: pass elif root1.left == None and root2.left != None: root1.left = root2.left else: union(root1.left, root2.left) if root1.right == None and root2.right == None: pass elif root1.right != None and root2.right == None: pass elif root1.right == None and root2.right != None: root1.right = root2.right else: union(root1.right, root2.right) if __name__ == '__main__': try: while True: line = input().strip().split() c = line[0] a = Node.fromString(line[1]) b = Node.fromString(line[2]) if c == 'i': intersection(a, b) else: union(a, b) print(a) except EOFError: pass ```
output
1
84,947
13
169,895
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,))
instruction
0
84,948
13
169,896
"Correct Solution: ``` import re class bintree(): def __init__(self, str1): self.str1 = str1 if self.str1[1] != ",": c = 0 counter = 0 for s in str1[1:]: counter += 1 if s == "(": c += 1 elif s == ")": c -= 1 if c == 0: break self.left = bintree(str1[1:counter+1]) #match1 = re.search("\((\(.*\)),.*\)",str1) #if match1 != None: # self.left = bintree(str(match1.group(1))) else: self.left = "" if self.str1[-2] != ",": str1 = str1[0]+str1[1+len(str(self.left)):] match2 = re.search("\(,(\(.*\))\)",str1) if match2 != None: self.right = bintree(str(str1[2:-1])) else: self.right = "" def __str__(self): return self.str1 def inter(bin1, bin2): if bin1.left != "" and bin2.left != "": strleft = inter(bin1.left, bin2.left) else: strleft = "" if bin1.right != "" and bin2.right != "": strright = inter(bin1.right, bin2.right) else: strright = "" return "(" + strleft + "," + strright + ")" def union(bin1, bin2): if bin1.left != "" or bin2.left != "": if bin1.left == "": strleft = str(bin2.left) elif bin2.left == "": strleft = str(bin1.left) else: strleft = union(bin1.left, bin2.left) else: strleft = "" if bin1.right != "" or bin2.right != "": if bin1.right == "": strright = str(bin2.right) elif bin2.right == "": strright = str(bin1.right) else: strright = union(bin1.right, bin2.right) else: strright = "" #print("(" + strleft + "," + strright + ")") return "(" + strleft + "," + strright + ")" while True: try: inputs = map(str,input().split()) order = next(inputs) if order == "i": t1 = bintree(next(inputs)) t2 = bintree(next(inputs)) #print(t1.left,t1.right) print(inter(t1, t2))# == "((((((,),),),),),)") elif order == "u": t1 = bintree(next(inputs)) t2 = bintree(next(inputs)) #print(t1.left,t1.right) #print(t1.left,t1.right) print(union(t1,t2))# == "((((,),(,)),((,),(,))),(((,),(,)),((,),(,))))") except EOFError as exception: break ```
output
1
84,948
13
169,897
Provide a correct Python 3 solution for this coding contest problem. Given two binary trees, we consider the “intersection” and “union” of them. Here, we distinguish the left and right child of a node when it has only one child. The definitions of them are very simple. First of all, draw a complete binary tree (a tree whose nodes have either 0 or 2 children and leaves have the same depth) with sufficiently large depth. Then, starting from its root, write on it a number, say, 1 for each position of first tree, and draw different number, say, 2 for second tree. The “intersection” of two trees is a tree with nodes numbered both 1 and 2, and the “union” is a tree with nodes numbered either 1 or 2, or both. For example, the intersection of trees in Figures 1 and 2 is a tree in Figure 3, and the union of them is a tree in Figure 4. <image> A node of a tree is expressed by a sequence of characters, “(,)“. If a node has a left child, the expression of the child is inserted between ’(’ and ’,’. The expression of a right child is inserted between ’,’ and ’)’. For exam- ple, the expression of trees in Figures 1 and 2 are “((,),(,))“ and “((,(,)),)“, respectively. Input Each line of the input contains an operation. An operation starts with a character which specifies the type of operation, either ’i’ or ’u’: ’i’ means intersection, and ’u’ means union. Following the character and a space, two tree expressions are given, separated by a space. It is assumed that 1 <= #nodes in a tree <= 100, and no tree expression contains spaces and syntax errors. Input is terminated by EOF. Output For each line of the input, output a tree expression, without any space, for the result of the operation. Example Input i ((,),(,)) ((,(,)),) u ((,),(,)) ((,(,)),) Output ((,),) ((,(,)),(,))
instruction
0
84,949
13
169,898
"Correct Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys def tree_left(node, it): c = next(it) if c == "(": node[0] = [None, None] tree_left(node[0], it) c = next(it) if c == ",": tree_right(node, it) else: assert False def tree_right(node, it): c = next(it) if c == "(": node[1] = [None, None] tree_left(node[1], it) c = next(it) if c == ")": pass else: assert False def tree_parse(s): root = [None, None] s = s[1:] it = iter(s) tree_left(root, it) return root def tree_dump(node): s = "" s += "(" if node[0]: s += tree_dump(node[0]) s += "," if node[1]: s += tree_dump(node[1]) s += ")" return s def intersection(t1, t2): if t1 is None or t2 is None: return None node = [None, None] node[0] = intersection(t1[0], t2[0]) node[1] = intersection(t1[1], t2[1]) return node def union(t1, t2): if t1 is None and t2 is None: return None elif t1 is None: return t2 elif t2 is None: return t1 node = [None, None] node[0] = union(t1[0], t2[0]) node[1] = union(t1[1], t2[1]) return node def main(): for line in sys.stdin: op, s1, s2 = line.split() tree1 = tree_parse(s1) tree2 = tree_parse(s2) #print(tree_dump(tree1)) #print(tree_dump(tree2)) if op == "i": ans = intersection(tree1, tree2) print(tree_dump(ans)) elif op == "u": ans = union(tree1, tree2) print(tree_dump(ans)) if __name__ == "__main__": main() ```
output
1
84,949
13
169,899
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,042
13
170,084
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` # n,m = map(int,input().split()) # G = [[] for _ in range(n+1)] # V = [1]*(n+1) # for i in range(m): # x,y = map(int,input().split()) # G[x].append(y) # G[y].append(x) # l = [1] # V[1] = 0 # q = [] # q.extend(G[1]) # while len(q)>0: # q.sort() # if q[0] not in l: l.append(q[0]) # V[q[0]] = 0 # for x in G[q.pop(0)]: # if V[x]: q.append(x) # print(*l) from heapq import* n,m= map(int,input().split()) V=[0,0]+[1]*(n-1) g=[[]for _ in V] for _ in [0]*m: u,v= map(int,input().split()) g[u].append(v) g[v].append(u) h=[1] l = [] while h: u=heappop(h) l.append(u) for v in g[u]: if V[v]: V[v]=0 heappush(h,v) print(*l) ```
output
1
85,042
13
170,085
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,043
13
170,086
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import heapq from collections import defaultdict graph = defaultdict(list) n,m = list(map(int,input().split())) for i in range(m): u,v = list(map(int,input().split())) u-=1 v-=1 graph[u].append(v) graph[v].append(u) visited = [False for i in range(n)] q = [0] heapq.heapify(q) visited[0] = True while q!=[]: u = heapq.heappop(q) print(u+1,end=' ') for v in graph[u]: if visited[v]==False: visited[v]=True heapq.heappush(q,v) ```
output
1
85,043
13
170,087
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,044
13
170,088
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import heapq n, m = map(int,input().split()) vertices = [ [] for i in range(n)] for _ in range(m): v1, v2 = map(int,input().split()) vertices[v1-1].append(v2-1) vertices[v2 - 1].append(v1 - 1) heap = [] heapq.heappush(heap,0) vis = set() ans = [] while not len(heap)==0: v = heapq.heappop(heap) vis.add(v) ans.append(v+1) for node in vertices[v]: if not node in vis: vis.add(node) heapq.heappush(heap,node) print(*ans) ```
output
1
85,044
13
170,089
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,045
13
170,090
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import math #import math #------------------------------warmup---------------------------- 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") #-------------------game starts now----------------------------------------------------import math import heapq from collections import defaultdict n,m=map(int,input().split()) s=set() ans=[] d=defaultdict(list) for i in range(m): a,b=map(int,input().split()) d[a].append(b) d[b].append(a) ans.append(1) s.add(1) st=[] e=1 scur=set() heapq.heapify(st) for j in range(n-1): for i in d[e]: if i in s or i in scur: continue heapq.heappush(st,i) scur.add(i) e=heapq.heappop(st) scur.remove(e) ans.append(e) s.add(e) print(*ans,sep=" ") ```
output
1
85,045
13
170,091
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,046
13
170,092
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` import sys from heapq import heappush,heappop from collections import defaultdict as dd def get_array(): return list(map(int, sys.stdin.readline().split())) def get_ints(): return map(int, sys.stdin.readline().split()) def input(): return sys.stdin.readline().strip('\n') visited = [0]*(10**5 + 10) l = dd(list) queue = [] ans = [] def bfs(): c = 1 while c != 0: vertex = heappop(queue) c-=1 ans.append(vertex) visited[vertex] = 1 for i in l[vertex]: if visited[i] == 0: heappush(queue,i) visited[i] = 1 c+=1 n , k = get_ints() for _ in range(k): a,b = get_ints() if a!=b: l[a].append(b) l[b].append(a) heappush(queue,1) bfs() print(*ans) ```
output
1
85,046
13
170,093
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,047
13
170,094
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from collections import defaultdict import heapq graph=defaultdict(list) nodes,edges=map(int,input().split()) for i in range(edges): vertex1,vertex2=map(int,input().split()) graph[vertex1].append(vertex2) graph[vertex2].append(vertex1) start=[1] visited=set() answer=[] while start: node=heapq.heappop(start) if node not in visited: visited.add(node) answer.append(node) for w in graph[node]: heapq.heappush(start,w) print(*answer) ```
output
1
85,047
13
170,095
Provide tags and a correct Python 3 solution for this coding contest problem. Lunar New Year is approaching, and Bob decides to take a wander in a nearby park. The park can be represented as a connected graph with n nodes and m bidirectional edges. Initially Bob is at the node 1 and he records 1 on his notebook. He can wander from one node to another through those bidirectional edges. Whenever he visits a node not recorded on his notebook, he records it. After he visits all nodes at least once, he stops wandering, thus finally a permutation of nodes a_1, a_2, …, a_n is recorded. Wandering is a boring thing, but solving problems is fascinating. Bob wants to know the lexicographically smallest sequence of nodes he can record while wandering. Bob thinks this problem is trivial, and he wants you to solve it. A sequence x is lexicographically smaller than a sequence y if and only if one of the following holds: * x is a prefix of y, but x ≠ y (this is impossible in this problem as all considered sequences have the same length); * in the first position where x and y differ, the sequence x has a smaller element than the corresponding element in y. Input The first line contains two positive integers n and m (1 ≤ n, m ≤ 10^5), denoting the number of nodes and edges, respectively. The following m lines describe the bidirectional edges in the graph. The i-th of these lines contains two integers u_i and v_i (1 ≤ u_i, v_i ≤ n), representing the nodes the i-th edge connects. Note that the graph can have multiple edges connecting the same two nodes and self-loops. It is guaranteed that the graph is connected. Output Output a line containing the lexicographically smallest sequence a_1, a_2, …, a_n Bob can record. Examples Input 3 2 1 2 1 3 Output 1 2 3 Input 5 5 1 4 3 4 5 4 3 2 1 5 Output 1 4 3 2 5 Input 10 10 1 4 6 8 2 5 3 7 9 4 5 6 3 4 8 10 8 9 1 10 Output 1 4 3 7 9 8 6 5 2 10 Note In the first sample, Bob's optimal wandering path could be 1 → 2 → 1 → 3. Therefore, Bob will obtain the sequence \{1, 2, 3\}, which is the lexicographically smallest one. In the second sample, Bob's optimal wandering path could be 1 → 4 → 3 → 2 → 3 → 4 → 1 → 5. Therefore, Bob will obtain the sequence \{1, 4, 3, 2, 5\}, which is the lexicographically smallest one.
instruction
0
85,048
13
170,096
Tags: data structures, dfs and similar, graphs, greedy, shortest paths Correct Solution: ``` from heapq import heappush, heappop n, m = map(int, input().split()) adj = [[] for i in range(n+1)] for i in range(m): u, v = map(int, input().split()) adj[u].append(v) adj[v].append(u) v = [False for i in range(n+1)] q = [] perm = [] v[1] = True heappush(q, 1) while q: e = heappop(q) perm += [e] for i in adj[e]: if not v[i]: v[i] = True heappush(q, i) print(*perm) ```
output
1
85,048
13
170,097