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 a correct Python 3 solution for this coding contest problem. You are given a rooted tree with N vertices. The vertices are numbered 0, 1, ..., N-1. The root is Vertex 0, and the parent of Vertex i (i = 1, 2, ..., N-1) is Vertex p_i. Initially, an integer a_i is written in Vertex i. Here, (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). You can execute the following operation at most 25 000 times. Do it so that the value written in Vertex i becomes i. * Choose a vertex and call it v. Consider the path connecting Vertex 0 and v. * Rotate the values written on the path. That is, For each edge (i, p_i) along the path, replace the value written in Vertex p_i with the value written in Vertex i (just before this operation), and replace the value of v with the value written in Vertex 0 (just before this operation). * You may choose Vertex 0, in which case the operation does nothing. Constraints * 2 \leq N \leq 2000 * 0 \leq p_i \leq i-1 * (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). Input Input is given from Standard Input in the following format: N p_1 p_2 ... p_{N-1} a_0 a_1 ... a_{N-1} Output In the first line, print the number of operations, Q. In the second through (Q+1)-th lines, print the chosen vertices in order. Examples Input 5 0 1 2 3 2 4 0 1 3 Output 2 3 4 Input 5 0 1 2 2 4 3 1 2 0 Output 3 4 3 1
instruction
0
36,719
13
73,438
"Correct Solution: ``` from collections import deque def get_children(ps): children = [set() for _ in range(n)] for i, p in enumerate(ps): children[p].add(i + 1) return children def make_levels(cs): levels_set = [] levels_dict = {} queue = deque([(0, 0)]) while queue: i, l = queue.popleft() if fixed[i]: continue if len(levels_set) <= l: levels_set.append(set()) levels_set[l].add(i) levels_dict[i] = l queue.extend((c, l + 1) for c in cs[i]) return levels_set, levels_dict def make_where(aa): where = [0] * n for i, a in enumerate(aa): where[a] = i return where def get_leaves(levels): leaves = {} children_count = [-1] * n for l, cs in reversed(list(enumerate(levels))): for c in cs: cc = children_count[c] pi = ps[c - 1] if cc == -2: children_count[pi] = -2 continue if cc == -1: if aa[c] == c: fixed[c] = True continue leaves[c] = c cc = c else: leaves[c] = cc if children_count[pi] == -1: children_count[pi] = cc else: children_count[pi] = -2 return leaves def put(i, x): buf.append(i) where[x] = i x, aa[i] = aa[i], x while i: pi = ps[i - 1] where[x] = pi x, aa[pi] = aa[pi], x i = pi def solve(): cs = get_children(ps) levels_set, levels_dict = make_levels(cs) while not fixed[0]: leaves = get_leaves(levels_set) while leaves: root = aa[0] if root in leaves: gci = leaves[root] while True: a = aa[gci] if not fixed[a] or a < root: put(gci, root) fixed[root] = True break gci = ps[gci - 1] del leaves[root] else: ml, mi = max((levels_dict[where[i]], where[i]) for i in leaves) put(mi, root) n = int(input()) ps = list(map(int, input().split())) aa = list(map(int, input().split())) where = make_where(aa) fixed = [False] * n buf = [] solve() print(len(buf)) print('\n'.join(map(str, buf))) ```
output
1
36,719
13
73,439
Provide a correct Python 3 solution for this coding contest problem. You are given a rooted tree with N vertices. The vertices are numbered 0, 1, ..., N-1. The root is Vertex 0, and the parent of Vertex i (i = 1, 2, ..., N-1) is Vertex p_i. Initially, an integer a_i is written in Vertex i. Here, (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). You can execute the following operation at most 25 000 times. Do it so that the value written in Vertex i becomes i. * Choose a vertex and call it v. Consider the path connecting Vertex 0 and v. * Rotate the values written on the path. That is, For each edge (i, p_i) along the path, replace the value written in Vertex p_i with the value written in Vertex i (just before this operation), and replace the value of v with the value written in Vertex 0 (just before this operation). * You may choose Vertex 0, in which case the operation does nothing. Constraints * 2 \leq N \leq 2000 * 0 \leq p_i \leq i-1 * (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). Input Input is given from Standard Input in the following format: N p_1 p_2 ... p_{N-1} a_0 a_1 ... a_{N-1} Output In the first line, print the number of operations, Q. In the second through (Q+1)-th lines, print the chosen vertices in order. Examples Input 5 0 1 2 3 2 4 0 1 3 Output 2 3 4 Input 5 0 1 2 2 4 3 1 2 0 Output 3 4 3 1
instruction
0
36,720
13
73,440
"Correct Solution: ``` from collections import deque from heapq import heapreplace def get_children(ps): children = [set() for _ in range(n)] for i, p in enumerate(ps): children[p].add(i + 1) return children def make_levels(cs): levels = [] queue = deque([(0, 0)]) while queue: i, l = queue.popleft() if fixed[i]: continue if len(levels) <= l: levels.append(set()) levels[l].add(i) queue.extend((c, l + 1) for c in cs[i]) return levels def make_where(): where = [0] * n for i, a in enumerate(aa): where[a] = i return where def get_leaves(levels): leaves = {} children_count = [-1] * n for l, cs in reversed(list(enumerate(levels))): for c in cs: cc = children_count[c] pi = ps[c - 1] if cc == -1: if aa[c] == c: fixed[c] = True continue else: leaves[c] = c if children_count[pi] == -1: children_count[pi] = c else: children_count[pi] = -2 elif cc == -2: children_count[pi] = -2 else: leaves[c] = cc if children_count[pi] == -1: children_count[pi] = cc else: children_count[pi] = -2 return leaves def put(i, x, where): # print('put', i, x) buf.append(i) where[x] = i x, aa[i] = aa[i], x while i: pi = ps[i - 1] where[x] = pi x, aa[pi] = aa[pi], x i = pi # assert all(i == where[aa[i]] for i in range(n)) def solve(): cs = get_children(ps) # print(cs) while not fixed[0]: levels = make_levels(cs) leaves = get_leaves(levels) where = make_where() # print('--') # print(levels) # print(leaves) while leaves: r = aa[0] # print('aa', aa) if r in leaves: gci = leaves[r] # print('gci', r, gci, aa) while True: a = aa[gci] if not fixed[a] or a < r: put(gci, r, where) fixed[r] = True break gci = ps[gci - 1] del leaves[r] else: mi = max(where[i] for i in leaves if not fixed[i]) put(mi, r, where) # print(aa, fixed) n = int(input()) ps = list(map(int, input().split())) aa = list(map(int, input().split())) fixed = [False] * n buf = [] solve() print(len(buf)) print('\n'.join(map(str, buf))) ```
output
1
36,720
13
73,441
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree with N vertices. The vertices are numbered 0, 1, ..., N-1. The root is Vertex 0, and the parent of Vertex i (i = 1, 2, ..., N-1) is Vertex p_i. Initially, an integer a_i is written in Vertex i. Here, (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). You can execute the following operation at most 25 000 times. Do it so that the value written in Vertex i becomes i. * Choose a vertex and call it v. Consider the path connecting Vertex 0 and v. * Rotate the values written on the path. That is, For each edge (i, p_i) along the path, replace the value written in Vertex p_i with the value written in Vertex i (just before this operation), and replace the value of v with the value written in Vertex 0 (just before this operation). * You may choose Vertex 0, in which case the operation does nothing. Constraints * 2 \leq N \leq 2000 * 0 \leq p_i \leq i-1 * (a_0, a_1, ..., a_{N-1}) is a permutation of (0, 1, ..., N-1). Input Input is given from Standard Input in the following format: N p_1 p_2 ... p_{N-1} a_0 a_1 ... a_{N-1} Output In the first line, print the number of operations, Q. In the second through (Q+1)-th lines, print the chosen vertices in order. Examples Input 5 0 1 2 3 2 4 0 1 3 Output 2 3 4 Input 5 0 1 2 2 4 3 1 2 0 Output 3 4 3 1 Submitted Solution: ``` from collections import deque from heapq import heapreplace def get_children(ps): children = [set() for _ in range(n)] for i, p in enumerate(ps): children[p].add(i + 1) return children def make_levels(cs): levels = [] queue = deque([(0, 0)]) while queue: i, l = queue.popleft() if fixed[i]: continue if len(levels) <= l: levels.append(set()) levels[l].add(i) queue.extend((c, l + 1) for c in cs[i]) return levels def get_leaves(levels): leaves = {} leaf_levels = [] children_count = [-1] * n for l, cs in reversed(list(enumerate(levels))): for c in cs: cc = children_count[c] pi = ps[c - 1] if cc == -1: leaves[c] = c leaf_levels.append([-l, c]) if children_count[pi] == -1: children_count[pi] = c else: children_count[pi] = -2 elif cc == -2: children_count[pi] = -2 else: leaves[c] = cc leaf_levels.append([-l, c]) if children_count[pi] == -1: children_count[pi] = cc else: children_count[pi] = -2 return leaves, leaf_levels def put(i, x): # print('put', i, x) buf.append(i) x, aa[i] = aa[i], x while i: pi = ps[i - 1] x, aa[pi] = aa[pi], x i = pi def solve(): cs = get_children(ps) # print(cs) while not fixed[0]: levels = make_levels(cs) leaves, leaf_levels = get_leaves(levels) # print('--') # print(levels) # print(leaves) # print(leaf_levels) while leaves: r = aa[0] if r in leaves: gci = leaves[r] # print('gci', r, gci, aa) while True: a = aa[gci] if not fixed[a] or a < r: put(gci, r) fixed[r] = True break gci = ps[gci - 1] del leaves[r] else: deepest_leaf = leaf_levels[0] put(deepest_leaf[1], r) deepest_leaf[0] += 1 heapreplace(leaf_levels, deepest_leaf) # print(aa, fixed) n = int(input()) ps = list(map(int, input().split())) aa = list(map(int, input().split())) fixed = [False] * n buf = [] solve() print(len(buf)) print('\n'.join(map(str, buf))) ```
instruction
0
36,721
13
73,442
No
output
1
36,721
13
73,443
Provide tags and a correct Python 3 solution for this coding contest problem. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image>
instruction
0
36,927
13
73,854
Tags: constructive algorithms, dfs and similar, dp, hashing, implementation, trees Correct Solution: ``` #!/usr/bin/env python def longest_path(): try: d = [-1 for _ in range(n)] d[0] = 0; q = [0] for i in range(n): f = q[i] for t in g[f]: if d[t] == -1: q.append(t) d[t] = d[f] + 1 u = q[-1] d = [-1 for _ in range(n)] p = [-1 for _ in range(n)] d[u] = 0; q = [u] for i in range(n): f = q[i] for t in g[f]: if d[t] == -1: q.append(t) d[t] = d[f] + 1 p[t] = f v = q[-1] ld = d[v] w = v if ld & 1: return u, v, None while d[w] != (ld >> 1): w = p[w] return u, v, w except: print(f'Error raised in longest_path()') def top(u): try: if u is None: return False dist = [-1 for _ in range(n)] deg = [-1 for _ in range(n)] dist[u] = 0; q = [u] for i in range(n): f = q[i] if deg[dist[f]] == -1: deg[dist[f]] = len(g[f]) elif len(g[f]) != deg[dist[f]]: return False for t in g[f]: if dist[t] == -1: q.append(t) dist[t] = dist[f] + 1 return True except: print(f'Error raised in top({u})') def semitop(w): try: if w is None: return False, None d = [-1 for _ in range(n)] d[w] = 0; q = [w]; i = 0 while i < len(q): f = q[i] for t in g[f]: if d[t] == -1: if len(g[t]) != 2: d[t] = 100_500 if top(t): return True, t else: d[t] = d[f] + 1 q.append(t) i += 1 return False, None except: print(f'Error raised in semitop({w})') try: n = int(input()) g = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(lambda _: int(_) - 1, input().split()) g[u].append(v); g[v].append(u) u, v, w = longest_path() if top(u): print(u + 1) elif top(v): print(v + 1) elif top(w): print(w + 1) else: k, t = semitop(w) if k: print(t + 1) else: print(-1) except: print(f'Error raised in main') ```
output
1
36,927
13
73,855
Provide tags and a correct Python 3 solution for this coding contest problem. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image>
instruction
0
36,928
13
73,856
Tags: constructive algorithms, dfs and similar, dp, hashing, implementation, trees Correct Solution: ``` from sys import * from collections import deque #setrecursionlimit(10**8) n = int(input()) adj = [[] for i in range(n)] for i in range(n-1): u, v = map(int, stdin.readline().split()) adj[u-1].append(v-1) adj[v-1].append(u-1) leaves = [u for u in range(n) if len(adj[u]) == 1] def test(v): degs = [-1] * n dists = [-1]*n dists[v] = 0 todo = [v] while todo: top = todo.pop() for nbr in adj[top]: if degs[dists[top]] == -1: degs[dists[top]] = len(adj[top]) elif degs[dists[top]] != len(adj[top]): return False if dists[nbr] != -1: continue dists[nbr] = dists[top] + 1 todo.append(nbr) return True def bfs(v): dists = [-1]*n todo = deque([v]) dists[v] = 0 while todo: top = todo.popleft() for nbr in adj[top]: if dists[nbr] == -1: dists[nbr] = dists[top] + 1 todo.append(nbr) return dists def explore(v, w): revisited = [False]*n revisited[v] = True todo = [v] pi = [-1]*n while todo: top = todo.pop() for nbr in adj[top]: if not revisited[nbr]: todo.append(nbr) revisited[nbr] = True pi[nbr] = top ans = [w] cur = w while cur != v: cur = pi[cur] ans.append(cur) return ans # find the center vtx/edge def center(): dists = bfs(0) best = -1 best_arg = -1 for i in range(n): if dists[i] > best: best = dists[i] best_arg = i if best_arg < 0 or best_arg >= n: print("first BFS failed", best_arg, best) exit() dists_2 = bfs(best_arg) diam = -1 diam_arg = -1 for i in range(n): if dists_2[i] > diam: diam = dists_2[i] diam_arg = i if diam_arg < 0 or diam_arg >= n: print("first BFS failed", diam_arg, diam) exit() path = explore(diam_arg, best_arg) # from best_arg to diam_arg if path is None: print("explore failed", diam_arg, best_arg) if len(path) % 2 == 1: return [path[len(path) // 2]] else: return [path[len(path) // 2 - 1], path[len(path) // 2]] cc = center() if len(cc) == 1: if test(cc[0]): print(cc[0]+1) exit() for c in cc: leaf_dists = bfs(c) cl_leaf = n+1 cl_leaf_arg = -1 for nbr in adj[c]: cur = nbr prev = c while len(adj[cur]) == 2: tmp = cur cur = [v for v in adj[cur] if v != prev][0] prev = tmp if len(adj[cur]) == 1: if leaf_dists[cur] < cl_leaf: cl_leaf = leaf_dists[cur] cl_leaf_arg = cur # if cl_leaf_arg < 0 or cl_leaf_arg >= n: # print("closest leaf failed", cl_leaf_arg, cl_leaf) #print(cl_leaf_arg) if cl_leaf_arg != -1 and test(cl_leaf_arg): print(cl_leaf_arg+1) exit() print(-1) ```
output
1
36,928
13
73,857
Provide tags and a correct Python 3 solution for this coding contest problem. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image>
instruction
0
36,929
13
73,858
Tags: constructive algorithms, dfs and similar, dp, hashing, implementation, trees Correct Solution: ``` import sys from collections import Counter N = int(input()) Edge = [[] for _ in range(N)] Dim = [0]*N for _ in range(N-1): a, b = map(int, sys.stdin.readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Dim[a] += 1 Dim[b] += 1 def dfs(x): dist = [0]*N stack = [x] visited = set([x]) for _ in range(N): vn = stack.pop() for vf in Edge[vn]: if vf not in visited: visited.add(vf) dist[vf] = 1 + dist[vn] stack.append(vf) return dist def check(i): dist = dfs(i) D = [-1]*N for i in range(N): if D[dist[i]] == -1: D[dist[i]] = Dim[i] elif D[dist[i]] != Dim[i]: return False return True def getpar(Edge, p): N = len(Edge) par = [0]*N par[p] -1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn stack.append(vf) return par def solve(): Leaf = [i for i in range(N) if Dim[i] == 1] dist0 = dfs(0) md0 = max(dist0) p1 = dist0.index(md0) distp1 = dfs(p1) mdp1 = max(distp1) p2 = distp1.index(mdp1) if check(p1): return p1 + 1 if check(p2): return p2 + 1 if mdp1 % 2 == 1: return -1 distp2 = dfs(p2) for i in range(N): if distp1[i] == distp2[i] == mdp1//2: break cen = i distcen = dfs(cen) if check(cen): return cen + 1 G = [distcen[l] for l in Leaf] GC = Counter(G) if len(GC) == 1: P = getpar(Edge, cen) for l in Leaf: k = P[l] while k != cen: if Dim[k] != 2: break k = P[k] else: if check(l): return l + 1 else: return -1 return -1 else: sl = set(Leaf) for k, v in GC.items(): if v == 1: for i, d in enumerate(distcen): if i in sl and d == k: if check(i): return i + 1 return -1 print(solve()) ```
output
1
36,929
13
73,859
Provide tags and a correct Python 3 solution for this coding contest problem. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image>
instruction
0
36,930
13
73,860
Tags: constructive algorithms, dfs and similar, dp, hashing, implementation, trees Correct Solution: ``` from collections import deque, Counter import sys def check_node(g, node, n): vis = [False] * n q = deque() vis[node] = True q.append((node, 0)) l_p = -1 adj = -1 while len(q) > 0: v, l = q.popleft() if l_p == l: if len(g[v]) != adj: return False else: adj = len(g[v]) l_p = l for u in g[v]: if not vis[u]: vis[u] = True q.append((u, l + 1)) return True def length(g, node, n): vis = [False] * n s = deque() vis[node] = True s.append((-1, [node])) d = 0 e = None m = None while len(s) > 0: ls = len(s) - 1 if ls > d: if ls % 2 == 1: m = s[ls//2 + 1][0] e = s[-1][0] else: e = s[-1][0] m = None d = ls if not s[-1][1]: s.pop() continue v = s[-1][1].pop() s.append((v, [x for x in g[v] if not vis[x]])) for x in g[v]: vis[x] = True return e, m def get(g, nodes, n, prev): vis = [False] * n s = deque() for node in nodes: vis[node] = True s.append((node, 0)) vis[prev] = True res = [] while len(s) > 0: v, l = s.pop() if len(g[v]) > 2: continue elif len(g[v]) == 1: res.append((v, l)) for u in g[v]: if not vis[u]: vis[u] = True s.append((u, l + 1)) return res if __name__ == '__main__': n = int(input()) if n == 1: print(1) exit(0) g = [[] for _ in range(n)] lines = sys.stdin.readlines() for line in lines: v, u = map(int, line.split()) g[v - 1].append(u - 1) g[u - 1].append(v - 1) s = -1 for i in range(n): if len(g[i]) == 1: s = i break if check_node(g, s, n): print(s + 1) exit(0) e, m = length(g, s, n) if check_node(g, e, n): print(e + 1) exit(0) if not m: print(-1) exit(0) if check_node(g, m, n): print(m + 1) exit(0) gt = get(g, g[m], n, m) if not gt: print(-1) exit(0) ctr = Counter((map(lambda x: x[1], gt))) if len(ctr) == 1: if check_node(g, gt[0][0], n): print(gt[0][0] + 1) exit(0) if len(ctr) == 2 and 1 in ctr.values(): p = list(filter(lambda x: x[1] == 1, ctr.items()))[0][0] for y in gt: if y[1] == p: if check_node(g, y[0], n): print(y[0] + 1) exit(0) print(-1) ```
output
1
36,930
13
73,861
Provide tags and a correct Python 3 solution for this coding contest problem. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image>
instruction
0
36,931
13
73,862
Tags: constructive algorithms, dfs and similar, dp, hashing, implementation, trees Correct Solution: ``` from collections import deque n = int(input()) e = [[] for i in range(n+1)] for i in range(n - 1): u, v = map(int, input().split()) e[u].append(v) e[v].append(u) dep = [-1] * (n + 1) dep[1] = 0 q = deque([1]) cur = 1 while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) # starting from cur, to end dep = [-1] * (n + 1) pred = [0] * (n + 1) dep[cur] = 0 q = deque([cur]) end = cur while q: end = q.popleft() for to in e[end]: if dep[to] == -1: dep[to] = dep[end] + 1 pred[to] = end q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(cur) # print('not bad') exit() center = end for i in range(dep[end] // 2): center = pred[center] # starting from end, check end dep = [-1] * (n + 1) dep[end] = 0 q = deque([end]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(end) exit() # from center, check center top = center dep = [-1] * (n + 1) dep[center] = 0 q = deque([center]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: if len(e[to]) == 2: dep[to] = dep[cur] + 1 q.append(to) elif len(e[to]) == 1: top = to q.clear() break deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(center) exit() dep = [-1] * (n + 1) dep[top] = 0 q = deque([top]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(top) exit() # print('not found') print(-1) ```
output
1
36,931
13
73,863
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image> Submitted Solution: ``` import sys N = int(input()) edges = [[] for _ in range(N)] for _ in range(N-1): [u,v] = list(map(int,input().split())) u-=1 v-=1 edges[u].append(v) edges[v].append(u) good_mm = {} # is the tree rooted at u okay after disconnected it with v # if good return a hash of the indegree # otherwise return None def allsame(v): for i in v: if i == None: return False if i != v[0]: return False return True # return the chain of degree after removing (u,p) rooted at u # None otherwise def good(u,p): if (u,p) in good_mm: return good_mm[(u,p)] if len(edges[u]) == 1 and edges[u][0] == p: return [1] paths = [] for to in edges[u]: if to == p: continue paths.append(good(to,u)) good_mm[(u,p)] = [len(edges[u])] + paths[0] if allsame(paths) else None return good_mm[(u,p)] leafs = set() leaf = None for u in range(N): if len(edges[u]) == 1: leaf = u leafs.add(leaf) def dfs(u,p=None): g = good(u,p) if g != None: if u in leafs and p == None: return u for v in edges[u]: if v == p: continue g = dfs(v,u) if g != None: return g return None for leaf in leafs: g = dfs(leaf, None) if g != None: print(g+1) sys.exit(0) print(-1) ```
instruction
0
36,932
13
73,864
No
output
1
36,932
13
73,865
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image> Submitted Solution: ``` n = int(input()) graph = {} def count_children(graph, node): return len(graph[node]) def compare_children(graph, node, seen=[]): #print(f'examining {node}') if not seen: seen = [node] children = [n for n in graph[node] if n not in seen] if not children: # print(f'{node} has no unexamined children') return True childCount = [] for child in children: childCount.append(count_children(graph, child)) if not compare_children(graph, child, seen + [child]): return False if len(set(childCount)) > 1: return False return True for _ in range(n - 1): v, u = map(int, input().strip().split()) if graph.get(v): graph[v].append(u) else: graph[v] = [u] if graph.get(u): graph[u].append(v) else: graph[u] = [v] #print(graph) for node in graph: #print(f'Is it {node}?') n = compare_children(graph, node, [node]) if n: print(node) exit() print(-1) ```
instruction
0
36,933
13
73,866
No
output
1
36,933
13
73,867
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image> Submitted Solution: ``` def main(): n = int(input()) cands = [1 for i in range(n)] adjs = [[] for i in range(n)] pows = [0 for i in range(n)] for i in range(n - 1): f, s = map(int, input().split()) adjs[f - 1].append(s - 1) adjs[s - 1].append(f - 1) pows[f - 1] += 1 pows[s - 1] += 1 while sum(cands) != 0: root = cands.index(1) used = set() used.add(root) levels = [[root], []] counter = 1 while counter != n: for i in levels[-2]: for j in adjs[i]: if j not in used: levels[-1].append(j) used.add(j) counter += len(levels[-1]) levels.append([]) levels.pop() flag = 'good' visited = [] for lev in levels: powpow = pows[lev[0]] for el in lev: visited.append(el) if pows[el] != powpow: flag = 'bad' break if flag == 'bad': break if flag == 'bad': for v in visited: cands[v] = 0 else: print(root) return 0 print(-1) return 0 main() ```
instruction
0
36,934
13
73,868
No
output
1
36,934
13
73,869
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You have given tree consist of n vertices. Select a vertex as root vertex that satisfies the condition below. * For all vertices v_{1} and v_{2}, if distance(root, v_{1}) = distance(root, v_{2}) then degree(v_{1}) = degree(v_{2}), where degree means the number of vertices connected to that vertex, and distance means the number of edges between two vertices. Determine and find if there is such root vertex in the tree. If there are multiple answers, find any of them. Input The first line contains a single integer n (1 ≤ n ≤ 10^{5}) — the number of vertices. Each of the next n-1 lines contains two integers v_{i} and u_{i} (1 ≤ v_{i} < u_{i} ≤ n) — it means there is an edge exist between v_{i} and u_{i}. It is guaranteed that the graph forms tree. Output If there is such root vertex exists, print any of them. Otherwise, print -1. Examples Input 7 1 2 2 3 3 4 4 5 3 6 6 7 Output 3 Input 6 1 3 2 3 3 4 4 5 4 6 Output -1 Note This is the picture for the first example. 1, 5, 7 also can be a valid answer. <image> This is the picture for the second example. You can see that it's impossible to find such root vertex. <image> Submitted Solution: ``` from collections import deque n = int(input()) debug = (n == 93784) e = [[] for i in range(n+1)] for i in range(n - 1): u, v = map(int, input().split()) e[u].append(v) e[v].append(u) dep = [-1] * (n + 1) dep[1] = 0 q = deque([1]) cur = 1 while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) dep = [-1] * (n + 1) pred = [0] * (n + 1) dep[cur] = 0 q = deque([cur]) end = cur while q: end = q.popleft() for to in e[end]: if dep[to] == -1: dep[to] = dep[end] + 1 pred[to] = end q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(cur) # print('not bad') exit() # if dep[end] & 1: # if debug: # print('checked: %d, %d' % (cur, end)) # print('-1') # exit() # for i in range(dep[end] // 2): # end = pred[end] center = end dep = [-1] * (n + 1) dep[center] = 0 q = deque([center]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(end) exit() top = center dep = [-1] * (n + 1) dep[center] = 0 q = deque([center]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: if len(e[to]) == 2: dep[to] = dep[cur] + 1 q.append(to) elif len(e[to]) == 1: top = to q.clear() break deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): if debug: print(dep[i], deg[dep[i]], len(e[i])) bad = True break if not bad: print(center) exit() dep = [-1] * (n + 1) dep[top] = 0 q = deque([top]) while q: cur = q.popleft() for to in e[cur]: if dep[to] == -1: dep[to] = dep[cur] + 1 q.append(to) deg = [-1] * (n + 1) bad = False for i in range(1, n + 1): if deg[dep[i]] == -1: deg[dep[i]] = len(e[i]) else: if deg[dep[i]] != len(e[i]): bad = True break if not bad: print(top) exit() # print('not found') print(-1) ```
instruction
0
36,935
13
73,870
No
output
1
36,935
13
73,871
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a simple graph, output the number of simple cycles in it. A simple cycle is a cycle with no repeated vertices or edges. Input The first line of input contains two integers n and m (1 ≤ n ≤ 19, 0 ≤ m) – respectively the number of vertices and edges of the graph. Each of the subsequent m lines contains two integers a and b, (1 ≤ a, b ≤ n, a ≠ b) indicating that vertices a and b are connected by an undirected edge. There is no more than one edge connecting any pair of vertices. Output Output the number of cycles in the given graph. Examples Input 4 6 1 2 1 3 1 4 2 3 2 4 3 4 Output 7 Note The example graph is a clique and contains four cycles of length 3 and three cycles of length 4. Submitted Solution: ``` def dfs(v,p,visit): global c if visit[v]==1: c+=1 return visit[v]=1 for k in g[v]: if k!=p: dfs(k,v,visit) n,m=map(int,input().split()) g=[[] for _ in range(n)] for _ in range(m): x,y=map(int,input().split()) g[x-1].append(y-1) g[y-1].append(x-1) visit=[0 for _ in range(n)] c=0 dfs(0,-1,visit) print(c+1) ```
instruction
0
36,936
13
73,872
No
output
1
36,936
13
73,873
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,135
13
74,270
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` n = int(input()) r = [[] for i in range(n + 1)] r[1] = [0] for i in range(n - 1): a, b = map(int, input().split()) r[a].append(b) r[b].append(a) t = list(map(int, input().split())) u, v = [0] * (n + 1), [0] * (n + 1) for i, j in enumerate(t, 1): if j < 0: u[i] = - j else: v[i] = j # print(u,v) t, p = [1], [0] * (n + 1) while t: a = t.pop() for b in r[a]: if p[b]: continue p[b] = a t.append(b) k = [len(t) for t in r] t = [a for a in range(2, n + 1) if k[a] == 1] x, y = [0] * (n + 1), [0] * (n + 1) while t: a = t.pop() b = p[a] x[b] = max(x[b], u[a]) y[b] = max(y[b], v[a]) k[b] -= 1 if k[b] == 1: t.append(b) if u[b] > 0: if x[b] - y[b] > u[b]: u[b], v[b] = x[b], x[b] - u[b] else: u[b], v[b] = y[b] + u[b], y[b] else: if y[b] - x[b] > v[b]: u[b], v[b] = y[b] - v[b], y[b] else: u[b], v[b] = x[b], x[b] + v[b] print(u[1] + v[1]) ```
output
1
37,135
13
74,271
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,136
13
74,272
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from sys import stdin, stdout,setrecursionlimit from collections import defaultdict,deque,Counter,OrderedDict from heapq import heappop,heappush import threading n = int(stdin.readline()) graph = [set() for x in range(n)] for x in range(n-1): a,b = [int(x) for x in stdin.readline().split()] a -= 1 b -= 1 graph[a].add(b) graph[b].add(a) vals = [int(x) for x in stdin.readline().split()] bruh = [(0,-1)] for x in range(n): num,p = bruh[x] for y in graph[num]: if y != p: bruh.append((y,num)) result = [-1 for x in range(n)] for v,parent in bruh[::-1]: nP = 0 nN = 0 for x in graph[v]: if x != parent: p,n = result[x] nP = max(nP,p) nN = max(nN, n) nN = max(nN, nP+vals[v]) nP = max(nP, nN-vals[v]) result[v] = (nP,nN) ng, ps = result[0] vals[0] += ps - ng stdout.write(str(ng+ps)) ```
output
1
37,136
13
74,273
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,137
13
74,274
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` n = int(input()) r = [[] for i in range(n + 1)] r[1] = [0] for i in range(n - 1): a, b = map(int, input().split()) r[a].append(b) r[b].append(a) t = list(map(int, input().split())) u, v = [0] * (n + 1), [0] * (n + 1) for i, j in enumerate(t, 1): if j < 0: u[i] = - j else: v[i] = j t, p = [1], [0] * (n + 1) while t: a = t.pop() for b in r[a]: if p[b]: continue p[b] = a t.append(b) k = [len(t) for t in r] t = [a for a in range(2, n + 1) if k[a] == 1] x, y = [0] * (n + 1), [0] * (n + 1) while t: a = t.pop() b = p[a] x[b] = max(x[b], u[a]) y[b] = max(y[b], v[a]) k[b] -= 1 if k[b] == 1: t.append(b) if u[b] > 0: if x[b] - y[b] > u[b]: u[b], v[b] = x[b], x[b] - u[b] else: u[b], v[b] = y[b] + u[b], y[b] else: if y[b] - x[b] > v[b]: u[b], v[b] = y[b] - v[b], y[b] else: u[b], v[b] = x[b], x[b] + v[b] print(u[1] + v[1]) ```
output
1
37,137
13
74,275
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,138
13
74,276
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` from collections import defaultdict from sys import stdin,setrecursionlimit setrecursionlimit(10**6) import threading def dfs(g,node,parent,cr,req): l=[0,0] for i in g[node]: if i!=parent: t=dfs(g,i,node,cr,req) # print(t) l[0]=max(t[0],l[0]) l[1]=max(t[1],l[1]) if l[0]-l[1]<=req[node]: l[0]+=req[node]-(l[0]-l[1]) else: l[1]+=(l[0]-l[1])-req[node] # print(l) return l def main(): n=int(input()) g=defaultdict(list) for i in range(n-1): a,b=map(int,input().strip().split()) g[a-1].append(b-1) g[b-1].append(a-1) req=list(map(int,input().strip().split())) cr=[0] #fol incre and decre x=dfs(g,0,-1,cr,req) print(sum(x)) threading.stack_size(10 ** 8) t = threading.Thread(target=main) t.start() t.join() ```
output
1
37,138
13
74,277
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,139
13
74,278
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` import sys def minp(): return sys.stdin.readline().strip() n = int(minp()) e = [0] p = [None]*(n+1) for i in range(n): e.append([]) for i in range(n-1): a, b = map(int,minp().split()) e[a].append(b) e[b].append(a) v = list(map(int,minp().split())) plus = [0]*(n+1) minus = [0]*(n+1) was = [False]*(n+1) was[1] = True i = 0 j = 1 q = [0]*(n+100) q[0] = 1 p[1] = 0 while i < j: x = q[i] i += 1 for y in e[x]: if not was[y]: was[y] = True p[y] = x q[j] = y j += 1 i = j-1 while i >= 0: x = q[i] i -= 1 s = minus[x] - plus[x] z = v[x-1] + s pp = p[x] #print(x, p[x], plus[x], minus[x], '-', s[x], v[x-1]+s[x], v[0]+s[1]) #print(-(plus[x]-minus[x]),s[x]) minus[pp] = max(minus[x],minus[pp]) plus[pp] = max(plus[x],plus[pp]) if z > 0: plus[pp] = max(plus[pp],plus[x]+z) elif z < 0: minus[pp] = max(minus[pp],minus[x]-z) #print(v[0]) #print(plus[0], minus[0]) print(plus[0] + minus[0]) ```
output
1
37,139
13
74,279
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,140
13
74,280
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) 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 @bootstrap def dfs(u,p): s1=0 s2=0 for j in adj[u]: if j!=p: r= yield dfs(j, u) s1=max(s1,r[0]) s2=max(s2,r[1]) req= b[u-1]-s1+s2 if req>=0: yield [s1+req,s2] else: yield [s1, s2+abs(req)] n=int(input()) adj=[[] for i in range(n+1)] for j in range(n-1): u,v=map(int,input().split()) adj[u].append(v) adj[v].append(u) b=list(map(int,input().split())) print(sum(dfs(1,0))) ```
output
1
37,140
13
74,281
Provide tags and a correct Python 3 solution for this coding contest problem. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3
instruction
0
37,141
13
74,282
Tags: dfs and similar, dp, greedy, trees Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) path = [[] for _ in range(n)] for _ in range(n-1): u1,v1 = map(lambda xx:int(xx)-1,input().split()) path[u1].append(v1) path[v1].append(u1) val = list(map(int,input().split())) st,poi,visi,dp = [0],[0]*n,[1]+[0]*(n-1),[[0]*n for _ in range(2)] while len(st): x,y = st[-1],path[st[-1]] if poi[x] != len(y) and visi[y[poi[x]]]: poi[x] += 1 if poi[x] == len(y): st.pop() a,b = dp[0][x],dp[1][x] ne = val[x]-a+b if len(st): if ne < 0: b -= ne else: a += ne dp[0][st[-1]] = max(dp[0][st[-1]],a) dp[1][st[-1]] = max(dp[1][st[-1]],b) else: st.append(y[poi[x]]) visi[st[-1]] = 1 poi[x] += 1 print(abs(val[0]-dp[0][0]+dp[1][0])+dp[0][0]+dp[1][0]) # 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
37,141
13
74,283
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(2*10**5) 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 @bootstrap def dfs(u,p): s1=0 s2=0 for j in adj[u]: if j!=p: r= yield dfs(j, u) s1=max(s1,r[0]) s2=max(s2,r[1]) req= b[u-1]+s1-s2 if req>=0: yield [s1+req,s2] else: yield [s1, s2+req] n=int(input()) adj=[[] for i in range(n+1)] for j in range(n-1): u,v=map(int,input().split()) adj[u].append(v) adj[v].append(u) b=list(map(int,input().split())) print(sum(dfs(1,0))) ```
instruction
0
37,142
13
74,284
No
output
1
37,142
13
74,285
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3 Submitted Solution: ``` from sys import stdin n = int(stdin.readline()) graph = [set() for x in range(n)] for x in range(n-1): a,b = [int(x) for x in stdin.readline().split()] a -= 1 b -= 1 graph[a].add(b) graph[b].add(a) vals = [int(x) for x in stdin.readline().split()] def moves(v,parent): nP = max(0,-vals[v]) nN = max(0,vals[v]) for x in graph[v]: if x != parent: p,n = moves(x,v) nP = max(nP,p) nN = max(nN, n) return (nP,nN) ng, ps = moves(0,-1) vals[0] += ps - ng print(ng+ps+abs(vals[0])) ```
instruction
0
37,143
13
74,286
No
output
1
37,143
13
74,287
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3 Submitted Solution: ``` #import resource, sys #resource.setrlimit(resource.RLIMIT_STACK, (2**24,-1)) #sys.setrecursionlimit(10**4) from sys import * from collections import deque from heapq import * ONLINE_JUDGE = 1 if ONLINE_JUDGE == 0: stdin = open("/home/danil/prog/input.txt", "r") stdout = open("/home/danil/prog/output.txt", "w") ######################################################################## n = int(stdin.readline()) g = [[] for i in range(n+1)] for i in range(n-1): lst = [int(x) for x in stdin.readline().strip().split(" ")] print(lst) u = lst[0] v = lst[1] g[u].append(v) g[v].append(u) s = stdin.readline().split(" ") pass v = [0]*(n+1) for i in range(n): v[i+1] = int(s[i]) pos = [0]*(n+1) neg = [0]*(n+1) def dfs(u, p): global v global g global pos global neg pos[u] = 0 neg[u] = 0 for to in g[u]: if (to != p): dfs(to,u) pos[u] = max(pos[u],pos[to]) neg[u] = max(neg[u],neg[to]) v[u] += neg[u] v[u] -= pos[u] if v[u] > 0: pos[u] += v[u] v[u] = 0 if v[u] < 0: neg[u] -= v[u] v[u] = 0 dfs(1,-1) print(pos[1]+neg[1]) ############################################################################### if ONLINE_JUDGE == 0: stdin.close() stdout.close() ```
instruction
0
37,144
13
74,288
No
output
1
37,144
13
74,289
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A tree is a graph with n vertices and exactly n - 1 edges; this graph should meet the following condition: there exists exactly one shortest (by number of edges) path between any pair of its vertices. A subtree of a tree T is a tree with both vertices and edges as subsets of vertices and edges of T. You're given a tree with n vertices. Consider its vertices numbered with integers from 1 to n. Additionally an integer is written on every vertex of this tree. Initially the integer written on the i-th vertex is equal to vi. In one move you can apply the following operation: 1. Select the subtree of the given tree that includes the vertex with number 1. 2. Increase (or decrease) by one all the integers which are written on the vertices of that subtree. Calculate the minimum number of moves that is required to make all the integers written on the vertices of the given tree equal to zero. Input The first line of the input contains n (1 ≤ n ≤ 105). Each of the next n - 1 lines contains two integers ai and bi (1 ≤ ai, bi ≤ n; ai ≠ bi) indicating there's an edge between vertices ai and bi. It's guaranteed that the input graph is a tree. The last line of the input contains a list of n space-separated integers v1, v2, ..., vn (|vi| ≤ 109). Output Print the minimum number of operations needed to solve the task. Please, do not write the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams or the %I64d specifier. Examples Input 3 1 2 1 3 1 -1 1 Output 3 Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): n = int(input()) path = [[] for _ in range(n)] for _ in range(n-1): u1,v1 = map(lambda xx:int(xx)-1,input().split()) path[u1].append(v1) path[v1].append(u1) val = list(map(int,input().split())) st,poi,visi,ans = [0],[0]*n,[1]+[0]*(n-1),0 while len(st): x,y = st[-1],path[st[-1]] if poi[x] != len(y) and visi[y[poi[x]]]: poi[x] += 1 if poi[x] == len(y): ans += abs(val[st.pop()]) if len(st): val[st[-1]] += val[x] else: st.append(y[poi[x]]) visi[st[-1]] = 1 poi[x] += 1 print(ans) # 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() ```
instruction
0
37,145
13
74,290
No
output
1
37,145
13
74,291
Provide tags and a correct Python 3 solution for this coding contest problem. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES
instruction
0
37,147
13
74,294
Tags: dfs and similar, graphs Correct Solution: ``` def dfs(edge_list, start, end): queue = [start] visited = [False] * len(edge_list) while len(queue) > 0: el = queue.pop() for i in edge_list[el]: if not visited[i]: if i == end: return True visited[i] = True queue.append(i) return False edge_list = [] intervals = [] for _ in range(int(input())): a, b, c = map(int, input().split()) if a == 1: edge_list.append([]) intervals.append((b, c)) for idx, i in enumerate(intervals): if i[0] < b < i[1] or i[0] < c < i[1]: edge_list[-1].append(idx) if b < i[0] < c or b < i[1] < c: edge_list[idx].append(len(edge_list) - 1) else: print('YES' if dfs(edge_list, b - 1, c - 1) else 'NO') ```
output
1
37,147
13
74,295
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` from sys import stdin class Graph: def __init__(self): self.intervals = list() self.intervals.append(tuple()) def add_interval(self, a, b): edges = set() for i in range (1, len(self.intervals)): c = self.intervals[i][0] d = self.intervals[i][1] if (c < a and a < d) or (c < b and b < d): edges.add(i) if (a < c and c < b) or (a < d and d < b): self.intervals[i][2].add(len(self.intervals)) tup = (a, b, edges) self.intervals.append(tup) def connected(self, s, d): visited = [False]*len(self.intervals) queue = [] queue.append(s) visited[s] = True while queue: n = queue.pop(0) if n == d: return True for vertex in self.intervals[n][2]: if visited[vertex] == False: queue.append(vertex) visited[vertex] = True return False def print_graph(self): for i in range(1, len(self.intervals)): print("{0}: {1}".format(i, self.intervals[i])) #stdin = open('input.txt','r') queries = int(stdin.readline().strip()) graph = Graph() for i in range(queries): query = list(stdin.readline().strip().split()) if int(query[0]) == 1: graph.add_interval(int(query[1]), int(query[2])) else: if graph.connected(int(query[1]), int(query[2])): print("YES") else: print ("NO") #graph.print_graph() ```
instruction
0
37,155
13
74,310
Yes
output
1
37,155
13
74,311
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` def dfs(G, start, target, path_exists): s = [start] visited = set([]) # if not start in path_exists: # path_exists[start] = set([]) while(s): node = s.pop() if not node in visited: visited.add(node) # path_exists[start].add(node) a, b = G[node] for i, (c, d) in enumerate(G): if i != node: if (c < a < d) or (c < b < d): s.append(i) if i == target: return True if __name__ == "__main__": n = int(input()) G = [] path_exists = {} for _ in range(n): q, a, b = map(int, input().split()) if q == 1: G.append((a, b)) else: a -= 1 b -= 1 if dfs(G, a, b, path_exists): print("YES") else: print("NO") ```
instruction
0
37,156
13
74,312
Yes
output
1
37,156
13
74,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. In this problem at each moment you have a set of intervals. You can move from interval (a, b) from our set to interval (c, d) from our set if and only if c < a < d or c < b < d. Also there is a path from interval I1 from our set to interval I2 from our set if there is a sequence of successive moves starting from I1 so that we can reach I2. Your program should handle the queries of the following two types: 1. "1 x y" (x < y) — add the new interval (x, y) to the set of intervals. The length of the new interval is guaranteed to be strictly greater than all the previous intervals. 2. "2 a b" (a ≠ b) — answer the question: is there a path from a-th (one-based) added interval to b-th (one-based) added interval? Answer all the queries. Note, that initially you have an empty set of intervals. Input The first line of the input contains integer n denoting the number of queries, (1 ≤ n ≤ 100). Each of the following lines contains a query as described above. All numbers in the input are integers and don't exceed 109 by their absolute value. It's guaranteed that all queries are correct. Output For each query of the second type print "YES" or "NO" on a separate line depending on the answer. Examples Input 5 1 1 5 1 5 11 2 1 2 1 2 9 2 1 2 Output NO YES Submitted Solution: ``` #represents a node on the graph class interval(): a = 0 b = 0 i = 0 class neighbors(): interval = None edges = [] visited = False numQuery = int(input()) iList = [] #unecessary for now nList = [] index = 0 for x in range(numQuery): inp = input().split() ty = int(inp[0]) x = int(inp[1]) y = int(inp[2]) #create new node, make edges if (ty == 1): newInt = interval() newInt.a = x newInt.b = y newInt.i = index newNeigh = neighbors() newNeigh.interval = newInt nList.append(newNeigh) index += 1 for n in nList: #exists a path from interval n to new interval if ((x < n.interval.a and n.interval.a < y) or (x < n.interval.b and n.interval.b < y)): n.edges.append(newInt) #exists a path from new interval to interval n if ((n.interval.a < x and x < n.interval.b) or (n.interval.a < y and y < n.interval.b )): newNeigh.edges.append(n.interval) else: queue = [] start = x stop = y found = False for n in nList: if (n.interval.a == start): queue.append(n) n.visited = True else: n.visited = False while (len(queue) != 0): curr = queue.pop(0) curr.visited = True if (curr.interval.a == stop): found = True print ("YES") break else: for e in curr.edges: queue.append(nList[e.i]) if (found == False): print ("NO") nList = [] ```
instruction
0
37,162
13
74,324
No
output
1
37,162
13
74,325
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+
instruction
0
37,419
13
74,838
Tags: dfs and similar, graphs Correct Solution: ``` def put(): return map(int, input().split()) def dfs(x,flag=1): s,vis,ans = [x],[0]*n,['+']*m vis[x]= 1 while s: i = s.pop() for j,k in graph[i]: if vis[j]==0: if k*flag<0: ans[abs(k)-1]='-' elif k*flag>0: ans[abs(k)-1]='+' if flag==1 or k==0: s.append(j) vis[j]=1 return ''.join(ans), sum(vis) n,m,s = put() graph = [[] for i in range(n)] k=1 for _ in range(m): z,x,y = put() x,y = x-1,y-1 if z==1: graph[x].append((y, 0)) else: graph[x].append((y, k)) graph[y].append((x,-k)) k+=1 m = k-1 x,y = dfs(s-1, 1) print(y) print(x) x,y = dfs(s-1,-1) print(y) print(x) ```
output
1
37,419
13
74,839
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+
instruction
0
37,420
13
74,840
Tags: dfs and similar, graphs Correct Solution: ``` from collections import defaultdict import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict 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") sys.setrecursionlimit(7*10**4) 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 @bootstrap def dfs(u): vis[u]=1 for j in adj[u]: if d[j,u]==1: d1[j,u]="+" if d[u,j]==1: d1[u,j]="-" if d3[u,j]: if not vis[j]: yield dfs(j) yield @bootstrap def dfs2(u): vis[u] = 1 for j in adj[u]: if not vis[j]: if d[j, u] == 1: d2[j, u] = "-" if d[u, j] == 1: d2[u, j] = "+" yield dfs2(j) yield n,m,s=map(int,input().split()) edges=[] adj=[[] for i in range(n+1)] d=defaultdict(lambda:0) d3=defaultdict(lambda:0) d1=defaultdict(lambda:"+") d2=defaultdict(lambda:"+") for j in range(m): b=list(map(int,input().split())) if b[0]==1: adj[b[1]].append(b[2]) d3[b[1],b[2]]=1 else: adj[b[1]].append(b[2]) adj[b[2]].append(b[1]) d[b[1],b[2]]=1 edges.append([b[1],b[2]]) vis=[0]*(n+1) dfs(s) m1=vis.count(1) vis=[0]*(n+1) dfs2(s) m2=vis.count(1) res1=[] res2=[] for j in edges: res1.append(d1[j[0],j[1]]) res2.append(d2[j[0],j[1]]) print(m2) print("".join(res2)) print(m1) print("".join(res1)) ```
output
1
37,420
13
74,841
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+
instruction
0
37,421
13
74,842
Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline def put(): return map(int, input().split()) def dfs(x,flag=1): s,vis,ans = [x],[0]*n,['+']*m vis[x]= 1 while s: i = s.pop() for j,k in graph[i]: if vis[j]==0: if k*flag<0: ans[abs(k)-1]='-' elif k*flag>0: ans[abs(k)-1]='+' if flag==1 or k==0: s.append(j) vis[j]=1 return ''.join(ans), sum(vis) n,m,s = put() graph = [[] for i in range(n)] k=1 for _ in range(m): z,x,y = put() x,y = x-1,y-1 if z==1: graph[x].append((y, 0)) else: graph[x].append((y, k)) graph[y].append((x,-k)) k+=1 m = k-1 x,y = dfs(s-1, 1) print(y) print(x) x,y = dfs(s-1,-1) print(y) print(x) ```
output
1
37,421
13
74,843
Provide tags and a correct Python 3 solution for this coding contest problem. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+
instruction
0
37,422
13
74,844
Tags: dfs and similar, graphs Correct Solution: ``` import sys input = sys.stdin.readline def put(): return map(int, input().split()) def dfs0(x): s = [x] vis = [0] * n ans = ['+'] * m vis[x] = 1 while s: i = s.pop() for j, k in graph[i]: if (vis[j] == 0): if (k < 0): ans[-k - 1] = '-' elif (k > 0): ans[k - 1] = '+' s.append(j) vis[j] = 1 return ''.join(ans), sum(vis) def dfs1(x): s = [x] vis = [0] * n ans = ['+'] * m vis[x] = 1 while s: i = s.pop() for j, k in graph[i]: if (vis[j] == 0): if (k < 0): ans[-k - 1] = '+' elif (k > 0): ans[k - 1] = '-' if (k == 0): s.append(j) vis[j] = 1 return ''.join(ans), sum(vis) n,m,s = put() graph = [[] for i in range(n)] k = 1 for _ in range(m): z,x,y = put() x,y = x - 1, y - 1 if (z == 1): graph[x].append((y, 0)) else: graph[x].append((y, k)) graph[y].append((x, -k)) k += 1 m = k - 1 x, y = dfs0(s - 1) print(y) print(x) x, y = dfs1(s - 1) print(y) print(x) ```
output
1
37,422
13
74,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+ Submitted Solution: ``` l1 = input().split() n = int(l1[0]) m = int(l1[1]) s = int(l1[2]) max_graph = {} min_graph = {} max_sequence = [] min_sequence = [] reachable = [s] for i in range(m): l = input().split() t = int(l[0]) u = int(l[1]) v = int(l[2]) if t == 2: if u in reachable: max_sequence.append('+') if u in max_graph.keys() and u not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] min_sequence.append('-') if v in min_graph.keys() and u not in min_graph[v]: min_graph[v].append(u) elif v not in max_graph.keys(): min_graph[v] = [u] elif v in reachable: max_sequence.append('-') if v in max_graph.keys() and u not in max_graph[v]: max_graph[v].append(u) elif v not in max_graph.keys(): max_graph[v] = [u] min_sequence.append('+') if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in max_graph.keys(): min_graph[u] = [v] else: max_sequence.append('+') if u in max_graph.keys() and v not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] min_sequence.append('+') if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in max_graph.keys(): min_graph[u] = [v] elif t == 1: if u in max_graph.keys() and v not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in min_graph.keys(): min_graph[u] = [v] if u in reachable and v not in reachable: reachable.append(v) max_count = 1 visited = [s] working = [s] while working != []: u = working.pop() if u in max_graph.keys(): for v in max_graph[u]: if v not in visited: visited.append(v) max_count += 1 working.append(v) print(max_count) print(''.join(max_sequence)) min_count = 1 visited = [s] working = [s] while working != []: u = working.pop() if u in min_graph.keys(): for v in min_graph[u]: if v not in visited: visited.append(v) min_count += 1 working.append(v) print(min_count) print(''.join(min_sequence)) ```
instruction
0
37,423
13
74,846
No
output
1
37,423
13
74,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+ Submitted Solution: ``` l1 = input().split() n = int(l1[0]) m = int(l1[1]) s = int(l1[2]) max_graph = {} min_graph = {} max_sequence = [] min_sequence = [] for i in range(m): l = input().split() t = int(l[0]) u = int(l[1]) v = int(l[2]) if t == 2: if u == s: max_sequence.append('+') if u in max_graph.keys() and u not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] min_sequence.append('-') if v in min_graph.keys() and u not in min_graph[v]: min_graph[v].append(u) elif v not in max_graph.keys(): min_graph[v] = [u] elif v == s: max_sequence.append('-') if v in max_graph.keys() and u not in max_graph[v]: max_graph[v].append(u) elif v not in max_graph.keys(): max_graph[v] = [u] min_sequence.append('+') if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in max_graph.keys(): min_graph[u] = [v] else: max_sequence.append('+') if u in max_graph.keys() and v not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] min_sequence.append('+') if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in max_graph.keys(): min_graph[u] = [v] elif t == 1: if u in max_graph.keys() and v not in max_graph[u]: max_graph[u].append(v) elif u not in max_graph.keys(): max_graph[u] = [v] if u in min_graph.keys() and v not in min_graph[u]: min_graph[u].append(v) elif u not in min_graph.keys(): min_graph[u] = [v] max_count = 1 visited = [s] working = [s] while working != []: u = working.pop() if u in max_graph.keys(): for v in max_graph[u]: if v not in visited: visited.append(v) max_count += 1 working.append(v) print(max_count) print(''.join(max_sequence)) min_count = 1 visited = [s] working = [s] while working != []: u = working.pop() if u in min_graph.keys(): for v in min_graph[u]: if v not in visited: visited.append(v) min_count += 1 working.append(v) print(min_count) print(''.join(min_sequence)) ```
instruction
0
37,424
13
74,848
No
output
1
37,424
13
74,849
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+ Submitted Solution: ``` l1 = input().split() n = int(l1[0]) m = int(l1[1]) s = int(l1[2]) max_sequence = [] min_sequence = [] graph = {} reachable = [s] undirected = [] directed = [] for i in range(m): l = input().split() t = int(l[0]) u = int(l[1]) v = int(l[2]) if t == 2: undirected.append((u,v)) if u not in graph.keys(): graph[u] = [v] elif v not in graph[u]: graph[u].append(v) if v not in graph.keys(): graph[v] = [u] elif u not in graph[v]: graph[v].append(u) else: directed.append((u,v)) if u not in graph.keys(): graph[u] = [v] elif v not in graph[u]: graph[u].append(v) if u in reachable: reachable.append(v) max_count = 1 visited = [s] working = [s] used_edge = [] while working != []: u = working.pop() if u in graph.keys(): for v in graph[u]: if v not in visited: used_edge.append((u,v)) visited.append(v) max_count += 1 working.append(v) for edge in undirected: (u,v) = edge if (v, u) in used_edge: max_sequence.append('-') else: max_sequence.append('+') print(len(visited)) print(''.join(max_sequence)) for edge in undirected: (u,v) = edge if u in reachable and v not in reachable: min_sequence.append('-') else: min_sequence.append('+') print(len(reachable)) print(''.join(min_sequence)) ```
instruction
0
37,425
13
74,850
No
output
1
37,425
13
74,851
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Vasya has a graph containing both directed (oriented) and undirected (non-oriented) edges. There can be multiple edges between a pair of vertices. Vasya has picked a vertex s from the graph. Now Vasya wants to create two separate plans: 1. to orient each undirected edge in one of two possible directions to maximize number of vertices reachable from vertex s; 2. to orient each undirected edge in one of two possible directions to minimize number of vertices reachable from vertex s. In each of two plans each undirected edge must become directed. For an edge chosen directions can differ in two plans. Help Vasya find the plans. Input The first line contains three integers n, m and s (2 ≤ n ≤ 3·105, 1 ≤ m ≤ 3·105, 1 ≤ s ≤ n) — number of vertices and edges in the graph, and the vertex Vasya has picked. The following m lines contain information about the graph edges. Each line contains three integers ti, ui and vi (1 ≤ ti ≤ 2, 1 ≤ ui, vi ≤ n, ui ≠ vi) — edge type and vertices connected by the edge. If ti = 1 then the edge is directed and goes from the vertex ui to the vertex vi. If ti = 2 then the edge is undirected and it connects the vertices ui and vi. It is guaranteed that there is at least one undirected edge in the graph. Output The first two lines should describe the plan which maximizes the number of reachable vertices. The lines three and four should describe the plan which minimizes the number of reachable vertices. A description of each plan should start with a line containing the number of reachable vertices. The second line of a plan should consist of f symbols '+' and '-', where f is the number of undirected edges in the initial graph. Print '+' as the j-th symbol of the string if the j-th undirected edge (u, v) from the input should be oriented from u to v. Print '-' to signify the opposite direction (from v to u). Consider undirected edges to be numbered in the same order they are given in the input. If there are multiple solutions, print any of them. Examples Input 2 2 1 1 1 2 2 2 1 Output 2 - 2 + Input 6 6 3 2 2 6 1 4 5 2 3 4 1 4 1 1 3 1 2 2 3 Output 6 ++- 2 +-+ Submitted Solution: ``` l1 = input().split() n = int(l1[0]) m = int(l1[1]) s = int(l1[2]) max_sequence = [] min_sequence = [] graph = {} reachable = [s] undirected = [] directed = [] for i in range(m): l = input().split() t = int(l[0]) u = int(l[1]) v = int(l[2]) if t == 2: undirected.append((u, v)) else: directed.append((u, v)) for (u, v) in directed: if u not in graph.keys(): graph[u] = [v] elif v not in graph[u]: graph[u].append(v) min_reachable = [s] working = [s] while working != []: u = working.pop() if u in graph.keys(): for v in graph[u]: if v not in min_reachable: min_reachable.append(v) working.append(v) for (u, v) in undirected: if u in reachable and v not in reachable: min_sequence.append('-') else: min_sequence.append('+') for (u, v) in undirected: if u not in graph.keys(): graph[u] = [v] elif v not in graph[u]: graph[u].append(v) if v not in graph.keys(): graph[v] = [u] elif u not in graph[v]: graph[v].append(u) max_reachable = [s] working = [s] used_edge = [] parent = {} while working != []: u = working.pop() if u in graph.keys(): for v in graph[u]: if v not in max_reachable: used_edge.append((u, v)) max_reachable.append(v) working.append(v) parent[v] = u for (u, v) in undirected: if u in parent.keys() and parent[u] == v: max_sequence.append('-') else: max_sequence.append('+') print(len(max_reachable)) print(''.join(max_sequence)) print(len(min_reachable)) print(''.join(min_sequence)) ```
instruction
0
37,426
13
74,852
No
output
1
37,426
13
74,853
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,491
13
74,982
"Correct Solution: ``` N, Q = map(int, input().split()) class Unionfind(): def __init__(self, n): self.n = n self.parents = [-1] * (n+1) def find(self, x): if(self.parents[x] < 0): return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if(x == y): return if(self.parents[x] > self.parents[y]): x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}:{}'.format(r, self.members(r)) for r in self.roots()) uf = Unionfind(N) for i in range(Q): t, u, v = map(int, input().split()) if(t == 0): uf.union(u, v) uf.union(v, u) else: if(uf.same(u, v)): print(1) else: print(0) ```
output
1
37,491
13
74,983
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,492
13
74,984
"Correct Solution: ``` n,q=map(int,input().split()) import sys sys.setrecursionlimit(10**9) #再帰の上限をあげる root=[i for i in range(n+1)] #自分が親なら自身の番号を、そうでないなら(元)親の番号を示す def r(x): #親は誰? if root[x]==x: return x else: root[x]=r(root[x]) return root[x] def unite(x,y): x=r(x) y=r(y) if x==y: return if x>y: x,y=y,x root[y]=x for i in range(q): t,x,y=map(int,input().split()) if t==0: unite(x,y) else: if r(x)==r(y): print(1) else: print(0) ```
output
1
37,492
13
74,985
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,493
13
74,986
"Correct Solution: ``` N,Q = [int(i) for i in input().split()] L = list(range(N)) for _ in range(Q): n,u,v = [int(i) for i in input().split()] while u != L[u]: u = L[u] while v != L[v]: v = L[v] u,v = [max(u,v),min(u,v)] if n == 0: L[u] = v else: if u == v: print(1) else: print(0) ```
output
1
37,493
13
74,987
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,494
13
74,988
"Correct Solution: ``` class UnionFind: __slots__ = ["_data_size", "_roots"] def __init__(self, data_size: int) -> None: self._data_size = data_size self._roots = [-1] * data_size def __getitem__(self, x: int) -> int: while self._roots[x] >= 0: x = self._roots[x] return x def is_connected(self, x: int, y: int) -> bool: return self[x] == self[y] def unite(self, x: int, y: int) -> None: x, y = self[x], self[y] if x == y: return if self._roots[x] > self._roots[y]: x, y = y, x self._roots[x] += self._roots[y] self._roots[y] = x def main(): import sys readline = sys.stdin.buffer.readline N, Q = map(int, readline().split()) tree = UnionFind(N) res = [] for _ in range(Q): t, u, v = map(int, readline().split()) if t: res.append(int(tree.is_connected(u, v))) else: tree.unite(u, v) print("\n".join(map(str, res))) if __name__ == "__main__": main() ```
output
1
37,494
13
74,989
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,495
13
74,990
"Correct Solution: ``` class UnionFind: def __init__(self, size): self.par = [-1] * size def find(self, x): if self.par[x] < 0: return x else: self.par[x] = self.find(self.par[x]) return self.par[x] def unite(self, x, y): x, y = self.find(x), self.find(y) if x == y: return False if self.par[x] > self.par[y]: x, y = y, x self.par[x] += self.par[y] self.par[y] = x return True def same(self, x, y): return self.find(x) == self.find(y) def size(self, x): return -self.par[self.find(x)] N, Q = map(int, input().split()) uf = UnionFind(N) for _ in range(Q): t, u, v = map(int, input().split()) if t == 0: uf.unite(u, v) else: if uf.same(u, v): print(1) else: print(0) ```
output
1
37,495
13
74,991
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,496
13
74,992
"Correct Solution: ``` class UnionFind(): def __init__(self, n): self.n = n self.parents = [-1] * n def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x def size(self, x): return -self.parents[self.find(x)] def same(self, x, y): return self.find(x) == self.find(y) def members(self, x): root = self.find(x) return [i for i in range(self.n) if self.find(i) == root] def roots(self): return [i for i, x in enumerate(self.parents) if x < 0] def group_count(self): return len(self.roots()) def all_group_members(self): return {r: self.members(r) for r in self.roots()} def __str__(self): return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots()) N,Q=map(int,input().split()) uf=UnionFind(N) for i in range(Q): t,u,v=map(int,input().split()) if t==0: uf.union(u,v) else: if uf.find(u)==uf.find(v): print(1) else: print(0) ```
output
1
37,496
13
74,993
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,497
13
74,994
"Correct Solution: ``` # by size # 0-indexed class UnionFind: N=0 parent=None size=None def __init__(self,N): self.N=N self.parent=[i for i in range(self.N)] self.size=[1]*self.N def root(self,x): while x!=self.parent[x]: self.parent[x]=self.parent[self.parent[x]] x=self.parent[x] return x def same(self,x,y): return self.root(x)==self.root(y) def unite(self,x,y): x=self.root(x) y=self.root(y) if x==y: return if self.size[x]>self.size[y]: # 大きい方にくっつける self.parent[y]=x self.size[x]+=self.size[y] else: self.parent[x]=y self.size[y]+=self.size[x] def get_group_size(self,x): return self.size[self.root(x)] def get_roots(self): r=set() for i in range(self.N): r.add(self.root(i)) return r def show_parent(self): print(self.parent) def show_size(self): print(self.size) import sys readline = sys.stdin.readline N,Q = map(int,readline().split()) UF = UnionFind(N) for i in range(Q): t,u,v = map(int,readline().split()) u -= 1 v -= 1 if t == 0: UF.unite(u,v) else: print(int(UF.same(u,v))) ```
output
1
37,497
13
74,995
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1
instruction
0
37,498
13
74,996
"Correct Solution: ``` # 参考URL https://note.nkmk.me/python-union-find/ class UnionFind(): # 各要素の親要素の番号を格納するリスト # 要素が根(ルート)の場合は-(そのグループの要素数)を格納する def __init__(self, n): self.n = n self.parents = [-1] * n # 要素xが属するグループの根を返す def find(self, x): if self.parents[x] < 0: return x else: self.parents[x] = self.find(self.parents[x]) return self.parents[x] # 要素xが属するグループと要素yが属するグループとを併合する def union(self, x, y): x = self.find(x) y = self.find(y) if x == y: return if self.parents[x] > self.parents[y]: x, y = y, x self.parents[x] += self.parents[y] self.parents[y] = x # 要素x, yが同じグループに属するかどうかを返す def same(self, x, y): return self.find(x) == self.find(y) def main(): from sys import stdin def input(): return stdin.readline().strip() n, q = map(int, input().split()) uf = UnionFind(n) ans = [] for _ in range(q): t, u, v = map(int, input().split()) if t == 0: uf.union(u, v) else: if uf.same(u, v): ans.append(1) else: ans.append(0) for i in ans: print(i) main() ```
output
1
37,498
13
74,997
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: x = a while self.parent_or_size[x] >= 0: x = self.parent_or_size[x] while a != x: self.parent_or_size[a], a = x, self.parent_or_size[a] return x def size(self, a: int) -> int: return -self.parent_or_size[self.leader(a)] def groups(self): g = [[] for _ in range(self._n)] for i in range(self._n): g[self.leader(i)].append(i) return list(c for c in g if c) import sys input = sys.stdin.readline n, q = map(int, input().split()) d = dsu(n) for _ in range(q): t, u, v = map(int, input().split()) if t == 0: d.merge(u, v) else: print(int(d.same(u, v))) ```
instruction
0
37,499
13
74,998
Yes
output
1
37,499
13
74,999
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 9) class UnionFind(): def __init__(self, n): self.n = n self.root = [-1]*(n+1) self.rank = [0]*(n+1) def find(self, x):#親となる要素を探索 if self.root[x] < 0: return x else: self.root[x] = self.find(self.root[x])#再帰 return self.root[x] def unite(self, x, y): x = self.find(x) y = self.find(y) if x == y: return elif self.rank[x] > self.rank[y]:#深い木に連結 self.root[x] += self.root[y] self.root[y] = x#yの親をxとする else: self.root[y] += self.root[x] self.root[x] = y if self.rank[x] == self.rank[y]: self.rank[y] += 1 def issame(self, x, y):#x, yが同じ集合か判定 return self.find(x) == self.find(y) def count(self, x):#要素の個数 return (-1)*self.root[self.find(x)] n, q = map(int ,input().split()) uf = UnionFind(n) t = [0 for _ in range(q)] u = [0 for _ in range(q)] v = [0 for _ in range(q)] uf.__init__(n) for i in range(q): t[i], u[i], v[i] = map(int, input().split()) if t[i] == 0:uf.unite(u[i], v[i]) else:print(int(uf.issame(u[i], v[i]))) ```
instruction
0
37,500
13
75,000
Yes
output
1
37,500
13
75,001
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` class dsu: def __init__(self, n=0): self._n = n self.parent_or_size = [-1] * n def merge(self, a: int, b: int) -> int: x = self.leader(a) y = self.leader(b) if x == y: return x if self.parent_or_size[x] > self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a: int, b: int) -> bool: return self.leader(a) == self.leader(b) def leader(self, a: int) -> int: x = a while self.parent_or_size[x] >= 0: x = self.parent_or_size[x] while a != x: self.parent_or_size[a], a = x, self.parent_or_size[a] return x def size(self, a: int) -> int: return -self.parent_or_size[self.leader(a)] def groups(self): g = [[] for _ in range(self._n)] for i in range(self._n): g[self.leader(i)].append(i) return list(c for c in g if c) n, q = map(int, input().split()) d = dsu(n) for _ in range(q): t, u, v = map(int, input().split()) if t == 0: d.merge(u, v) else: print(int(d.same(u, v))) ```
instruction
0
37,501
13
75,002
Yes
output
1
37,501
13
75,003
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` import sys input = sys.stdin.readline class DSU: def __init__(self, n): self._n = n self.parent_or_size = [-1] * n def merge(self, a, b): x, y = self.leader(a), self.leader(b) if x == y: return x if -self.parent_or_size[x] < -self.parent_or_size[y]: x, y = y, x self.parent_or_size[x] += self.parent_or_size[y] self.parent_or_size[y] = x return x def same(self, a, b): return self.leader(a) == self.leader(b) def leader(self, a): stack = [] while self.parent_or_size[a] >= 0: stack.append(a) a = self.parent_or_size[a] for i in stack: self.parent_or_size[i] = a return a def size(self, a): return -self.parent_or_size[self.leader(a)] def groups(self): leader_buf = [self.leader(i) for i in range(self._n)] group_size = [0] * self._n for i in leader_buf: group_size[i] += 1 result = [[] for _ in range(self._n)] for i in range(self._n): result[leader_buf[i]].append(i) result = [i for i in result if i] return result n, q = map(int, input().split()) dsu = DSU(n) for _ in range(q): t, u, v = map(int, input().split()) if t == 0: dsu.merge(u, v) else: print(1 if dsu.same(u, v) else 0) ```
instruction
0
37,502
13
75,004
Yes
output
1
37,502
13
75,005
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` class UnionFind: __slots__ = ["_data_size", "_roots"] def __init__(self, data_size: int) -> None: self._data_size = data_size self._roots = [-1] * data_size def __getitem__(self, x: int) -> int: while self._roots[x] >= 0: x = self._roots[x] return x def is_connected(self, x: int, y: int) -> bool: return self[x] == self[y] def unite(self, x: int, y: int) -> None: x, y = self[x], self[y] if x == y: return if self._roots[x] > self._roots[y]: x, y = y, x self._roots[x] += self._roots[y] self._roots[y] = x import sys read = sys.stdin.read N, _, *X = map(int, readline().split()) tree = UnionFind(N) res = [] for t, u, v in zip(*[iter(X)] * 3): if t: res.append(int(tree.is_connected(u, v))) else: tree.unite(u, v) print("\n".join(map(str, res))) ```
instruction
0
37,503
13
75,006
No
output
1
37,503
13
75,007
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with N vertices and 0 edges. Process Q queries of the following types. * `0 u v`: Add an edge (u, v). * `1 u v`: Print 1 if u and v are in the same connected component, 0 otherwise. Constraints * 1 \leq N \leq 200,000 * 1 \leq Q \leq 200,000 * 0 \leq u_i, v_i \lt N Input Input is given from Standard Input in the following format: N Q t_1 u_1 v_1 t_2 u_2 v_2 : t_Q u_Q v_Q 出力 For each query of the latter type, print the answer. Example Input 4 7 1 0 1 0 0 1 0 2 3 1 0 1 1 1 2 0 0 2 1 1 3 Output 0 1 0 1 Submitted Solution: ``` n,m=list(map(int,input().split())) parents=[i for i in range(n)] def find(a): if parents[a]!=a: return find(parents[a]) return a def union(a,b): a=find(a) b=find(b) if a==b: return else: parents[a]=b for i in range(m): h,a,b=list(map(int,input().split())) if h==0: union(a,b) else: x=find(a) y=find(b) print(1 if x==y else 0) ```
instruction
0
37,504
13
75,008
No
output
1
37,504
13
75,009