message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above. Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i < B_i \leq N * The given graph is a tree. * 1 \leq C_i \leq 10^8 * All input values are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 C_1 A_2 B_2 C_2 : A_{N-1} B_{N-1} C_{N-1} Output Print the length of the longest Hamiltonian path in the complete graph created by Joisino. Examples Input 5 1 2 5 3 4 7 2 3 3 2 5 2 Output 38 Input 8 2 8 8 1 5 1 4 8 2 2 5 4 3 8 6 6 8 9 2 7 12 Output 132 Submitted Solution: ``` import sys input = sys.stdin.readline from collections import defaultdict n = int(input()) abd = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0 for i in range(n+1)] for a,b,d in abd: graph[a].append((b,d)) graph[b].append((a,d)) deg[a] += 1 deg[b] += 1 stack = [] root = 0 dp = [[] for i in range(n+1)] sm = [1 for i in range(n+1)] mx = [0 for i in range(n+1)] for i in range(1,n+1): if deg[i] == 1: stack.append(i) elif root == 0: root = i deg[i] += 1 ans = 0 flg = 0 while stack: x = stack.pop() if dp[x]: sm[x] += sum(dp[x]) if sm[x]*2 == n: flg = 1 for y,d in graph[x]: if deg[y] > 1: dp[y].append(sm[x]) if sm[x] == n-sm[x]: ans += (sm[x]*2-1)*d else: ans += min(sm[x],n-sm[x])*2*d deg[y] -= 1 if deg[y] == 1: stack.append(y) dmn = 10**18 if not flg: for a,b,d in abd: for v in (a,b): if not mx[v]: if dp[v]: mx[v] = max(max(dp[v]),n-1-sm[v]) else: mx[v] = n-2 if min(mx[a],mx[b])*2 < n: dmn = min(dmn,d) ans -= dmn print(ans) ```
instruction
0
14,009
13
28,018
No
output
1
14,009
13
28,019
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above. Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i < B_i \leq N * The given graph is a tree. * 1 \leq C_i \leq 10^8 * All input values are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 C_1 A_2 B_2 C_2 : A_{N-1} B_{N-1} C_{N-1} Output Print the length of the longest Hamiltonian path in the complete graph created by Joisino. Examples Input 5 1 2 5 3 4 7 2 3 3 2 5 2 Output 38 Input 8 2 8 8 1 5 1 4 8 2 2 5 4 3 8 6 6 8 9 2 7 12 Output 132 Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) abd = [list(map(int,input().split())) for i in range(n-1)] if n == 2: print(abd[0][2]) exit() graph = [[] for i in range(n+1)] deg = [0 for i in range(n+1)] for a,b,d in abd: graph[a].append((b,d)) graph[b].append((a,d)) deg[a] += 1 deg[b] += 1 stack = [] root = 0 dp = [1 for i in range(n+1)] for i in range(1,n+1): if deg[i] == 1: stack.append(i) elif root == 0: root = i deg[i] += 1 ans = 0 flg = 0 while stack: x = stack.pop() for y,d in graph[x]: if deg[y] > 1: dp[y] += dp[x] if dp[x] == n-dp[x]: flg = 1 ans += (dp[x]*2-1)*d else: ans += min(dp[x],n-dp[x])*2*d deg[y] -= 1 if deg[y] == 1: stack.append(y) if not flg: print(2/0) dmn = min(list(zip(*abd))[2]) ans -= dmn print(ans) ```
instruction
0
14,010
13
28,020
No
output
1
14,010
13
28,021
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices, numbered 1 through N. The i-th edge in this tree connects Vertices A_i and B_i and has a length of C_i. Joisino created a complete graph with N vertices. The length of the edge connecting Vertices u and v in this graph, is equal to the shortest distance between Vertices u and v in the tree above. Joisino would like to know the length of the longest Hamiltonian path (see Notes) in this complete graph. Find the length of that path. Constraints * 2 \leq N \leq 10^5 * 1 \leq A_i < B_i \leq N * The given graph is a tree. * 1 \leq C_i \leq 10^8 * All input values are integers. Input Input is given from Standard Input in the following format: N A_1 B_1 C_1 A_2 B_2 C_2 : A_{N-1} B_{N-1} C_{N-1} Output Print the length of the longest Hamiltonian path in the complete graph created by Joisino. Examples Input 5 1 2 5 3 4 7 2 3 3 2 5 2 Output 38 Input 8 2 8 8 1 5 1 4 8 2 2 5 4 3 8 6 6 8 9 2 7 12 Output 132 Submitted Solution: ``` import sys input = sys.stdin.readline n = int(input()) abd = [list(map(int,input().split())) for i in range(n-1)] if n == 2: print(abd[0][2]) exit() graph = [[] for i in range(n+1)] deg = [0 for i in range(n+1)] for a,b,d in abd: graph[a].append((b,d)) graph[b].append((a,d)) deg[a] += 1 deg[b] += 1 stack = [] root = 0 dp = [1 for i in range(n+1)] for i in range(1,n+1): if deg[i] == 1: stack.append(i) elif root == 0: root = i deg[i] += 1 ans = 0 flg = 0 while stack: x = stack.pop() for y,d in graph[x]: if deg[y] > 1: dp[y] += dp[x] if dp[x] == n-dp[x]: flg = 1 ans += (dp[x]*2-1)*d else: ans += min(dp[x],n-dp[x])*2*d deg[y] -= 1 if deg[y] == 1: stack.append(y) if not flg: dmn = min(list(zip(*abd))[2]) ans -= dmn print(ans) ```
instruction
0
14,011
13
28,022
No
output
1
14,011
13
28,023
Provide tags and a correct Python 3 solution for this coding contest problem. Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers β€” its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i β‰  j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them). For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: <image> A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 15 β‹… 10^4) β€” the number of the queries. The first line of each query contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers x and y (1 ≀ x, y ≀ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the maximum size of a good subtree of the given tree. Example Input 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 Note In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}.
instruction
0
14,244
13
28,488
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.readline t = int(input()) for _ in range(t): n = int(input()) ab = [list(map(int,input().split())) for i in range(n-1)] graph = [[] for i in range(n+1)] deg = [0]*(n+1) for a,b in ab: graph[a].append(b) graph[b].append(a) deg[a] += 1 deg[b] += 1 pnt = [max(deg[i]-1,1) for i in range(n+1)] root = 1 stack = [root] dist = [0]*(n+1) dist[root] = pnt[root] while stack: x = stack.pop() for y in graph[x]: if dist[y] == 0: dist[y] = dist[x]+pnt[y] stack.append(y) far = dist.index(max(dist)) root = far stack = [root] dist = [0]*(n+1) dist[root] = pnt[root] while stack: x = stack.pop() for y in graph[x]: if dist[y] == 0: dist[y] = dist[x]+pnt[y] stack.append(y) print(max(dist)) ```
output
1
14,244
13
28,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers β€” its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i β‰  j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them). For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: <image> A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 15 β‹… 10^4) β€” the number of the queries. The first line of each query contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers x and y (1 ≀ x, y ≀ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the maximum size of a good subtree of the given tree. Example Input 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 Note In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}. Submitted Solution: ``` from collections import defaultdict def maximum_subtree(u, graph, metrics): # leaf node if u not in graph: metrics[u] = (1, 1) return # recursively solve for all children for v in graph[u]: maximum_subtree(v, graph, metrics) # classify children non_loners = [v for v in graph[u] if metrics[v][0] > 1] loners = len(graph[u]) - len(non_loners) # get metrics if len(non_loners) == 0: best_tree = upward_tree = 1 + loners elif len(non_loners) == 1: best_tree = upward_tree = 1 + max(loners + metrics[non_loners[0]][1], metrics[non_loners[0]][0]) else: non_loners.sort(key=lambda x: metrics[x][1], reverse=True) # include both non_loners best_tree = 1 + loners + len(non_loners) - 2 + metrics[non_loners[0]][1] + metrics[non_loners[1]][1] upward_tree = 1 + loners + len(non_loners) - 1 + metrics[non_loners[0]][1] # include 1 non_loner best_tree = max(best_tree, 1 + max(metrics[i][0] for i in non_loners)) metrics[u] = (best_tree, upward_tree) q = int(input()) for _ in range(q): # obtain the tree n = int(input()) graph = defaultdict(list) for _ in range(n-1): u, v = list(map(int, input().split())) graph[min(u, v)].append(max(u, v)) metrics = {} maximum_subtree(1, graph, metrics) print(max(v[0] for v in metrics.values())) ```
instruction
0
14,245
13
28,490
No
output
1
14,245
13
28,491
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers β€” its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i β‰  j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them). For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: <image> A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 15 β‹… 10^4) β€” the number of the queries. The first line of each query contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers x and y (1 ≀ x, y ≀ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the maximum size of a good subtree of the given tree. Example Input 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 Note In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}. Submitted Solution: ``` q = int(input()) while(q > 0): n = int(input()) ady = [[] for _ in range(n + 1)] dp = [0] * (n + 1) sol = int(1) def dfs(nod, p): global dp, ady, sol multiset = [] may1 = int(0) may2 = int(0) for to in ady[nod]: if(to == p): continue dfs(to, nod) dp[nod] = max(dp[nod], dp[to]) if(dp[to] >= may1): if(may1 > may2): may2 = may1 may1 = dp[to] if(len(ady[nod]) > 2): dp[nod] += len(ady[nod]) - 1 if(p != -1): dp[nod] -= 1 sol = max(sol, may1 + may2 + len(ady[nod]) - (may1 != 0) - (may2 != 0) + 1) dp[nod] += 1 for i in range(n - 1): n1, n2 = input().split() n1 = int(n1) n2 = int(n2) ady[n1].append(n2) ady[n2].append(n1) dfs(1, -1) q -= 1 print(sol) ```
instruction
0
14,246
13
28,492
No
output
1
14,246
13
28,493
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers β€” its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i β‰  j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them). For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: <image> A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 15 β‹… 10^4) β€” the number of the queries. The first line of each query contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers x and y (1 ≀ x, y ≀ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the maximum size of a good subtree of the given tree. Example Input 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 Note In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}. Submitted Solution: ``` q = int(input()) while(q > 0): n = int(input()) ady = [[] for _ in range(n + 1)] dp = [0] * (n + 1) sol = int(1) def dfs(nod, p): global dp, ady, sol multiset = [] may1 = int(0) may2 = int(0) for to in ady[nod]: if(to == p): continue dfs(to, nod) dp[nod] = max(dp[nod], dp[to]) if(dp[to] > may1): if(may1 > may2): may2 = may1 may1 = dp[to] if(len(ady[nod]) > 2): dp[nod] += len(ady[nod]) - 1 if(p != -1): dp[nod] -= 1 sol = max(sol, may1 + may2 + len(ady[nod]) - (may1 != 0) - (may2 != 0) + 1) dp[nod] += 1 for i in range(n - 1): n1, n2 = input().split() n1 = int(n1) n2 = int(n2) ady[n1].append(n2) ady[n2].append(n1) dfs(1, -1) q -= 1 print(sol) ```
instruction
0
14,247
13
28,494
No
output
1
14,247
13
28,495
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Assume that you have k one-dimensional segments s_1, s_2, ... s_k (each segment is denoted by two integers β€” its endpoints). Then you can build the following graph on these segments. The graph consists of k vertexes, and there is an edge between the i-th and the j-th vertexes (i β‰  j) if and only if the segments s_i and s_j intersect (there exists at least one point that belongs to both of them). For example, if s_1 = [1, 6], s_2 = [8, 20], s_3 = [4, 10], s_4 = [2, 13], s_5 = [17, 18], then the resulting graph is the following: <image> A tree of size m is good if it is possible to choose m one-dimensional segments so that the graph built on these segments coincides with this tree. You are given a tree, you have to find its good subtree with maximum possible size. Recall that a subtree is a connected subgraph of a tree. Note that you have to answer q independent queries. Input The first line contains one integer q (1 ≀ q ≀ 15 β‹… 10^4) β€” the number of the queries. The first line of each query contains one integer n (2 ≀ n ≀ 3 β‹… 10^5) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers x and y (1 ≀ x, y ≀ n) denoting an edge between vertices x and y. It is guaranteed that the given graph is a tree. It is guaranteed that the sum of all n does not exceed 3 β‹… 10^5. Output For each query print one integer β€” the maximum size of a good subtree of the given tree. Example Input 1 10 1 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 Output 8 Note In the first query there is a good subtree of size 8. The vertices belonging to this subtree are {9, 4, 10, 2, 5, 1, 6, 3}. Submitted Solution: ``` import sys def get_ints(): return int(sys.stdin.readline()) q = get_ints() while(q > 0): n = int(input()) ady = [[] for _ in range(n + 1)] dp = [0] * (n + 1) sol = int(1) def dfs(nod, p): global dp, ady, sol may1 = int(0) may2 = int(0) for to in ady[nod]: if(to == p): continue dfs(to, nod) dp[nod] = max(dp[nod], dp[to]) if(dp[to] >= may1): if(may1 > may2): may2 = may1 may1 = dp[to] elif(dp[to] >= may2): may2 = dp[to] if(len(ady[nod]) > 2): dp[nod] += len(ady[nod]) - 1 if(p != -1): dp[nod] -= 1 sol = max(sol, may1 + may2 + len(ady[nod]) - (may1 != 0) - (may2 != 0) + 1) dp[nod] += 1 for i in range(n - 1): n1, n2 = [int(x) for x in sys.stdin.readline().split()] ady[n1].append(n2) ady[n2].append(n1) dfs(1, -1) q -= 1 sys.stdout.write(str(sol)) ```
instruction
0
14,248
13
28,496
No
output
1
14,248
13
28,497
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,673
13
29,346
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) g = [[] for _ in range(n)] for _ in range(n-1): u, v = map(int, input().split()) u -= 1 v -= 1 g[u].append(v) g[v].append(u) c = list(map(int, input().split())) dif = [0 for _ in range(n)] cnt = 0 for v in range(n): dif[v] = 0 for u in g[v]: if c[u] != c[v]: dif[v] += 1 cnt += dif[v] > 0 ans = -1 for v in range(n): if dif[v] + 1 >= cnt: ans = v+1 if ans >= 0: print('YES\n%d' % ans) else: print('NO') ```
output
1
14,673
13
29,347
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,674
13
29,348
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` n = int(input()) edges = [tuple(map(int, input().split())) for i in range(n - 1)] colours = input().split() '''better plan: 1)take any node 2)go up while parent has the same colour 3)as soon as colour changes save the result 4)check if result is good enough 5)if no, then it's unsolvable 6)else -- print result ''' '''even better plan: 1)take any edge than connects two different colour nodes 2)if imbossible -- we won 3)else check if one of two nodes in the picked edge is good enough 4)we have ans ''' possible_roots = [] for edge in edges: one, two = edge if colours[one - 1] != colours[two - 1]: possible_roots.append(edge) if len(possible_roots) == 0: print('YES') print(1) exit() one, two = possible_roots[0] is_one_root = False is_two_root = False for edge in possible_roots[1:]: if one in edge: is_one_root = True elif two in edge: is_two_root = True else: print('NO') exit() if is_one_root and is_two_root: print('NO') exit() print('YES') if is_one_root: print(one) else: print(two) ```
output
1
14,674
13
29,349
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,675
13
29,350
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` read = lambda: map(int, input().split()) n = int(input()) ed = [] for i in range(n - 1): u, v = read() if u > v: u, v = v, u ed.append((u, v)) c = [0] + list(read()) edr = [] g = [list() for i in range(n + 1)] ver = set() for u, v in ed: if c[u] != c[v]: g[u].append(v) g[v].append(u) ver.add(u) ver.add(v) root = 1 for i in range(1, n + 1): if len(g[i]) > 1: root = i break if len(g[i]) == 1: root = i was = [0] * (n + 1) was[root] = 1 for u in g[root]: was[u] = 1 for i in ver: if not was[i]: print('NO') exit() print('YES') print(root) ```
output
1
14,675
13
29,351
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,676
13
29,352
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` N = int(input()) G = [[] for i in range(N)] d = [] for i in range(N - 1): a, b = map(int, input().split()) a, b = a - 1, b - 1 G[a].append(b) G[b].append(a) d.append((a, b)) C = list(map(int, input().split())) num = 0 for i in range(N - 1): if C[d[i][0]] != C[d[i][1]]: num += 1 for i in range(N): s = 0 for j in G[i]: if C[i] != C[j]: s += 1 if s == num: print('YES') print(i + 1) break else: print('NO') ```
output
1
14,676
13
29,353
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,677
13
29,354
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n = mint() e = [ [] for i in range(n+1)] for i in range(n-1): u,v = mints() e[u].append(v) e[v].append(u) c = list(mints()) start = None for i in range(1, n+1): ci = c[i-1] for j in e[i]: if c[j-1] != ci: start = (i, j) break if start != None: break if start == None: print("YES") print(1) return for s in start: was = [False]*(n+1) ql = 0 q = [] was[s] = True for i in e[s]: was[i] = True q.append((i, c[i-1])) ok = True while ql < len(q): v, cc = q[ql] ql += 1 for i in e[v]: if was[i]: continue was[i] = True if c[i-1] != cc: ok = False q.append((i, cc)) if ok: print("YES") print(s) return print("NO") solve() ```
output
1
14,677
13
29,355
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,678
13
29,356
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` import sys import collections import itertools n = int(sys.stdin.readline()) graph = collections.defaultdict(list) for _ in range(n - 1): u, v = map(int, str.split(sys.stdin.readline())) graph[u].append(v) graph[v].append(u) colors = tuple(map(int, str.split(sys.stdin.readline()))) root = None root_possible = [] for node in graph: diff_subs = [] for sub_node in graph[node]: if colors[node - 1] != colors[sub_node - 1]: diff_subs.append(sub_node) if len(diff_subs) > 1: if root is None: root = node else: print("NO") exit() elif len(diff_subs) == 1: root_possible.append((node, diff_subs[0])) root_possible_set = set(itertools.chain.from_iterable(root_possible)) if root: print("YES") print(root) elif not root_possible: print("YES") print(1) elif len(root_possible_set) == 2: print("YES") print(next(iter(root_possible_set))) else: print("NO") ```
output
1
14,678
13
29,357
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,679
13
29,358
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` #!/usr/bin/env python3 def ri(): return map(int, input().split()) n = int(input()) e = [] for i in range(n-1): a, b = ri() a -= 1 b -= 1 e.append([a, b]) c = list(ri()) ed = [] for ee in e: if c[ee[0]] != c[ee[1]]: ed.append(ee) if len(ed) == 0: print("YES") print(1) exit() cand = ed[0] not0 = 0 not1 = 0 for ee in ed: if cand[0] != ee[0] and cand[0] != ee[1]: not0 = 1 break for ee in ed: if cand[1] != ee[0] and cand[1] != ee[1]: not1 = 1 break if not0 == 0: print("YES") print(cand[0]+1) elif not1 == 0: print("YES") print(cand[1]+1) else: print("NO") ```
output
1
14,679
13
29,359
Provide tags and a correct Python 3 solution for this coding contest problem. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO
instruction
0
14,680
13
29,360
Tags: dfs and similar, dp, dsu, graphs, implementation, trees Correct Solution: ``` class Node: def __init__(self, number, color, adjacency_set): self.number = number self.color = color self.adjacency_set = adjacency_set def main(): n = int(input()) tree = [] for i in range(n): tree.append(Node(i+1, 0, set())) for i in range(n-1): I = input().split(" ") a = int(I[0]) b = int(I[1]) tree[a-1].adjacency_set.add(tree[b-1]) tree[b-1].adjacency_set.add(tree[a-1]) I = input().split(" ") for i in range(n): tree[i].color = int(I[i]) edges = set() for node in tree: for adjacent_node in node.adjacency_set: if node.color != adjacent_node.color: edges.add(frozenset([node, adjacent_node])) if len(edges) == 0: print("YES") print(1) return if len(edges) == 1: print("YES") only_set = edges.pop() print(list(only_set)[0].number) return # now we know that len(edges) >= 2 intersection = edges.pop() for edge in edges: intersection &= edge if len(intersection) == 0: print("NO") return print("YES") print(list(intersection)[0].number) main() ```
output
1
14,680
13
29,361
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) e = [[0, 0] for i in range(n - 1)] c = [0 for i in range(n)] t = [] num = 0 for i in range(n - 1): inp = input().split() for j in range(2): e[i][j] = int(inp[j]) - 1 inp = input().split() for i in range(n): c[i] = int(inp[i]) for i in range(n - 1): if c[e[i][0]] != c[e[i][1]]: #print(e[i], "opposite color") if num == 0: t = e[i] num += 1 else: if len(t) > 1 and t[1] not in e[i]: t.remove(t[1]) if len(t) > 0 and t[0] not in e[i]: t.remove(t[0]) #print(t) if num == 0: print("YES") print(1) else: if len(t) == 0: print("NO") else: print("YES") print(t[0] + 1) ```
instruction
0
14,681
13
29,362
Yes
output
1
14,681
13
29,363
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) graph=dict() for i in range(1,n+1): graph[i]=[] diff=[] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) graph[v].append(u) color=list(map(int,input().split())) # print(color) # print(graph) flag=0 # used to indicate if two different colors nodes are present in an edge for i in range(1,n+1): if(graph[i]!=[]): for j in graph[i]: if(color[i-1]!=color[j-1]): diff.append(i) diff.append(j) flag=1 break if(flag==1): break # print(diff) #check=[-1 for i in range(n)] def dfs(graph,node,col,parentnode): # print(node,col,color[node-1]) # global check if(color[node-1]!=col): return -1 # check[node-1]=0 if(graph[node]!=[]): for i in graph[node]: if(i!=parentnode): f1=dfs(graph,i,col,node) if(f1==-1): return -1 return 1 if(flag==0): # single color nodes are present in the entire tree print("YES") print(n) else: # different color present # print("check",check) #check[diff[0]-1]=0 f=1 for i in graph[diff[0]]: f=dfs(graph,i,color[i-1],diff[0]) # print(f,i) if(f==-1): # some of the children nodes are of different color break if(f!=-1):# if all the children satisfy the condition # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[0]) # else: # f=-1 if(f==-1): # the checking of the children node has started # for i in range(n): # check[i]=-1 # check[diff[1]-1]=0 # print("check1",check1) f2=1 for i in graph[diff[1]]: f2=dfs(graph,i,color[i-1],diff[1]) # print(f2,i) if(f2==-1): break # print(f2,check1) if(f2==-1): print("NO") else:# if all the children satisfy the condition # print(color) # flag1=0 # for i in range(n): # if(check[i]==-1): # for j in range(i+1,n): # if(check[j]==-1 and color[j]!=color[i]): # flag1=-1 # two different colors found # break # if(flag1==-1): # break # if(flag1==0): print("YES") print(diff[1]) # else: # print("NO") ```
instruction
0
14,682
13
29,364
Yes
output
1
14,682
13
29,365
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) edges = list() edges = [] for i in range(n-1): edge = [] edge = input().split(' ') edge = list(map(int,edge)) edges.append(edge) colors = [] colors = input().split(' ') colors = list(map(int,colors)) colors.insert(0,0) if n<3: print('YES') print(edges[0][0]) exit() commonedge = [] for edge in edges: if colors[edge[0]] != colors[edge[1]]: if len(commonedge)==0: commonedge.append(edge[0]) commonedge.append(edge[1]) elif len(commonedge)==2: if commonedge.count(edge[0])==0 and commonedge.count(edge[1])==0: print('NO') exit() elif commonedge.count(edge[1])==0: if commonedge[0]==edge[0]: del commonedge[1] else: del commonedge[0] else: if commonedge[0]==edge[1]: del commonedge[1] else: del commonedge[0] else: if commonedge.count(edge[0])==0 and commonedge.count(edge[1])==0: print('NO') exit() print('YES') if len(commonedge)>0: print(commonedge[0]) else: print(edges[0][0]) ```
instruction
0
14,683
13
29,366
Yes
output
1
14,683
13
29,367
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) edges = [] for i in range(n-1): edges.append(list(map(int, input().split()))) colors = [0] + list(map(int, input().split())) tops = [] for e in edges: if colors[e[0]] != colors[e[1]]: tops.append(e) if not tops: print('YES') print(1) else: s = set(tops[0]) list(map(lambda t: s.intersection_update(set(t)), tops)) if s: print('YES') print(list(s)[0]) else: print('NO') ```
instruction
0
14,684
13
29,368
Yes
output
1
14,684
13
29,369
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n = int(input()) edges = [tuple(map(int, input().split())) for i in range(n - 1)] colours = input().split() '''better plan: 1)take any node 2)go up while parent has the same colour 3)as soon as colour changes save the result 4)check if result is good enough 5)if no, then it's unsolvable 6)else -- print result ''' '''even better plan: 1)take any edge than connects two different colour nodes 2)if imbossible -- we won 3)else check if one of two nodes in the picked edge is good enough 4)we have ans ''' possible_roots = [] for edge in edges: one, two = edge if colours[one - 1] != colours[two - 1]: possible_roots.append(edge) if len(possible_roots) == 0: print('YES') print(1) one, two = possible_roots[0] is_one_root = False is_two_root = False for edge in possible_roots[1:]: if one in edge: is_one_root = True if two in edge: is_two_root = True if is_one_root and is_two_root: print('NO') exit() print('YES') if is_one_root: print(one) else: print(two) ```
instruction
0
14,685
13
29,370
No
output
1
14,685
13
29,371
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` from collections import Counter def dfs(graph, start): c = colors[start] top = set() visited, stack = [], [start] while stack: vertex = stack.pop() if vertex not in visited: if vertex not in graph: top.add(vertex) else: if colors[vertex] == c: visited.append(vertex) stack.extend(graph[vertex] - set(visited)) else: top.add(vertex) return visited, top n = int(input()) tree = {} tops = [] possible = True for _ in range(n-1): a, b = map(int, input().split()) tree[a] = tree.get(a, set()).union({b}) tree[b] = tree.get(b, set()).union({a}) colors = [0] + list(map(int, input().split())) ncolors = Counter(colors) del ncolors[0] tree2 = tree.copy() while tree: i = list(tree.keys())[0] vs, top = dfs(tree, i) tops.append(top) for k in vs: tree.pop(k, None) # print(vs, i) # print(tops) count = Counter([item for sublist in tops for item in sublist]) # print(count) # print(ncolors) if len(ncolors) == 1: print(1) else: if max(count, key=lambda x: count[x]) >= len(tops) - 1: print('YES') print(max(count, key=lambda x: count[x])) else: print('NO') # print(Counter(colors)) # print(tree) # print(dfs(tree, 1)) ```
instruction
0
14,686
13
29,372
No
output
1
14,686
13
29,373
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) graph=dict() for i in range(1,n+1): graph[i]=[] parent=dict() diff=[] for i in range(n-1): u,v=map(int,input().split()) graph[u].append(v) parent[v]=u color=list(map(int,input().split())) # print(color) # print(graph) flag=0 # used to indicate if two different colors nodes are present in an edge for i in range(1,n+1): if(graph[i]!=[]): for j in graph[i]: if(color[i-1]!=color[j-1]): diff.append(i) diff.append(j) flag=1 break if(flag==1): break # print(diff) def dfs(graph,node,col): # print(node,col,color[node-1]) if(color[node-1]!=col): return -1 if(graph[node]!=[]): for i in graph[node]: f1=dfs(graph,i,col) if(f1==-1): return -1 return 1 if(flag==0): # single color nodes are present in the entire tree print("YES") print(1) else: f=0 for i in graph[diff[0]]: f=dfs(graph,i,color[i-1]) # print(f,i) if(f==-1): # some of the children nodes are of different color break if(f!=-1): print("YES") print(diff[0]) else: # the checking of the children node has started f2=0 for i in graph[diff[1]]: f2=dfs(graph,i,color[i-1]) # print(f2,i) if(f2==-1): break if(f2!=-1): print("YES") print(diff[1]) else: print("NO") ```
instruction
0
14,687
13
29,374
No
output
1
14,687
13
29,375
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Each New Year Timofey and his friends cut down a tree of n vertices and bring it home. After that they paint all the n its vertices, so that the i-th vertex gets color ci. Now it's time for Timofey birthday, and his mother asked him to remove the tree. Timofey removes the tree in the following way: he takes some vertex in hands, while all the other vertices move down so that the tree becomes rooted at the chosen vertex. After that Timofey brings the tree to a trash can. Timofey doesn't like it when many colors are mixing together. A subtree annoys him if there are vertices of different color in it. Timofey wants to find a vertex which he should take in hands so that there are no subtrees that annoy him. He doesn't consider the whole tree as a subtree since he can't see the color of the root vertex. A subtree of some vertex is a subgraph containing that vertex and all its descendants. Your task is to determine if there is a vertex, taking which in hands Timofey wouldn't be annoyed. Input The first line contains single integer n (2 ≀ n ≀ 105) β€” the number of vertices in the tree. Each of the next n - 1 lines contains two integers u and v (1 ≀ u, v ≀ n, u β‰  v), denoting there is an edge between vertices u and v. It is guaranteed that the given graph is a tree. The next line contains n integers c1, c2, ..., cn (1 ≀ ci ≀ 105), denoting the colors of the vertices. Output Print "NO" in a single line, if Timofey can't take the tree in such a way that it doesn't annoy him. Otherwise print "YES" in the first line. In the second line print the index of the vertex which Timofey should take in hands. If there are multiple answers, print any of them. Examples Input 4 1 2 2 3 3 4 1 2 1 1 Output YES 2 Input 3 1 2 2 3 1 2 3 Output YES 2 Input 4 1 2 2 3 3 4 1 2 1 2 Output NO Submitted Solution: ``` n=int(input()) ip=[[] for i in range(n)] for i in range(n-1): a,b=map(int,input().split()) a-=1 b-=1 ip[a].append(b) ip[b].append(a) col=list(map(int,input().split())) cs=[0 for i in range(n)] for i in range(n): count=0 for j in ip[i]: if col[j]!=col[i]: count+=1 cs[i]=count #print(cs) #print(ip) count=0 c1=0 for i in range(n): if cs[i]==0: continue elif cs[i]==1: c1+=1 ans1=i+1 else: #print("csi",cs[i]) count+=1 ans=i+1 #print(count) if count==0: if c1==0: print('YES') print(1) elif c1==1: print('YES') print(ans1) else: print('NO') elif count==1: if c1<=2: print('YES') print(ans) else: print('NO') else: print('NO') ```
instruction
0
14,688
13
29,376
No
output
1
14,688
13
29,377
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,724
13
29,448
Tags: constructive algorithms, trees Correct Solution: ``` def read(): return tuple(int(x) for x in input().split()) def main(): (h, ) = read() a = read() tree = [] fi = 0 flag = False for i, x in enumerate(a): if fi == 0: if not flag and x > 1: flag = True elif flag and x > 1: fi = len(tree) else: flag = False tree.extend([len(tree)] * x) if fi == 0: print('perfect') return else: print('ambiguous') print(' '.join(str(x) for x in tree)) tree[fi] = fi - 1 print(' '.join(str(x) for x in tree)) main() ```
output
1
14,724
13
29,449
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,725
13
29,450
Tags: constructive algorithms, trees Correct Solution: ``` h=int(input()) l=list(map(int,input().split())) x=False pos=0 s=1 for i in range(h): if (l[i]!=1) and (l[i+1]!=1) : pos=i+1 x=True print("ambiguous") break if not x: print("perfect") else: ch="0" ch1="0" for i in range(1,len(l)): ch+=(" "+str(s))*l[i] if i!=pos: ch1+=(" "+str(s))*l[i] else: ch1+=" "+str(s-1)+(" "+str(s))*(l[i]-1) s+=l[i] print(ch) print(ch1) ```
output
1
14,725
13
29,451
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,726
13
29,452
Tags: constructive algorithms, trees Correct Solution: ``` n = int(input()) h = [int(i) for i in input().split()] flag = 0 for i in range(n): if h[i] >= 2 and h[i+1] >= 2: flag = i if flag: a = [] c = 0 for i in range(n+1): for j in range(h[i]): a.append(c) c += h[i] b = [] c = 0 for i in range(n+1): for j in range(h[i]): if i == flag+1 and j == 0: b.append(c-1) else: b.append(c) c += h[i] print("ambiguous") print(" ".join([str(i) for i in a])) print(" ".join([str(i) for i in b])) else: print("perfect") ```
output
1
14,726
13
29,453
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,727
13
29,454
Tags: constructive algorithms, trees Correct Solution: ``` h = int(input()) a = list(map(int,input().split())) perfect = True for i in range(h): if a[i]>1 and a[i+1]>1: perfect = False break if perfect: print("perfect") else: print("ambiguous") tree1 = list(range(h+1)) tree2 = list(tree1) for i in range(1,h+1): tree1.extend([i]*(a[i]-1)) for i in range(1,h+1): p = i if a[i]>1 and a[i-1]>1: p = len(tree2) tree2.extend([p]*(a[i]-1)) print(" ".join(map(str,tree1))) print(" ".join(map(str,tree2))) ```
output
1
14,727
13
29,455
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,728
13
29,456
Tags: constructive algorithms, trees Correct Solution: ``` h = int(input()) a = list(map(int,input().split())) p, c, f = 0, 0, False s1, s2 = [], [] for i in a: for j in range(i): s1.append(c) if j == i-1 and not f and p >= 2 and i >= 2: f = True s2.append(c-1) else : s2.append(c) c += i p = i print('perfect' if not f else 'ambiguous') if f: print(*s1) print(*s2) ```
output
1
14,728
13
29,457
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,729
13
29,458
Tags: constructive algorithms, trees Correct Solution: ``` import sys #f = open('input', 'r') f = sys.stdin n = f.readline() n = int(n) cl = f.readline().split() cl = [int(x) for x in cl] c_index = 0 p1 = ['0'] p2 = ['0'] ambiguous = False cur_index = 1 for i, c in enumerate(cl): if i == 0: continue if i > 0 and cl[i-1] > 1 and c > 1: ambiguous = True p1 += [str(cur_index)] * c p2 += [str(cur_index-1)] + [str(cur_index)] * (c-1) else: p1 += [str(cur_index)] * c p2 += [str(cur_index)] * c cur_index += c if ambiguous: print('ambiguous') print(' '.join(p1)) print(' '.join(p2)) else: print('perfect') ```
output
1
14,729
13
29,459
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,730
13
29,460
Tags: constructive algorithms, trees Correct Solution: ``` h = int(input()) a = list(map(int, input().split())) perfect = True for i in range(1, len(a)): if (a[i] != 1 and a[i - 1] != 1): perfect = False print ("perfect" if perfect else "ambiguous") ret1 = [0] * sum(a) ret2 = [0] * sum(a) #print (ret1) node = 0; p=0 if (perfect == False): for i in range(len(a)): for j in range(a[i]): ret1[node] = p node += 1; p = node; p1 = 0 p2 = 0 node = 0 for i in range(len(a)): for j in range(a[i]): if (j & 1): ret2[node] = p1 else: ret2[node] = p2 node += 1 p1 = node p2 = node if (a[i] != 1): p1 = node; p2 = node - 1; print (' '.join(str(x) for x in ret1)) print (' '.join(str(x) for x in ret2)) ```
output
1
14,730
13
29,461
Provide tags and a correct Python 3 solution for this coding contest problem. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image>
instruction
0
14,731
13
29,462
Tags: constructive algorithms, trees Correct Solution: ``` """ Author - Satwik Tiwari . 21th NOV , 2020 - Saturday """ #=============================================================================================== #importing some useful libraries. from __future__ import division, print_function from fractions import Fraction import sys import os from io import BytesIO, IOBase from functools import cmp_to_key # from itertools import * from heapq import * from math import gcd, factorial,floor,ceil,sqrt from copy import deepcopy from collections import deque from bisect import bisect_left as bl from bisect import bisect_right as br from bisect import bisect #============================================================================================== #fast I/O 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") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() if sys.version_info[0] < 3: sys.stdin, sys.stdout = FastIO(sys.stdin), FastIO(sys.stdout) else: sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) # inp = lambda: sys.stdin.readline().rstrip("\r\n") #=============================================================================================== ### START ITERATE RECURSION ### from types import GeneratorType def iterative(f, stack=[]): def wrapped_func(*args, **kwargs): if stack: return f(*args, **kwargs) to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) continue stack.pop() if not stack: break to = stack[-1].send(to) return to return wrapped_func #### END ITERATE RECURSION #### #=============================================================================================== #some shortcuts def inp(): return sys.stdin.readline().rstrip("\r\n") #for fast input def out(var): sys.stdout.write(str(var)) #for fast output, always take string def lis(): return list(map(int, inp().split())) def stringlis(): return list(map(str, inp().split())) def sep(): return map(int, inp().split()) def strsep(): return map(str, inp().split()) # def graph(vertex): return [[] for i in range(0,vertex+1)] def testcase(t): for pp in range(t): solve(pp) def google(p): print('Case #'+str(p)+': ',end='') def lcm(a,b): return (a*b)//gcd(a,b) def power(x, y, p) : y%=(p-1) #not so sure about this. used when y>p-1. if p is prime. res = 1 # Initialize result x = x % p # Update x if it is more , than or equal to p if (x == 0) : return 0 while (y > 0) : if ((y & 1) == 1) : # If y is odd, multiply, x with result res = (res * x) % p y = y >> 1 # y = y/2 x = (x * x) % p return res def ncr(n,r): return factorial(n) // (factorial(r) * factorial(max(n - r, 1))) def isPrime(n) : if (n <= 1) : return False if (n <= 3) : return True if (n % 2 == 0 or n % 3 == 0) : return False i = 5 while(i * i <= n) : if (n % i == 0 or n % (i + 2) == 0) : return False i = i + 6 return True inf = pow(10,20) mod = 10**9+7 #=============================================================================================== # code here ;)) def solve(case): n = int(inp()) a = lis() cnt = False for i in range(1,n+1): if(a[i] > 1 and a[i-1] > 1): cnt = True if(not cnt): print('perfect') return print('ambiguous') ans = [0] par = 1 for i in range(1,n+1): # print(i,par) for j in range(a[i]): ans.append(par) par+=a[i-1] # print(ans) ans2 = [0] par = 1 for i in range(1,n+1): # print(i,a[i-1],par) for j in range(a[i]-1): ans2.append(par) if(a[i-1] > 1): ans2.append(par+1) else: ans2.append(par) par+=a[i-1] # print(ans2) print(' '.join(str(ans[i]) for i in range(len(ans)))) print(' '.join(str(ans2[i]) for i in range(len(ans2)))) testcase(1) # testcase(int(inp())) ```
output
1
14,731
13
29,463
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) pre = a[0] index = -1 for i in range(1, n + 1): if pre >= 2 and a[i] >= 2: index = i break pre = a[i] else: print("perfect") exit() print("ambiguous") N = sum(a) R = [0] for i in range(1, n + 1): k = len(R) for j in range(a[i]): R.append(k) L = [0] flag = False for i in range(1, n + 1): k = len(L) m = 0 if i == index: L.append(k - a[i - 1] + 1) m = 1 for j in range(a[i] - m): L.append(k) print(*R) print(*L) ```
instruction
0
14,732
13
29,464
Yes
output
1
14,732
13
29,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` h = int(input()) a = list(map(int,input().split())) ok = True for i in range(h): if a[i]>=2 and a[i+1]>=2: ok = False idx = i+1 if ok: print('perfect') else: print('ambiguous') ans = [] p = 0 for x in a: ans.extend([p]*x) p = len(ans) print(' '.join(map(str,ans))) ans[sum(a[:idx])] -= 1 print(' '.join(map(str,ans))) ```
instruction
0
14,733
13
29,466
Yes
output
1
14,733
13
29,467
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` import sys lines = [] for line in sys.stdin: lines.append(line.rstrip("\r\n\t ")) h = int(lines[0]) ids = lines[1].split(" ") leafs1 = "0" leafs2 = "0" parents = [] last_id = 1 is_perfect = True leafs = int(ids[1]) last_leafs = leafs for j in range(0, leafs): last_id += 1 leafs1 += " 1" leafs2 += " 1" parents.append(last_id) for i in range(3, h + 2): leafs = int(ids[i - 1]) s0 = " " + str(parents[0]) if last_leafs > 1 and leafs > 1: is_perfect = False last_id += 1 s1 = " " + str(parents[1]) parents = [] leafs1 += s0 leafs2 += s1 parents.append(last_id) for j in range(1, leafs): last_id += 1 leafs1 += s0 leafs2 += s0 parents.append(last_id) else: parents = [] for j in range(0, leafs): last_id += 1 leafs1 += s0 leafs2 += s0 parents.append(last_id) last_leafs = leafs if is_perfect: print("perfect") else: print("ambiguous") print(leafs1) print(leafs2) ```
instruction
0
14,734
13
29,468
Yes
output
1
14,734
13
29,469
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` import sys from collections import Counter, deque def lInt(d = None): return map(int, input().split(d)) n, *_ = lInt() a = list(lInt()) a.append(0) j = 0 tot = sum(a) try: for i, va in enumerate(a): if va > 1 and a[i-1] > 1: print("ambiguous") j = i raise except: p = 0 ans = [] for i in range(0, n+1): va = a[i] for u in range(va): ans.append(p) p += va for u in ans: sys.stdout.write(str(u)+" ") print("") p = 0 ans = [] for i in range(0, n+1): va = a[i] if i == j: for u in range(va//2): ans.append(p-1) for u in range(va//2, va): ans.append(p) else: for u in range(va): ans.append(p) p += va for u in ans: sys.stdout.write(str(u)+" ") print("") else: print("perfect") ```
instruction
0
14,735
13
29,470
Yes
output
1
14,735
13
29,471
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n = int(input()) a = list(map(int, input().split())) ans = 0 f = 0 if a[0] >= 2: f += 1 for i in range(1, n + 1): if a[i] >= 2: f += 1 if a[i] >= 2 and a[i - 1] >= 2: ans = 1 if ans == 0: print("perfect") else: s1 = "0" s2 = "0" p = 0 ans = 1 for i in range(1, len(a)): if a[i - 1] == 1: s1 += (" " + str(ans)) * a[i] s2 += (" " + str(ans)) * a[i] else: f -= 1 if p == 0 and f == 1: s1 += (" " + str(ans)) * a[i] s2 += (" " + str(ans - 1)) * 1 + (" " + str(ans)) * (a[i] - 1) p = 1 else: s1 += (" " + str(ans)) * a[i] s2 += (" " + str(ans)) * a[i] ans += a[i] print("ambiguous") print(s1) print(s2) ```
instruction
0
14,736
13
29,472
No
output
1
14,736
13
29,473
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n=int(input()) m=[] p=list(map(int,input().split())) if p.count(1)<len(p)-1: print('ambiguous') x=1 z=0 s=['0'] for i in range(1,n+1): a=x for j in range(p[i]): s.append(str(a)) x+=1 if p[i]>1 and not z: z=len(s)+1 zx=x-1 print(' '.join(s)) s[z]=str(zx) print(' '.join(s)) else: print('perfect') ```
instruction
0
14,737
13
29,474
No
output
1
14,737
13
29,475
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n=int(input()) l=list(map(int,input().split())) f=0 for i in range(n): #print(l[i],l[i+1]) if l[i]>1 and l[i+1]>1: f+=1 break if f==0: print("perfect") else: g='' cnt=0 for i in l: for j in range(i): g+=str(cnt) cnt+=1 print("ambiguous") h='' for i in range(len(g)-1): h+=g[i] h+=str(len(l)) l,l1=list(g),list(h) print(*l) print(*l1) ```
instruction
0
14,738
13
29,476
No
output
1
14,738
13
29,477
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Sasha is taking part in a programming competition. In one of the problems she should check if some rooted trees are isomorphic or not. She has never seen this problem before, but, being an experienced participant, she guessed that she should match trees to some sequences and then compare these sequences instead of trees. Sasha wants to match each tree with a sequence a0, a1, ..., ah, where h is the height of the tree, and ai equals to the number of vertices that are at distance of i edges from root. Unfortunately, this time Sasha's intuition was wrong, and there could be several trees matching the same sequence. To show it, you need to write a program that, given the sequence ai, builds two non-isomorphic rooted trees that match that sequence, or determines that there is only one such tree. Two rooted trees are isomorphic, if you can reenumerate the vertices of the first one in such a way, that the index of the root becomes equal the index of the root of the second tree, and these two trees become equal. The height of a rooted tree is the maximum number of edges on a path from the root to any other vertex. Input The first line contains a single integer h (2 ≀ h ≀ 105) β€” the height of the tree. The second line contains h + 1 integers β€” the sequence a0, a1, ..., ah (1 ≀ ai ≀ 2Β·105). The sum of all ai does not exceed 2Β·105. It is guaranteed that there is at least one tree matching this sequence. Output If there is only one tree matching this sequence, print "perfect". Otherwise print "ambiguous" in the first line. In the second and in the third line print descriptions of two trees in the following format: in one line print <image> integers, the k-th of them should be the parent of vertex k or be equal to zero, if the k-th vertex is the root. These treese should be non-isomorphic and should match the given sequence. Examples Input 2 1 1 1 Output perfect Input 2 1 2 2 Output ambiguous 0 1 1 3 3 0 1 1 3 2 Note The only tree in the first example and the two printed trees from the second example are shown on the picture: <image> Submitted Solution: ``` n=int(input()) l=list(map(int,input().split())) f=0 for i in range(n): #print(l[i],l[i+1]) if l[i]>1 and l[i+1]>1: ind=i f+=1 break if f==0: print("perfect") else: g='' cnt=0 for i in range(len(l)): if i==ind+1: if l[i]==2: for j in range(2): g+=str(cnt) cnt+=1 else: for j in range(l[i]-1): g+=str(cnt) cnt+=1 g+=str(cnt) cnt+=1 else: for j in range(l[i]): g+=str(cnt) cnt+=1 print("ambiguous") h='' h='' cnt1=0 for i in range(len(l)): if i==ind+1: #print(i) if l[i]==2: for j in range(1): h+=str(cnt1) cnt1+=1 h+=str(cnt1) cnt1+=1 else: if l[i]%2!=0: for j in range(l[i]//2): h+=str(cnt1) cnt1+=1 for j in range((l[i]//2)+1): h+=str(cnt1) cnt1+=1 else: for j in range(l[i]//2): h+=str(cnt1) cnt1+=1 for j in range(l[i]//2): h+=str(cnt1) cnt1+=1 #h+=str(cnt1) else: for j in range(l[i]): h+=str(cnt1) cnt1+=1 l,l1=list(g),list(h) print(*l) print(*l1) ```
instruction
0
14,739
13
29,478
No
output
1
14,739
13
29,479
Provide tags and a correct Python 3 solution for this coding contest problem. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ …
instruction
0
15,173
13
30,346
Tags: brute force, data structures, dfs and similar, dp, graphs, implementation, math, number theory Correct Solution: ``` import io, sys input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip() LCM = 2520 n = int(input()) k = list(map(int, input().split())) m, e = [], [] for _ in range(n): m.append(int(input())) e.append(list(map(int, input().split()))) nxt = [] for i in range(n): for j in range(LCM): x = (j + k[i]) % LCM y = e[i][x % m[i]] - 1 nxt.append(y * LCM + x) mark = [-1] * (n * LCM) loop = [None] * (n * LCM) for i in range(n * LCM): if loop[i]: continue start = cur = i rec = [] while True: if mark[cur] != -1: break mark[cur] = i rec.append(cur) cur = nxt[cur] if loop[cur]: for u in rec: loop[u] = loop[cur] else: uniq = set() inloop = 0 for u in rec: loop[u] = uniq if u == cur: inloop = 1 if inloop: uniq.add(u // LCM) out = [] for _ in range(int(input())): x, y = map(int, input().split()) out.append(len(loop[(x - 1) * LCM + y % LCM])) print(*out, sep='\n') ```
output
1
15,173
13
30,347
Provide tags and a correct Python 3 solution for this coding contest problem. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ …
instruction
0
15,174
13
30,348
Tags: brute force, data structures, dfs and similar, dp, graphs, implementation, math, number theory Correct Solution: ``` import io, sys input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip() LCM = 2520 n = int(input()) k = list(map(int, input().split())) m, e = [0] * n, [None] * n for i in range(n): m[i] = int(input()) e[i] = list(map(int, input().split())) nxt = [] for i in range(n): for j in range(LCM): x = (j + k[i]) % LCM y = e[i][x % m[i]] - 1 nxt.append(y * LCM + x) loop = [None] * (n * LCM) for i in range(n * LCM): if loop[i]: continue loop[i] = set() cur, rec = nxt[i], [i] while True: if loop[cur] is not None: break loop[cur] = loop[i] rec.append(cur) cur = nxt[cur] if loop[cur]: for u in rec: loop[u] = loop[cur] else: while rec[-1] != cur: loop[i].add(rec.pop() // LCM) loop[i].add(cur // LCM) out = [] for _ in range(int(input())): x, y = map(int, input().split()) out.append(len(loop[(x - 1) * LCM + y % LCM])) print(*out, sep='\n') ```
output
1
15,174
13
30,349
Provide tags and a correct Python 3 solution for this coding contest problem. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ …
instruction
0
15,175
13
30,350
Tags: brute force, data structures, dfs and similar, dp, graphs, implementation, math, number theory Correct Solution: ``` import sys from sys import stdin def solve(v,c): if d[v][c] != None: return d[v][c] vnum = 0 visits = set() while True: if c*n+v in visits: last = d[v][c] vs = set() for u in visits: if d[u%n][u//n] <= last: vs.add(u%n) nans = len(vs) for u in visits: d[u%n][u//n] = nans return nans elif d[v][c] != None and d[v][c] > 0: nans = d[v][c] for u in visits: d[u%n][u//n] = nans return nans visits.add(c*n+v) d[v][c] = vnum vnum -= 1 c = (c+k[v]) % mod v = lis[v][c % len(lis[v])] n = int(stdin.readline()) mod = 2520 d = [ [None] * mod for i in range(n) ] #print (d) k = list(map(int,stdin.readline().split())) lis = [] for i in range(n): m = int(stdin.readline()) lis.append(list(map(int,stdin.readline().split()))) for j in range(m): lis[i][j] -= 1 q = int(stdin.readline()) ANS = [] for loop in range(q): x,y = map(int,stdin.readline().split()) x -= 1 ANS.append(solve(x,y % mod)) print ("\n".join(map(str,ANS))) ```
output
1
15,175
13
30,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ … Submitted Solution: ``` import io, sys input = lambda f=io.StringIO(sys.stdin.buffer.read().decode()).readline: f().rstrip() LCM = 2520 n = int(input()) k = list(map(int, input().split())) m, e = [0] * n, [None] * n for i in range(n): m[i] = int(input()) e[i] = list(map(int, input().split())) nxt = [] for i in range(n): for j in range(LCM): x = (j + k[i]) % LCM y = e[i][x % m[i]] - 1 nxt.append(y * LCM + x) loop = [None] * (n * LCM) for i in range(n * LCM): if loop[i]: continue loop[i] = set() cur, rec = nxt[i], [i] while True: if loop[cur] is not None: break loop[cur] = loop[i] rec.append(cur) cur = nxt[cur] if loop[cur]: for u in rec: loop[u] = loop[cur] else: while rec[-1] != cur: loop[i].add(rec.pop()) loop[i].add(cur) out = [] for _ in range(int(input())): x, y = map(int, input().split()) out.append(len(loop[(x - 1) * LCM + y % LCM])) print(*out, sep='\n') ```
instruction
0
15,176
13
30,352
No
output
1
15,176
13
30,353
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ … Submitted Solution: ``` class Node: def __init__(self, i, c): self.i = i self.c = c def __eq__(self, node): return self.i == node.i def __hash__(self): return hash(self.i) def __str__(self): return f"{self.i + 1}({self.c})" n = int(input()) ks = list(map(int, input().split())) edges = [] for i in range(n): _ = input() ms = list(map(int, input().split())) e_i = [] for j, e in enumerate(ms): e_i.append(e - 1) edges.append(e_i) q = int(input()) for _ in range(q): v, c = map(int, input().split()) v -= 1 c += ks[v] visited = set() current = Node(v, c) stack = [] k = 1 while True: print(current) visited.add(current) stack.append(current) E = edges[current.i] m = len(E) x = c % m next_v = E[x] c += ks[next_v] current = Node(next_v, c) if next_v == v: k = 1 break elif current in visited: while stack: next_ = stack.pop() if next_.i == current.i: break else: k += 1 break else: v = next_v print(k) ```
instruction
0
15,177
13
30,354
No
output
1
15,177
13
30,355
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ … Submitted Solution: ``` class Node: def __init__(self, i, c): self.i = i self.c = c def __eq__(self, node): return self.i == node.i def __hash__(self): return hash(self.i) def __str__(self): return f"{self.i + 1}({self.c})" n = int(input()) ks = list(map(int, input().split())) edges = [] for i in range(n): _ = input() ms = list(map(int, input().split())) e_i = [] for j, e in enumerate(ms): e_i.append(e - 1) edges.append(e_i) q = int(input()) for _ in range(q): v, c = map(int, input().split()) v -= 1 c += ks[v] visited = set() current = Node(v, c) stack = [] k = 1 while True: visited.add(current) stack.append(current) E = edges[current.i] m = len(E) x = c % m next_v = E[x] c += ks[next_v] current = Node(next_v, c) if next_v == v: k = 1 break elif current in visited: while stack: next_ = stack.pop() if next_.i == current.i: break else: k += 1 break else: v = next_v print(k) ```
instruction
0
15,178
13
30,356
No
output
1
15,178
13
30,357
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Gildong is experimenting with an interesting machine Graph Traveler. In Graph Traveler, there is a directed graph consisting of n vertices numbered from 1 to n. The i-th vertex has m_i outgoing edges that are labeled as e_i[0], e_i[1], …, e_i[m_i-1], each representing the destination vertex of the edge. The graph can have multiple edges and self-loops. The i-th vertex also has an integer k_i written on itself. A travel on this graph works as follows. 1. Gildong chooses a vertex to start from, and an integer to start with. Set the variable c to this integer. 2. After arriving at the vertex i, or when Gildong begins the travel at some vertex i, add k_i to c. 3. The next vertex is e_i[x] where x is an integer 0 ≀ x ≀ m_i-1 satisfying x ≑ c \pmod {m_i}. Go to the next vertex and go back to step 2. It's obvious that a travel never ends, since the 2nd and the 3rd step will be repeated endlessly. For example, assume that Gildong starts at vertex 1 with c = 5, and m_1 = 2, e_1[0] = 1, e_1[1] = 2, k_1 = -3. Right after he starts at vertex 1, c becomes 2. Since the only integer x (0 ≀ x ≀ 1) where x ≑ c \pmod {m_i} is 0, Gildong goes to vertex e_1[0] = 1. After arriving at vertex 1 again, c becomes -1. The only integer x satisfying the conditions is 1, so he goes to vertex e_1[1] = 2, and so on. Since Gildong is quite inquisitive, he's going to ask you q queries. He wants to know how many distinct vertices will be visited infinitely many times, if he starts the travel from a certain vertex with a certain value of c. Note that you should not count the vertices that will be visited only finite times. Input The first line of the input contains an integer n (1 ≀ n ≀ 1000), the number of vertices in the graph. The second line contains n integers. The i-th integer is k_i (-10^9 ≀ k_i ≀ 10^9), the integer written on the i-th vertex. Next 2 β‹… n lines describe the edges of each vertex. The (2 β‹… i + 1)-st line contains an integer m_i (1 ≀ m_i ≀ 10), the number of outgoing edges of the i-th vertex. The (2 β‹… i + 2)-nd line contains m_i integers e_i[0], e_i[1], …, e_i[m_i-1], each having an integer value between 1 and n, inclusive. Next line contains an integer q (1 ≀ q ≀ 10^5), the number of queries Gildong wants to ask. Next q lines contains two integers x and y (1 ≀ x ≀ n, -10^9 ≀ y ≀ 10^9) each, which mean that the start vertex is x and the starting value of c is y. Output For each query, print the number of distinct vertices that will be visited infinitely many times, if Gildong starts at vertex x with starting integer y. Examples Input 4 0 0 0 0 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 2 1 3 2 Input 4 4 -5 -3 -1 2 2 3 1 2 3 2 4 1 4 3 1 2 1 6 1 0 2 0 3 -1 4 -2 1 1 1 5 Output 1 1 1 3 1 1 Note The first example can be shown like the following image: <image> Three integers are marked on i-th vertex: i, k_i, and m_i respectively. The outgoing edges are labeled with an integer representing the edge number of i-th vertex. The travel for each query works as follows. It is described as a sequence of phrases, each in the format "vertex (c after k_i added)". * 1(0) β†’ 2(0) β†’ 2(0) β†’ … * 2(0) β†’ 2(0) β†’ … * 3(-1) β†’ 1(-1) β†’ 3(-1) β†’ … * 4(-2) β†’ 2(-2) β†’ 2(-2) β†’ … * 1(1) β†’ 3(1) β†’ 4(1) β†’ 1(1) β†’ … * 1(5) β†’ 3(5) β†’ 1(5) β†’ … The second example is same as the first example, except that the vertices have non-zero values. Therefore the answers to the queries also differ from the first example. <image> The queries for the second example works as follows: * 1(4) β†’ 2(-1) β†’ 2(-6) β†’ … * 2(-5) β†’ 2(-10) β†’ … * 3(-4) β†’ 1(0) β†’ 2(-5) β†’ 2(-10) β†’ … * 4(-3) β†’ 1(1) β†’ 3(-2) β†’ 4(-3) β†’ … * 1(5) β†’ 3(2) β†’ 1(6) β†’ 2(1) β†’ 2(-4) β†’ … * 1(9) β†’ 3(6) β†’ 2(1) β†’ 2(-4) β†’ … Submitted Solution: ``` import sys sys.setrecursionlimit(10**7) class Scc: def __init__(self, Edge): self.Edge = Edge def decomposition(self): self.N = len(self.Edge) self.Edgeinv = [[] for _ in range(self.N)] for i in range(self.N): for e in self.Edge[i]: self.Edgeinv[e].append(i) self.order = [] self.used = set() for i in range(self.N): if i not in self.used: self.dfs1(i) self.res = [None]*self.N self.cnt = -1 self.used = set() for v in self.order[::-1]: if v not in self.used: self.cnt += 1 self.dfs2(v) n = self.cnt + 1 components = [[] for _ in range(n)] for i in range(self.N): components[self.res[i]].append(i) cEdge = [[] for _ in range(n)] cset = set() for i in range(self.N): for e in self.Edge[i]: if self.res[i] != self.res[e] and self.res[i] + self.N*self.res[e] not in cset: cset.add(self.res[i] + self.N*self.res[e]) cEdge[self.res[i]].append(self.res[e]) return self.res, components, cEdge def dfs1(self, v): self.used.add(v) for vf in self.Edge[v]: if vf not in self.used: self.used.add(vf) self.dfs1(vf) self.order.append(v) def dfs2(self, v): self.used.add(v) self.res[v] = self.cnt stack = [v] while stack: vn = stack.pop() for vf in self.Edgeinv[vn]: if vf not in self.used: self.used.add(vf) self.res[vf] = self.cnt stack.append(vf) N = int(input()) K = tuple(map(int, sys.stdin.readline().split())) rEdge = [None]*N M = [None]*N for i in range(N): M[i] = int(sys.stdin.readline()) rEdge[i] = tuple(map(lambda x: int(x) - 1, sys.stdin.readline().split())) LT = 2520 LN = LT*N tEdge = [None]*(LN) for i in range(LN): x, c = divmod(i, LT) nx = rEdge[x][c%M[x]] tEdge[i] = [nx*LT + (c+K[nx])%LT] G = Scc(tEdge) Res, Compo, cEdge = G.decomposition() CN = len(cEdge) Ans = [len(set(c//LT for c in Compo[i])) for i in range(CN)] dp = [0]*CN for i in range(CN-1, -1, -1): if not cEdge[i]: dp[i] = i else: dp[i] = dp[cEdge[i][0]] Q = int(sys.stdin.readline()) for _ in range(Q): x, c = tuple(map(int, sys.stdin.readline().split())) x -= 1 sys.stdout.write('{}\n'.format(Ans[Res[x*LT + (c+K[x])%LT]])) ```
instruction
0
15,179
13
30,358
No
output
1
15,179
13
30,359
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i. Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that: * all b_i are positive; * the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists. Input The first line contains two integers n and m (2 ≀ n ≀ 18; 0 ≀ m ≀ (n(n - 1))/(2)). Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 ≀ x_i, y_i ≀ n, 1 ≀ w_i ≀ 10^5, x_i β‰  y_i) β€” the description of the i-th arc. It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices. Output Print n integers a_1, a_2, ..., a_n (0 ≀ a_v ≀ 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 ≀ a_v ≀ 10^9. Examples Input 3 2 2 1 4 1 3 2 Output 1 2 0 Input 5 4 1 2 1 2 3 1 1 3 6 4 5 8 Output 43 42 41 1337 1336 Input 5 5 1 2 1 2 3 1 3 4 1 1 5 1 5 4 10 Output 4 3 2 1 2
instruction
0
15,268
13
30,536
Tags: bitmasks, dfs and similar, dp, flows, graphs, math Correct Solution: ``` from heapq import heappush, heappop class MinCostFlow: INF = 10**18 def __init__(self, N): self.N = N self.G = [[] for i in range(N)] def add_edge(self, fr, to, cap, cost): forward = [to, cap, cost, None] backward = forward[3] = [fr, 0, -cost, forward] self.G[fr].append(forward) self.G[to].append(backward) def flow(self, s, t, f): N = self.N; G = self.G INF = MinCostFlow.INF res = 0 H = [0]*N prv_v = [0]*N prv_e = [None]*N d0 = [INF]*N dist = [INF]*N while f: dist[:] = d0 dist[s] = 0 que = [(0, s)] while que: c, v = heappop(que) if dist[v] < c: continue r0 = dist[v] + H[v] for e in G[v]: w, cap, cost, _ = e if cap > 0 and r0 + cost - H[w] < dist[w]: dist[w] = r = r0 + cost - H[w] prv_v[w] = v; prv_e[w] = e heappush(que, (r, w)) if dist[t] == INF: return None for i in range(N): H[i] += dist[i] d = f; v = t while v != s: d = min(d, prv_e[v][1]) v = prv_v[v] f -= d res += d * H[t] v = t while v != s: e = prv_e[v] e[1] -= d e[3][1] += d v = prv_v[v] return res class UnionFindVerSize(): def __init__(self, N): self._parent = [n for n in range(0, N)] self._size = [1] * N self.group = N def find_root(self, x): if self._parent[x] == x: return x self._parent[x] = self.find_root(self._parent[x]) stack = [x] while self._parent[stack[-1]]!=stack[-1]: stack.append(self._parent[stack[-1]]) for v in stack: self._parent[v] = stack[-1] return self._parent[x] def unite(self, x, y): gx = self.find_root(x) gy = self.find_root(y) if gx == gy: return self.group -= 1 if self._size[gx] < self._size[gy]: self._parent[gx] = gy self._size[gy] += self._size[gx] else: self._parent[gy] = gx self._size[gx] += self._size[gy] def get_size(self, x): return self._size[self.find_root(x)] def is_same_group(self, x, y): return self.find_root(x) == self.find_root(y) n,m = map(int,input().split()) G = MinCostFlow(n+2) coef = [0 for i in range(n)] edge = [] for _ in range(m): x,y,b = map(int,input().split()) G.add_edge(y,x,10**18,-1) coef[x-1] += b coef[y-1] -= b edge.append((x,y)) s = 0 for i in range(n): if coef[i]<0: G.add_edge(0,i+1,-coef[i],0) s -= coef[i] elif coef[i]>0: G.add_edge(i+1,n+1,coef[i],0) #G.add_edge(0,n+1,10**18,0) f = G.flow(0,n+1,s) #print(-f) Edge = [[] for i in range(n)] use = [False]*m uf = UnionFindVerSize(n) for i in range(m): u,v = edge[i] for e in G.G[u]: to = e[0] if to==v and e[1]: Edge[v-1].append((u-1,1)) Edge[u-1].append((v-1,-1)) use[i] = True uf.unite(u-1,v-1) edge = [(edge[i][0],edge[i][1]) for i in range(m) if not use[i]] for u,v in edge: if not uf.is_same_group(u-1,v-1): Edge[v-1].append((u-1,1)) Edge[u-1].append((v-1,-1)) uf.unite(u-1,v-1) used_1 = [False]*n used_2 = [False]*n lazy = [0 for i in range(n)] a = [0 for i in range(n)] def dfs(v,pv): lazy[v] = min(lazy[v],a[v]) for nv,c in Edge[v]: if not used_1[nv]: used_1[nv] = True a[nv] = a[v] + c dfs(nv,v) lazy[v] = min(lazy[v],lazy[nv]) def add(v,pv,ff): a[v] += ff for nv,c in Edge[v]: if not used_2[nv]: used_2[nv] = True add(nv,v,ff) for i in range(n): if not used_1[i]: used_1[i] = True dfs(i,-1) used_2[i] = True add(i,-1,-lazy[i]+1) #print(used_1) #print(lazy) print(*a) ```
output
1
15,268
13
30,537
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i. Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that: * all b_i are positive; * the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists. Input The first line contains two integers n and m (2 ≀ n ≀ 18; 0 ≀ m ≀ (n(n - 1))/(2)). Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 ≀ x_i, y_i ≀ n, 1 ≀ w_i ≀ 10^5, x_i β‰  y_i) β€” the description of the i-th arc. It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices. Output Print n integers a_1, a_2, ..., a_n (0 ≀ a_v ≀ 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 ≀ a_v ≀ 10^9. Examples Input 3 2 2 1 4 1 3 2 Output 1 2 0 Input 5 4 1 2 1 2 3 1 1 3 6 4 5 8 Output 43 42 41 1337 1336 Input 5 5 1 2 1 2 3 1 3 4 1 1 5 1 5 4 10 Output 4 3 2 1 2 Submitted Solution: ``` n, m = map(int, input().split()) adj = [[] for i in range(n)] radj = [[] for i in range(n)] out = [0] * n inc = [0] * n diff = [0] * n for _ in range(m): u, v, w = map(int, input().split()) u-=1;v-=1 adj[u].append((v,w)) out[u] += v diff[u] += w diff[v] -= w inc[v] += 1 radj[v].append((u,w)) found = [0] * n topo = [] stack = [i for i in range(n) if inc[i] == 0] while stack: nex = stack.pop() topo.append(nex) for v, _ in adj[nex]: found[v] += 1 if inc[v] == found[v]: stack.append(v) best = [-1] * n bestV = 10 ** 9 out = [n+1] * n for v in topo: smol = n + 4 for u, _ in radj[v]: smol = min(out[u], smol) out[v] = smol - 1 import itertools things = [[0] if inc[topo[i]] == 0 else (0,1) for i in range(n)] for tup in itertools.product(*things): copy = out[::] for v in topo[::-1]: tol = 0 for u, _ in adj[v]: tol = max(copy[u], tol) copy[v] = tol + 1 curr = 0 for i in range(n): curr += copy[i] * diff[i] if curr < bestV: bestV = curr best = copy print(' '.join(map(str,best))) ```
instruction
0
15,269
13
30,538
No
output
1
15,269
13
30,539
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a directed acyclic graph (a directed graph that does not contain cycles) of n vertices and m arcs. The i-th arc leads from the vertex x_i to the vertex y_i and has the weight w_i. Your task is to select an integer a_v for each vertex v, and then write a number b_i on each arcs i such that b_i = a_{x_i} - a_{y_i}. You must select the numbers so that: * all b_i are positive; * the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. It can be shown that for any directed acyclic graph with non-negative w_i, such a way to choose numbers exists. Input The first line contains two integers n and m (2 ≀ n ≀ 18; 0 ≀ m ≀ (n(n - 1))/(2)). Then m lines follow, the i-th of them contains three integers x_i, y_i and w_i (1 ≀ x_i, y_i ≀ n, 1 ≀ w_i ≀ 10^5, x_i β‰  y_i) β€” the description of the i-th arc. It is guaranteed that the lines describe m arcs of a directed acyclic graph without multiple arcs between the same pair of vertices. Output Print n integers a_1, a_2, ..., a_n (0 ≀ a_v ≀ 10^9), which must be written on the vertices so that all b_i are positive, and the value of the expression βˆ‘ _{i = 1}^{m} w_i b_i is the lowest possible. If there are several answers, print any of them. It can be shown that the answer always exists, and at least one of the optimal answers satisfies the constraints 0 ≀ a_v ≀ 10^9. Examples Input 3 2 2 1 4 1 3 2 Output 1 2 0 Input 5 4 1 2 1 2 3 1 1 3 6 4 5 8 Output 43 42 41 1337 1336 Input 5 5 1 2 1 2 3 1 3 4 1 1 5 1 5 4 10 Output 4 3 2 1 2 Submitted Solution: ``` a,b=map(int,input().split());c=0 while a<=b:a*=3;b*=2;c+=1 print(c) ```
instruction
0
15,270
13
30,540
No
output
1
15,270
13
30,541