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. We have a graph with N vertices and M edges, and there are two people on the graph: Takahashi and Aoki. The i-th edge connects Vertex U_i and Vertex V_i. The time it takes to traverse this edge is D_i minutes, regardless of direction and who traverses the edge (Takahashi or Aoki). Takahashi departs Vertex S and Aoki departs Vertex T at the same time. Takahashi travels to Vertex T and Aoki travels to Vertex S, both in the shortest time possible. Find the number of the pairs of ways for Takahashi and Aoki to choose their shortest paths such that they never meet (at a vertex or on an edge) during the travel, modulo 10^9 + 7. Constraints * 1 \leq N \leq 100 000 * 1 \leq M \leq 200 000 * 1 \leq S, T \leq N * S \neq T * 1 \leq U_i, V_i \leq N (1 \leq i \leq M) * 1 \leq D_i \leq 10^9 (1 \leq i \leq M) * If i \neq j, then (U_i, V_i) \neq (U_j, V_j) and (U_i, V_i) \neq (V_j, U_j). * U_i \neq V_i (1 \leq i \leq M) * D_i are integers. * The given graph is connected. Input Input is given from Standard Input in the following format: N M S T U_1 V_1 D_1 U_2 V_2 D_2 : U_M V_M D_M Output Print the answer. Examples Input 4 4 1 3 1 2 1 2 3 1 3 4 1 4 1 1 Output 2 Input 3 3 1 3 1 2 1 2 3 1 3 1 2 Output 2 Input 8 13 4 2 7 3 9 6 2 3 1 6 4 7 6 9 3 8 9 1 2 2 2 8 12 8 6 9 2 5 5 4 2 18 5 3 7 5 1 515371567 4 8 6 Output 6 Submitted Solution: ``` from heapq import heappush, heappop import sys #input = sys.stdin.readline INF = 10**18 mod = 10**9+7 def dijkstra(start, n, graph): route_cnt = [start] * n route_cnt[start] = 1 que = [(0, start)] dist = [INF] * n dist[start] = 0 while que: min_dist, u = heappop(que) if min_dist > dist[u]: continue for c, v in graph[u]: if dist[u] + c < dist[v]: dist[v] = dist[u] + c route_cnt[v] = route_cnt[u] heappush(que, (dist[u] + c , v)) elif dist[u] + c == dist[v]: route_cnt[v] = (route_cnt[v] + route_cnt[u]) % mod return route_cnt, dist N, M = map(int, input().split()) S, T = map(int, input().split()) G = [[] for _ in range(N)] edges = [] for _ in range(M): u, v, d = map(int, input().split()) G[u-1].append((d, v-1)) G[v-1].append((d, u-1)) edges.append((v-1, u-1, d)) num_s, dist_s = dijkstra(S-1, N, G) num_t, dist_t = dijkstra(T-1, N, G) ans = num_s[T-1]**2%mod l = dist_s[T-1] for u, v, d in edges: if dist_s[v]<dist_s[u]: u, v = v, u if dist_s[u]*2<l<dist_s[v]*2 and dist_s[u]+dist_t[v]+d == l: ans-=(num_s[u]*num_t[v])**2 ans%=mod for v in range(N): if dist_s[v] == dist_t[v] == l/2: ans-=(num_t[v]*num_s[v])**2 ans%=mod print(ans%mod) ```
instruction
0
65,506
13
131,012
No
output
1
65,506
13
131,013
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree.
instruction
0
65,631
13
131,262
Tags: binary search, data structures, dp, greedy, trees Correct Solution: ``` from collections import defaultdict def rec(n, l, s): # dp[i] is a doctionary, where key is the chain length # and value is the weight at node i dp = [{} for _ in range(n)] ans = 0 for cur in range(n - 1, -1, -1): child_of_cur = children.get(cur, None) if not child_of_cur: dp[cur][1] = weight[cur] continue ans += len(child_of_cur) - 1 cur_weight = weight[cur] for ch in child_of_cur: for ln, child_weight in dp[ch].items(): if ln == l: continue agg_weight = cur_weight + child_weight if agg_weight > s: continue if ln + 1 not in dp[cur]: dp[cur][ln + 1] = agg_weight dp[cur][ln + 1] = min(dp[cur][ln + 1], agg_weight) if not dp[cur]: ans += 1 dp[cur][1] = weight[cur] return ans + 1 weight = [] children = defaultdict(set) n, l, s = map(int, input().split()) for w in map(int, input().split()): if w > s: print(-1) exit() weight.append(w) if n == 1: print(-1 if weight[0] > s else 1) exit() for i, v in enumerate(map(int, input().split())): children[v -1].add(i + 1) print(rec(n,l,s)) ```
output
1
65,631
13
131,263
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree.
instruction
0
65,632
13
131,264
Tags: binary search, data structures, dp, greedy, trees Correct Solution: ``` n , l , s = map(int , input().split()) i , ans = n , 0 w , par , vis = [0] , [0 , 0] , [0] * (n + 10) for u in map(int , input().split()): if(u > s): print(-1) , exit(0) w.append(u) if(n > 1): for u in map(int , input().split()): par.append(u) while(i > 0): if vis[i] == 0: c , p , x = i , l , s ans = ans + 1 while(x >= w[c] and p * c > 0): vis[c] = 1 p = p - 1 x = x - w[c] c = par[c] i = i - 1 print(ans) ```
output
1
65,632
13
131,265
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree.
instruction
0
65,633
13
131,266
Tags: binary search, data structures, dp, greedy, trees Correct Solution: ``` def solve(n, l, s, www, children): ans = 0 dp = [{} for _ in range(n)] for v in range(n - 1, -1, -1): cv = children[v] if not cv: dp[v][1] = www[v] continue ans += len(cv) - 1 wv = www[v] if wv > s: return -1 dv = dp[v] for c in cv: for lc, wc in dp[c].items(): if lc == l: continue wt = wc + wv if wt > s: continue if lc + 1 not in dv: dv[lc + 1] = wt else: dv[lc + 1] = min(dv[lc + 1], wt) if not dv: ans += 1 dv[1] = wv return ans + 1 n, l, s = list(map(int, input().split())) www = list(map(int, input().split())) if n == 1: print(-1 if www[0] > s else 1) exit() children = [set() for _ in range(n)] for i, p in enumerate(map(int, input().split())): children[p - 1].add(i + 1) print(solve(n, l, s, www, children)) ```
output
1
65,633
13
131,267
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree.
instruction
0
65,634
13
131,268
Tags: binary search, data structures, dp, greedy, trees Correct Solution: ``` from collections import defaultdict import sys def rec(n, l, s): # dp[i] is a doctionary, where key is the chain length # and value is the weight at node i dp = [{} for _ in range(n)] ans = 0 for cur in range(n - 1, -1, -1): child_of_cur = children.get(cur, None) if not child_of_cur: dp[cur][1] = weight[cur] continue ans += len(child_of_cur) - 1 cur_weight = weight[cur] for ch in child_of_cur: for ln, child_weight in dp[ch].items(): if ln == l: continue agg_weight = cur_weight + child_weight if agg_weight > s: continue if ln + 1 not in dp[cur]: dp[cur][ln + 1] = agg_weight dp[cur][ln + 1] = min(dp[cur][ln + 1], agg_weight) if not dp[cur]: ans += 1 dp[cur][1] = weight[cur] return ans + 1 weight = [] children = defaultdict(set) n, l, s = map(int, sys.stdin.readline().split()) for w in map(int, sys.stdin.readline().split()): if w > s: print(-1) exit() weight.append(w) if n == 1: print(-1 if weight[0] > s else 1) exit() for i, v in enumerate(map(int, sys.stdin.readline().split())): children[v -1].add(i + 1) print(rec(n,l,s)) ```
output
1
65,634
13
131,269
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree. Submitted Solution: ``` n , l , s = map(int , input().split()) i , ans = 0 , n w , par , vis = [0] , [0 , 0] , [0] * (n + 10) for u in map(int , input().split()): if(u > s): print(-1) , exit(0) w.append(u) if(n > 1): for u in map(int , input().split()): par.append(u) while(i > 0): if vis[i] == 0: c , p , x = i , l , s ans = ans + 1 while(x > w[c] - 1 and p * c > 0): vis[c] = 1 p = p - 1 x = x - w[c] c = par[c] i = i - 1 print(ans) ```
instruction
0
65,635
13
131,270
No
output
1
65,635
13
131,271
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a rooted tree on n vertices, its root is the vertex number 1. The i-th vertex contains a number w_i. Split it into the minimum possible number of vertical paths in such a way that each path contains no more than L vertices and the sum of integers w_i on each path does not exceed S. Each vertex should belong to exactly one path. A vertical path is a sequence of vertices v_1, v_2, …, v_k where v_i (i ≥ 2) is the parent of v_{i - 1}. Input The first line contains three integers n, L, S (1 ≤ n ≤ 10^5, 1 ≤ L ≤ 10^5, 1 ≤ S ≤ 10^{18}) — the number of vertices, the maximum number of vertices in one path and the maximum sum in one path. The second line contains n integers w_1, w_2, …, w_n (1 ≤ w_i ≤ 10^9) — the numbers in the vertices of the tree. The third line contains n - 1 integers p_2, …, p_n (1 ≤ p_i < i), where p_i is the parent of the i-th vertex in the tree. Output Output one number — the minimum number of vertical paths. If it is impossible to split the tree, output -1. Examples Input 3 1 3 1 2 3 1 1 Output 3 Input 3 3 6 1 2 3 1 1 Output 2 Input 1 1 10000 10001 Output -1 Note In the first sample the tree is split into \{1\},\ \{2\},\ \{3\}. In the second sample the tree is split into \{1,\ 2\},\ \{3\} or \{1,\ 3\},\ \{2\}. In the third sample it is impossible to split the tree. Submitted Solution: ``` from collections import defaultdict def rec(n, l, s): # dp[i] is a doctionary, where key is the chain length # and value is the weight at node i dp = [{} for _ in range(n)] ans = 0 for cur in range(n-1, -1, -1): child_of_cur = children.get(cur) if not child_of_cur: dp[cur][1] = weight[cur] continue ans += len(child_of_cur) - 1 cur_weight = weight[cur] for ch in child_of_cur: for ln, child_weight in dp[ch].items(): if ln == l: continue agg_weight = cur_weight + child_weight if agg_weight > s: continue if ln + 1 not in dp[cur]: dp[cur][ln + 1] = agg_weight dp[cur][ln + 1] = min(dp[cur][ln + 1], agg_weight) if not dp[cur]: ans += 1 dp[i][1] = weight[i] return ans + 1 n, l, s = map(int, input().split()) weight = [] children = defaultdict(set) for w in map(int, input().split()): if w > s: print(-1) exit() weight.append(w) for i, v in enumerate(map(int, input().split())): children[v -1].add(i + 1) print(rec(n,l,s)) ```
instruction
0
65,636
13
131,272
No
output
1
65,636
13
131,273
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider an undirected graph G with n vertices. There is a value a_i in each vertex. Two vertices i and j are connected with an edge if and only if gcd(a_i, a_j) > 1, where gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y. Consider a set of vertices. Let's call a vertex in this set fair if it is connected with an edge with all other vertices in this set. You need to find a set of k vertices (where k is a given integer, 2 ⋅ k ≤ n) where all vertices are fair or all vertices are not fair. One can show that such a set always exists. Input The first line contains integers n and k (6 ≤ 2 ⋅ k ≤ n ≤ 10^5) — the number of vertices and parameter k. The second line contains n integers a_1, a_2, …, a_n (2 ≤ a_i ≤ 10^7) — the values in the vertices. Output Print exactly k distinct integers — the indices of the vertices in the chosen set in any order. Examples Input 6 3 6 15 10 8 14 12 Output 2 4 5 Input 8 4 11 15 10 6 21 15 10 6 Output 5 7 1 2 Input 10 5 3003 17017 3230 49742 546 41990 17765 570 21945 36465 Output 1 2 4 5 6 Note In the first test case, set \{2, 4, 5\} is an example of set where no vertices are fair. The vertex 2 does not share an edge with vertex 4 since gcd(15, 8) = 1. The vertex 4 does not share an edge with vertex 2. The vertex 5 does not share an edge with vertex 2. In the second test case, set \{8, 5, 6, 4\} is an example of a set where all vertices are fair. Submitted Solution: ``` def gcd(a, b): if a == 0 : return b return gcd(b%a, a) n,k=input().split(" ") n=int(n) k=int(k) arr=input().split(" ") arr=[int(i) for i in arr] matrix=[[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if i!=j and gcd(arr[i],arr[j])>1: matrix[i][j]=1 al=[] none=[] for i in range(n): if matrix[i].count(1)==n-1: al.append(i+1) else: none.append(i+1) if len(al)>=k: for i in range(k): print(al[i],end=" ") print() else: if len(none)>=k: for i in range(k): print(none[i],end=" ") print() ```
instruction
0
65,674
13
131,348
No
output
1
65,674
13
131,349
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider an undirected graph G with n vertices. There is a value a_i in each vertex. Two vertices i and j are connected with an edge if and only if gcd(a_i, a_j) > 1, where gcd(x, y) denotes the [greatest common divisor (GCD)](https://en.wikipedia.org/wiki/Greatest_common_divisor) of integers x and y. Consider a set of vertices. Let's call a vertex in this set fair if it is connected with an edge with all other vertices in this set. You need to find a set of k vertices (where k is a given integer, 2 ⋅ k ≤ n) where all vertices are fair or all vertices are not fair. One can show that such a set always exists. Input The first line contains integers n and k (6 ≤ 2 ⋅ k ≤ n ≤ 10^5) — the number of vertices and parameter k. The second line contains n integers a_1, a_2, …, a_n (2 ≤ a_i ≤ 10^7) — the values in the vertices. Output Print exactly k distinct integers — the indices of the vertices in the chosen set in any order. Examples Input 6 3 6 15 10 8 14 12 Output 2 4 5 Input 8 4 11 15 10 6 21 15 10 6 Output 5 7 1 2 Input 10 5 3003 17017 3230 49742 546 41990 17765 570 21945 36465 Output 1 2 4 5 6 Note In the first test case, set \{2, 4, 5\} is an example of set where no vertices are fair. The vertex 2 does not share an edge with vertex 4 since gcd(15, 8) = 1. The vertex 4 does not share an edge with vertex 2. The vertex 5 does not share an edge with vertex 2. In the second test case, set \{8, 5, 6, 4\} is an example of a set where all vertices are fair. Submitted Solution: ``` def gcd(a, b): if a == 0 : return b return gcd(b%a, a) n,k=input().split(" ") n=int(n) k=int(k) arr=input().split(" ") arr=[int(i) for i in arr] matrix=[[0 for i in range(n)] for j in range(n)] for i in range(n): for j in range(n): if i!=j and gcd(arr[i],arr[j])>1: matrix[i][j]=1 al=[] none=[] #print(matrix) for i in range(n): if matrix[i].count(1)==n-1: al.append(i+1) else: none.append(i+1) #print(al,none) if len(al)>=k: for i in range(k): print(al[i],end=" ") print() else: ar=[none[0]] ln=len(none) for i in range(1,ln): l=0 for j in ar: if matrix[j-1][none[i]-1]==1: l=l+1 if l<ln: ar.append(none[i]) if len(ar)==k: break for i in ar: print(i,end=" ") print() ```
instruction
0
65,675
13
131,350
No
output
1
65,675
13
131,351
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a tree. We will consider simple paths on it. Let's denote path between vertices a and b as (a, b). Let d-neighborhood of a path be a set of vertices of the tree located at a distance ≤ d from at least one vertex of the path (for example, 0-neighborhood of a path is a path itself). Let P be a multiset of the tree paths. Initially, it is empty. You are asked to maintain the following queries: * 1 u v — add path (u, v) into P (1 ≤ u, v ≤ n). * 2 u v — delete path (u, v) from P (1 ≤ u, v ≤ n). Notice that (u, v) equals to (v, u). For example, if P = \{(1, 2), (1, 2)\}, than after query 2 2 1, P = \{(1, 2)\}. * 3 d — if intersection of all d-neighborhoods of paths from P is not empty output "Yes", otherwise output "No" (0 ≤ d ≤ n - 1). Input The first line contains two integers n and q — the number of vertices in the tree and the number of queries, accordingly (1 ≤ n ≤ 2 ⋅ 10^5, 2 ≤ q ≤ 2 ⋅ 10^5). Each of the following n - 1 lines contains two integers x_i and y_i — indices of vertices connected by i-th edge (1 ≤ x_i, y_i ≤ n). The following q lines contain queries in the format described in the statement. It's guaranteed that: * for a query 2 u v, path (u, v) (or (v, u)) is present in P, * for a query 3 d, P ≠ ∅, * there is at least one query of the third type. Output For each query of the third type output answer on a new line. Examples Input 1 4 1 1 1 1 1 1 2 1 1 3 0 Output Yes Input 5 3 1 2 1 3 3 4 4 5 1 1 2 1 5 5 3 1 Output No Input 10 6 1 2 2 3 3 4 4 7 7 10 2 5 5 6 6 8 8 9 1 9 9 1 9 8 1 8 5 3 0 3 1 3 2 Output No Yes Yes Submitted Solution: ``` x,y=map(int,input().split()) ar=list(map(int, input('').split())) ct= (len(ar)-1)*10 + sum(ar) if(ct>y): print(-1) else: a=int(((len(ar)-1)*10)/5) b=int((y-ct)/5) print(a+b) ```
instruction
0
65,802
13
131,604
No
output
1
65,802
13
131,605
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,835
13
131,670
Tags: dp, math, matrices Correct Solution: ``` from sys import stdin from collections import deque mod = 10**9 + 7 import sys sys.setrecursionlimit(10**5) from queue import PriorityQueue # def rl(): # return [int(w) for w in stdin.readline().split()] from bisect import bisect_right from bisect import bisect_left from collections import defaultdict from math import sqrt,factorial,gcd,log2,inf,ceil # map(int,input().split()) # # l = list(map(int,input().split())) # from itertools import permutations import heapq # input = lambda: sys.stdin.readline().rstrip() input = lambda : sys.stdin.readline().rstrip() from sys import stdin, stdout from heapq import heapify, heappush, heappop n = int(input()) d = 1 abc = 0 for i in range(1,n+1): d,abc = (3*abc)%mod,(d+2*abc)%mod print(d) ```
output
1
65,835
13
131,671
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,836
13
131,672
Tags: dp, math, matrices Correct Solution: ``` import sys input=sys.stdin.readline m=10**9+7 n=int(input()) a=b=c=s=1 d=t=0 '''dp[i][j] ye bata raha h ki (i remaining turns me j(A,B,C,D) pr kitne tareeko se pohoch skte h) wo humesha peeche steps pr hi depend krega''' '''matrix nhi bn skti h sirf purane states ka hi use h to just by using temp variables we maintain dp''' for i in range(2,n+1): a=b=c=(2*s+t)%m d=3*s%m s=a;t=d print(d) ```
output
1
65,836
13
131,673
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,837
13
131,674
Tags: dp, math, matrices Correct Solution: ``` import sys input = sys.stdin.readline mod = 10**9+7 ''' mod = 10**9+7 def abhi(y,n): if n==0: if y==4: return 1 else: return 0 elif dp[n][y]!=-1: return dp[n][y] else: u='1243' a=0 for j in u: if j!=str(y): a= (a+abhi(int(j),n-1))%mod dp[n][y] = a%mod return dp[n][y] ''' n = int(input()) abc , d= 0,1 for i in range(1,n+1): abc,d= (abc*2+d)%mod,(abc*3)%mod print(d) ''' dp=[ [-1 for i in range(5)] for j in range(n+1)] print(abhi(4,n)%mod) ''' ```
output
1
65,837
13
131,675
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,838
13
131,676
Tags: dp, math, matrices Correct Solution: ``` def main(): fpp = 0 fp = 0 f = 3 n = int(input()) if n == 1: print(0) return for i in range(3, n + 1): fpp = fp fp = f f = (2 * fp + 3 * fpp) % 1000000007 print(f) return if __name__ == "__main__": main() ```
output
1
65,838
13
131,677
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,839
13
131,678
Tags: dp, math, matrices Correct Solution: ``` def solve(n, mod, dp): current = dp[0] for i in range(1, n + 1): current = (3 * current) + (2 * dp[1]) dp = (dp[1] % mod, current % mod) current = dp[0] return dp[0] n = int(input()) mod = 1000000007 dp = (1, 0) print(solve(n, mod, dp)) ```
output
1
65,839
13
131,679
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,840
13
131,680
Tags: dp, math, matrices Correct Solution: ``` n=int(input()) # def mod1(a,mod): # return a%mod # def mult(a,b,mod): # return mod1((mod1(a,mod)*mod1(b,mod)),mod) # def sumd(a,b,mod): # return mod1((mod1(a,mod)+mod1(b,mod)),mod) # def main(n): # prev123 = 0 # prev4 = 1 # for i in range(1,n+1): # prevx = mod1(prev123,1000000007) # prev123 = sumd(mult(prev123,2,1000000007),prev4,1000000007) # prev4 = mult(prevx,3,1000000007) # print(prev4%1000000007) prev123 = 0 prev4 = 1 for i in range(1,n+1): prevx = prev123%1000000007 prev123 = ((prev123*2)+prev4)%1000000007 prev4 = (prevx*3)%1000000007 print(prev4) ```
output
1
65,840
13
131,681
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,841
13
131,682
Tags: dp, math, matrices Correct Solution: ``` n = int(input()); p = 3; ans = 0 for i in range(1,n): ans = (p - ans) % 1000000007; p = p % 1000000007 * 3; print(ans) ```
output
1
65,841
13
131,683
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a tetrahedron. Let's mark its vertices with letters A, B, C and D correspondingly. <image> An ant is standing in the vertex D of the tetrahedron. The ant is quite active and he wouldn't stay idle. At each moment of time he makes a step from one vertex to another one along some edge of the tetrahedron. The ant just can't stand on one place. You do not have to do much to solve the problem: your task is to count the number of ways in which the ant can go from the initial vertex D to itself in exactly n steps. In other words, you are asked to find out the number of different cyclic paths with the length of n from vertex D to itself. As the number can be quite large, you should print it modulo 1000000007 (109 + 7). Input The first line contains the only integer n (1 ≤ n ≤ 107) — the required length of the cyclic path. Output Print the only integer — the required number of ways modulo 1000000007 (109 + 7). Examples Input 2 Output 3 Input 4 Output 21 Note The required paths in the first sample are: * D - A - D * D - B - D * D - C - D
instruction
0
65,842
13
131,684
Tags: dp, math, matrices Correct Solution: ``` n=int(input()) a,b=1,0 m=10**9+7 for i in range(n): a,b=(b*3)%m,(a+b*2)%m print(a) ```
output
1
65,842
13
131,685
Evaluate the correctness of the submitted Python 2 solution to the coding contest problem. Provide a "Yes" or "No" response. Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i). The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1. We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree. Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query. Output Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Examples Input 6 5 1 1 1 3 3 zacccd 1 1 3 3 4 1 6 1 1 2 Output Yes No Yes Yes Yes Note String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac". Submitted Solution: ``` """ Python 3 compatibility tools. """ from __future__ import division, print_function import sys import os if False: from typing import List, Set, Dict, Tuple, Text, Optional, Callable, Any, Union from collections import deque import collections from types import GeneratorType import itertools import operator import functools import random import copy import heapq import math from atexit import register from io import BytesIO, IOBase import __pypy__ # type: ignore EPS = 10**-12 ######### # INPUT # ######### class Input(object): def __init__(self): if 'CPH' not in os.environ: sys.stdin = BytesIO(os.read(0, os.fstat(0).st_size)) sys.stdout = BytesIO() register(lambda: os.write(1, sys.stdout.getvalue())) def rawInput(self): # type: () -> str return sys.stdin.readline().rstrip('\r\n') def readInt(self): return int(self.rawInput()) ########## # OUTPUT # ########## class Output(object): def __init__(self): self.out = __pypy__.builders.StringBuilder() def write(self, text): # type: (str) -> None self.out.append(str(text)) def writeLine(self, text): # type: (str) -> None self.write(str(text) + '\n') def finalize(self): if sys.version_info[0] < 3: os.write(1, self.out.build()) else: os.write(1, self.out.build().encode()) ########### # LIBRARY # ########### def bootstrap(f, stack=[]): # Deep Recursion helper. # From: https://github.com/cheran-senthil/PyRival/blob/c1972da95d102d95b9fea7c5c8e0474d61a54378/docs/bootstrap.rst # Usage: # @bootstrap # def recur(n): # if n == 0: # yield 1 # yield (yield recur(n-1)) * n def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc int_add = __pypy__.intop.int_add int_sub = __pypy__.intop.int_sub int_mul = __pypy__.intop.int_mul def make_mod_mul(mod): fmod_inv = 1.0 / mod def mod_mul(a, b, c=0): res = int_sub(int_add(int_mul(a, b), c), int_mul( mod, int(fmod_inv * a * b + fmod_inv * c))) if res >= mod: return res - mod elif res < 0: return res + mod else: return res return mod_mul class Tree(object): ''' >>> tp = Tree([(1, 3), (5, 0), (0, 4), (7, 2), (3, 0), (6, 2), (0, 2)], 3) >>> tp.parent(3) -1 >>> tp.parent(1) 3 >>> tp.parent(4) 0 >>> tp.parent(6) 2 >>> tp.parent(7) 2 >>> tp.parent(2) 0 >>> tp.height(3) 0 >>> tp.height(1) 1 >>> tp.height(2) 2 >>> tp.height(6) 3 >>> tp.children(3) [1, 0] >>> tp.children(1) [] >>> tp.children(0) [5, 4, 2] https://codeforces.com/contest/609/submission/117755214 ''' def __init__(self, edges, root): # type: (List[Tuple[int, int]], int) -> None self.n = n = len(edges) + 1 self._root = root # type: int self._adj = [[] for _ in range(n)] for u, v in edges: assert 0 <= u < n assert 0 <= v < n self._adj[u].append(v) self._adj[v].append(u) self._parent = [-1] * n self._height = [-1] * n stack = [self._root] self._height[self._root] = 0 while stack: node = stack.pop() for child in self._adj[node]: if self._height[child] == -1: self._parent[child] = node self._height[child] = self._height[node] + 1 stack.append(child) self._children = [[] for _ in range(n)] for i in range(n): for neighbor in self._adj[i]: if neighbor != self._parent[i]: self._children[i].append(neighbor) def children(self, node): return self._children[node] def parent(self, node): return self._parent[node] def height(self, node): return self._height[node] def tree_flatten(tree): # type: (Tree) -> Tuple[List[int], List[int], List[int]] ''' >>> tree = Tree([[0, 4], [2, 0], [3, 1], [3, 0]], 3) >>> tree_flatten(tree) ([3, 1, 0, 4, 2], [2, 1, 4, 0, 3], [3, 1, 1, 5, 1]) >>> tree = Tree([], 0) >>> tree_flatten(tree) ([0], [0], [1]) Flatten a tree. Returns to_node, to_index, subtree_size to_node[i]: node at position i of the flattened array to_index[u]: index in the flattened array for node u subtree_size[u]: size of subtree rooted at node u ''' n = tree.n adj = tree._children clen = [len(i) for i in adj] ccur = [0] * n root = tree._root stack = [root] counter = 0 to_node = [0] * n to_index = [0] * n subtree_size = [0] * n while stack: node = stack[-1] if ccur[node] == 0: to_index[node] = counter to_node[counter] = node counter += 1 if ccur[node] == clen[node]: subtree_size[node] = counter - to_index[node] stack.pop() else: stack.append(adj[node][ccur[node]]) ccur[node] += 1 assert counter == n return to_node, to_index, subtree_size def Normalize(arr): ''' >>> Normalize([5, 1, 3, 5, 3, 1, 4]) [3, 0, 1, 3, 1, 0, 2] >>> Normalize([]) [] >>> Normalize([1.0, 3.0]) [0, 1] >>> Normalize([1, 2, 3]) [0, 1, 2] >>> Normalize([-1, -2, -3]) [2, 1, 0] ''' # transform arbitrary valued array into array of int, maintaining relative order. sorted_arr = map( operator.itemgetter(0), itertools.groupby(sorted(arr)) ) result = [0] * len(arr) for i in range(len(arr)): ele = arr[i] low = 0 high = len(sorted_arr) while low < high: mid = low + (high - low) // 2 if sorted_arr[mid] > ele: high = mid else: low = mid + 1 result[i] = low - 1 return result class RangeCountFind: ''' >>> x = RangeCountFind([1, 2, 3, 2, 1, 3]) >>> x.count(1, 3, 2) 2 >>> x.count(1, 3, 3) 1 >>> x.count(1, 3, 1) 0 >>> x.count(0, 5, 2) 2 >>> x.count(0, 5, 4) 0 >>> x.count(0, 5, -3) 0 >>> x.rightmost(0, 5, 3) 5 >>> x.rightmost(0, 4, 3) 2 >>> x.rightmost(0, 1, 3) -1 >>> x.leftmost(0, 5, 3) 2 >>> x.leftmost(4, 5, 3) 5 >>> x.leftmost(1, 1, 3) -1 >>> x.leftmost(1, 1, 999) -1 >>> x.rightmost (1, 1, 999) -1 >>> x.count(0, 4, 0) 0 >>> x.leftmost(0, 4, 0) -1 >>> x.rightmost(0, 4, 0) -1 >>> x.count(0, 4, 1) 2 >>> x.count(1, 4, 1) 1 >>> x = RangeCountFind([1, 2, 3, 2, 1, 3, -7]) >>> x.count(1, 3, 2) 2 >>> x.count(1, 3, 3) 1 >>> x.count(1, 3, 1) 0 >>> x.count(0, 5, 2) 2 >>> x.count(0, 5, 4) 0 >>> x.count(0, 5, -3) 0 >>> x.count(0, 4, 1) 2 >>> x.count(1, 4, 1) 1 >>> x.count(1, 4, -7) 0 >>> x.count(1, 6, -7) 1 ''' def __init__(self, data): # type: (List[Any]) -> None self._n = len(data) minval = min(data) maxval = max(data) # prevent import error Normalize if minval < 0 or maxval > 3 * len(data): # need to normalize self._normalized = True self._mapping = {} ndata = Normalize(data) else: self._normalized = False ndata = data self._nele = max(ndata)+1 self._ele_indexes = [[] for _ in range(self._nele)] for i, (original, val) in enumerate(zip(data, ndata)): self._ele_indexes[val].append(i) if self._normalized and len(self._ele_indexes[val]) == 1: self._mapping[original] = val def rightmost(self, start, stop, val): # Find rightmost occurrence of val, or -1 if not found assert 0 <= start <= stop < self._n if self._normalized: if val not in self._mapping: return -1 val = self._mapping[val] if val < 0 or val >= len(self._ele_indexes): return -1 indexes = self._ele_indexes[val] if not indexes: return -1 low = 0 high = len(indexes) while low < high: mid = low + (high - low) // 2 if indexes[mid] > stop: high = mid else: low = mid+1 if low == 0: return -1 position = indexes[low-1] if position < start: return -1 return position def leftmost(self, start, stop, val): # Find leftmost occurrence of val, or -1 if not found assert 0 <= start <= stop < self._n if self._normalized: if val not in self._mapping: return -1 val = self._mapping[val] if val < 0 or val >= len(self._ele_indexes): return -1 indexes = self._ele_indexes[val] low = 0 high = len(indexes) while low < high: mid = low + (high - low) // 2 if indexes[mid] >= start: high = mid else: low = mid+1 if low < len(indexes) and start <= indexes[low] <= stop: return indexes[low] else: return -1 def count(self, start, stop, val): # type: (int, int, Any) -> int """func of data[start, stop]""" assert 0 <= start <= stop < self._n if self._normalized: if val not in self._mapping: return 0 val = self._mapping[val] if val < 0 or val >= len(self._ele_indexes): return 0 indexes = self._ele_indexes[val] low = 0 high = len(indexes) while low < high: mid = low + (high - low) // 2 if indexes[mid] >= start: high = mid else: low = mid+1 start_index = low low = 0 high = len(indexes) while low < high: mid = low + (high - low) // 2 if indexes[mid] > stop: high = mid else: low = mid+1 stop_index = low return stop_index - start_index def __repr__(self): return "RangeCountFind({0})".format(self._data) class RangeXor: ''' >>> x = RangeXor([1, 2, 3, 2, 1]) >>> x.xor(1, 3) 3 >>> x.xor(0, 4) 3 >>> x.xor(2, 2) 3 ''' def __init__(self, data): # type: (List[Any]) -> None self._n = len(data) self._prefixsum = [0] * (self._n + 1) for i in range(self._n): self._prefixsum[i+1] = self._prefixsum[i] ^ data[i] def __len__(self): # type: () -> int return self._n def xor(self, start, stop): # type: (int, int) -> Any """func of data[start, stop]""" assert 0 <= start <= stop < self._n return self._prefixsum[stop+1] ^ self._prefixsum[start] def __repr__(self): return "RangeXor({0})".format(self._data) ######### # LOGIC # ######### def main(inp, out): # type: (Input, Output) -> None n, m = map(int, inp.rawInput().split()) edges = [] lel = map(int, inp.rawInput().split()) for i in range(1, n): u = lel[i-1] edges.append((u-1, i)) alphabet = inp.rawInput() tree = Tree(edges, 0) to_node, to_index, subtree_size = tree_flatten(tree) # Get depths heights = [tree.height(node) for node in to_node] rcf = RangeCountFind(heights) # Range xor for each height height_to_values = [[] for _ in range(n+1)] index_to_id = [0] * n for node in range(n): h = tree.height(node) index_to_id[to_index[node]] = len(height_to_values[h]) height_to_values[h].append(1 << (ord(alphabet[node]) - ord('a'))) xorsums = [RangeXor(values) for values in height_to_values] for _ in range(m): u, height = map(int, inp.rawInput().split()) u -= 1 height -= 1 left = to_index[u] right = left + subtree_size[u] - 1 lb = rcf.leftmost(left, right, height) if lb == -1: out.writeLine('Yes') else: rb = rcf.rightmost(left, right, height) # lb and rb are the indexes. ans = xorsums[height].xor(index_to_id[lb], index_to_id[rb]) if ans & (ans-1) == 0: out.writeLine('Yes') else: out.writeLine('No') ############### # BOILERPLATE # ############### output_obj = Output() main(Input(), output_obj) output_obj.finalize() ```
instruction
0
66,024
13
132,048
No
output
1
66,024
13
132,049
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i). The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1. We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree. Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query. Output Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Examples Input 6 5 1 1 1 3 3 zacccd 1 1 3 3 4 1 6 1 1 2 Output Yes No Yes Yes Yes Note String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac". Submitted Solution: ``` from bisect import bisect_left from collections import defaultdict from sys import stdin, stdout, stderr input = stdin.readline import gc, threading, sys from os import _exit gc.disable() def dfs(i, h): global time, IN, OUT, H IN[i] = time H[h].append((time, H[h][-1][1]^(1<<(ord(s[i])-ord('a')) ))) time+=1 for j in g[i]: dfs(j, h+1) OUT[i] = time time+=1 def find(i): ans = 0 for j in g[i]: ans = max(ans, find(j)) return ans+1 time, ans = 1, [] n ,m = map(int, input().split()) parent, s=list(map(int, input().split())), '$' + input() parent.insert(0, 0) parent.insert(0, 0) IN, OUT= [0]*(n+1), [0]*(n+1) g = [[] for v in range(n+1)] for i,j in enumerate(parent): g[j].append(i) try: z = find(1) except: print('height func') H = [[(0,0)] for i in range(z+5)] try: dfs(1,1) except: print('dfs func') for _ in range(m): root, height = map(int, input().split()) try: size = len(H[height]) except: print('bisect') try: l = bisect_left(H[height], (IN[root],-1), 0, size)-1 r = bisect_left(H[height], (OUT[root],-1), 0, size)-1 t = H[height][l][1] ^ H[height][r][1] b = t ^ (t & -t) ans.append('No' if b else 'Yes') except: print('xor') stdout.write('\n'.join(ans)) stdout.flush() _exit(0) ```
instruction
0
66,025
13
132,050
No
output
1
66,025
13
132,051
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i). The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1. We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree. Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query. Output Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Examples Input 6 5 1 1 1 3 3 zacccd 1 1 3 3 4 1 6 1 1 2 Output Yes No Yes Yes Yes Note String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac". Submitted Solution: ``` from bisect import bisect_left from collections import defaultdict from sys import stdin, stdout, stderr input = stdin.readline import gc, threading, sys from os import _exit gc.disable() def dfs(i, h): global time, IN, OUT, H IN[i] = time H[h].append((time, H[h][-1][1]^(1<<(ord(s[i])-ord('a')) ))) time+=1 for j in g[i]: dfs(j, h+1) OUT[i] = time time+=1 def find(i): ans = 0 for j in g[i]: ans = max(ans, find(j)) return ans+1 time, ans = 1, [] n ,m = map(int, input().split()) parent, s=list(map(int, input().split())), '$' + input() parent.insert(0, 0) parent.insert(0, 0) IN, OUT= [0]*(n+1), [0]*(n+1) g = [[] for v in range(n+1)] for i,j in enumerate(parent): g[j].append(i) try: z = find(1) except: print('height func') H = [[(0,0)] for i in range(z+1)] try: dfs(1,1) except: print('dfs func') try: for _ in range(m): root, height = map(int, input().split()) size = len(H[height]) try: l = bisect_left(H[height], (IN[root],-1), 0, size)-1 r = bisect_left(H[height], (OUT[root],-1), 0, size)-1 except: print('bisect') try: t = H[height][l][1] ^ H[height][r][1] except: print('xor') b = t ^ (t & -t) ans.append('No' if b else 'Yes') stdout.write('\n'.join(ans)) stdout.flush() _exit(0) except: print('query') ```
instruction
0
66,026
13
132,052
No
output
1
66,026
13
132,053
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i). The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1. We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree. Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query. Output Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Examples Input 6 5 1 1 1 3 3 zacccd 1 1 3 3 4 1 6 1 1 2 Output Yes No Yes Yes Yes Note String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac". Submitted Solution: ``` from bisect import bisect_left from collections import defaultdict from sys import stdin, stdout, stderr input = stdin.readline import gc, threading, sys from os import _exit gc.disable() def dfs(i, h): global time, IN, OUT, H IN[i] = time H[h].append((time, H[h][-1][1]^(1<<(ord(s[i])-ord('a')) ))) time+=1 for j in g[i]: dfs(j, h+1) OUT[i] = time time+=1 def find(i): ans = 0 for j in g[i]: ans = max(ans, find(j)) return ans+1 time, ans = 1, [] n ,m = map(int, input().split()) parent, s=list(map(int, input().split())), '$' + input() parent.insert(0, 0) parent.insert(0, 0) IN, OUT= [0]*(n+1), [0]*(n+1) g = [[] for v in range(n+1)] for i,j in enumerate(parent): g[j].append(i) try: z = find(1) except: print('height func') H = [[(0,0)] for i in range(z+5)] try: dfs(1,1) except: print('dfs func') for _ in range(m): try: root, height = map(int, input().split()) size = len(H[height]) l = bisect_left(H[height], (IN[root],-1), 0, size)-1 r = bisect_left(H[height], (OUT[root],-1), 0, size)-1 except: print('bisect') try: t = H[height][l][1] ^ H[height][r][1] b = t ^ (t & -t) ans.append('No' if b else 'Yes') except: print('xor') stdout.write('\n'.join(ans)) stdout.flush() _exit(0) ```
instruction
0
66,027
13
132,054
No
output
1
66,027
13
132,055
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i). The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1. We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree. Roma gives you m queries, the i-th of which consists of two numbers vi, hi. Let's consider the vertices in the subtree vi located at depth hi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used. Input The first line contains two integers n, m (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively. The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i). The next line contains n lowercase English letters, the i-th of these letters is written on vertex i. Next m lines describe the queries, the i-th line contains two numbers vi, hi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in the i-th query. Output Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes). Examples Input 6 5 1 1 1 3 3 zacccd 1 1 3 3 4 1 6 1 1 2 Output Yes No Yes Yes Yes Note String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome. Clarification for the sample test. In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z". In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them. In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome. In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome. In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac". Submitted Solution: ``` def populate(cur): if depth[cur] > y: return elif depth[cur] == y: words.append(cur) if cur not in parent: return for val in parent[cur]: populate(val) def isPal(): tmp = {} for val in words: if d[val] not in tmp: tmp[d[val]] = 1 else: tmp[d[val]] += 1 odds = 0 for val in tmp: if tmp[val] % 2 == 1: odds += 1 if odds >= 2: return False return True if __name__ == "__main__": n, m = map(int, input().split()) depth = [1 for _ in range(n)] parent = {} for i, val in enumerate(map(int, input().split())): depth[i+1] = depth[val-1] + 1 if val-1 not in parent: parent[val-1] = [i+1] else: parent[val-1].append(i+1) d = input() for _ in range(m): x, y = map(int, input().split()) words = [] populate(x-1) print(isPal()) ```
instruction
0
66,028
13
132,056
No
output
1
66,028
13
132,057
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,338
13
132,676
"Correct Solution: ``` from collections import defaultdict def paint(v, d, c): if color[v] == 0: color[v] = c if dp[v] >= d or d == 0: return dp[v] = d for nb in graph[v]: paint(nb, d-1, c) N, M = map(int, input().split()) dp = [0] * N color = [0] * N graph = defaultdict(set) for _ in range(M): i, j = map(int, input().split()) graph[i-1].add(j-1) graph[j-1].add(i-1) Q = int(input()) vdcs = [] for _ in range(Q): v, d, c = map(int, input().split()) vdcs.append((v-1, d, c)) vdcs.reverse() for v, d, c in vdcs: paint(v, d, c) for c in color: print(c) ```
output
1
66,338
13
132,677
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,339
13
132,678
"Correct Solution: ``` import sys input = sys.stdin.readline from collections import deque N,M=map(int,input().split()) table=[[] for i in range(N)] for i in range(M): a,b=map(int,input().split()) a,b=a-1,b-1 table[a].append(b) table[b].append(a) Q=int(input()) X=[[int(i) for i in input().split()] for i in range(Q)] color=[0]*Q dp=[[-1]*N for i in range(11)] for i in range(Q-1,-1,-1): v, d, c=X[i] v=v-1 color[i]=c dp[d][v]=max(dp[d][v],i) for d in range(10,0,-1): for x in range(N): for y in table[x]: dp[d-1][y]=max(dp[d][x],dp[d-1][y]) for i in range(N): s=-1 for d in range(11): s=max(s,dp[d][i]) if s==-1: print(0) else: print(color[s]) ```
output
1
66,339
13
132,679
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,340
13
132,680
"Correct Solution: ``` N, M = map(int, input().split()) G = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) G[a-1].append(b-1) G[b-1].append(a-1) dp = [{-1: -1} for i in range(N)] mark = {} Q = int(input()) col = [0]*(Q+1) col[-1] = 0 C = [] for i in range(Q): v, d, c = map(int, input().split()) col[i] = c C.append((v-1, d)) def dfs(v, d, idx): if d <= max(dp[v]): return dp[v][d] = idx if d: for w in G[v]: dfs(w, d-1, idx) for i in range(Q-1, -1, -1): v, d = C[i] dfs(v, d, i) print(*(col[max(e.values())] for e in dp), sep='\n') ```
output
1
66,340
13
132,681
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,341
13
132,682
"Correct Solution: ``` import sys readline = sys.stdin.readline ns = lambda: readline().rstrip() ni = lambda: int(readline().rstrip()) nm = lambda: map(int, readline().split()) nl = lambda: list(map(int, readline().split())) def solve(): n, m = nm() G = [list() for _ in range(n)] for _ in range(m): a, b = nm() a -= 1; b -= 1 G[a].append(b) G[b].append(a) Q = int(input()) queries = [tuple(nm()) for _ in range(Q)][::-1] dp = [[Q]*11 for _ in range(n)] for i in range(Q-1, -1, -1): v, d, _ = queries[i] dp[v-1][d] = i for d in range(10, 0, -1): for v in range(n): for x in G[v] + [v]: if dp[x][d-1] > dp[v][d]: dp[x][d-1] = dp[v][d] queries.append((-1, -1, 0)) color = [queries[dp[v][0]][2] for v in range(n)] print(*color, sep='\n') return solve() ```
output
1
66,341
13
132,683
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,342
13
132,684
"Correct Solution: ``` import sys input = sys.stdin.readline def func(v, d, c): if memo[v][d]!=0: return memo[v][d] = c if d==0: return func(v, d-1, c) for nv in G[v]: func(nv, d-1, c) N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) G[a-1].append(b-1) G[b-1].append(a-1) Q = int(input()) q = [tuple(map(int, input().split())) for _ in range(Q)] q.reverse() memo = [[0]*11 for _ in range(N)] for v, d, c in q: func(v-1, d, c) for v in range(N): print(memo[v][0]) ```
output
1
66,342
13
132,685
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,343
13
132,686
"Correct Solution: ``` import sys sys.setrecursionlimit(10**7) input = sys.stdin.readline def main(): n, m = map(int, input().split()) G = [[] for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 G[a].append(b) G[b].append(a) q = int(input()) vdc = [list(map(int, input().split())) for _ in range(q)][::-1] dp = [[0]*11 for _ in range(n)] def dfs(v, d, c): if dp[v][d]: return dp[v][d] if d == 0: dp[v][d] = c return for u in G[v]: dfs(u, d-1, c) dfs(v, d-1, c) dp[v][d] = c for v, d, c in vdc: dfs(v-1, d, c) for i in range(n): print(dp[i][0]) if __name__ == "__main__": main() ```
output
1
66,343
13
132,687
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,344
13
132,688
"Correct Solution: ``` from collections import deque N,M=map(int,input().split()) G=[[] for i in range(N)] for i in range(M): a,b=map(int,input().split()) G[a-1].append(b-1) G[b-1].append(a-1) Q=int(input()) v=[0 for i in range(Q)] d=[0 for i in range(Q)] c=[0 for i in range(Q)] for i in range(Q): v[-i-1],d[-i-1],c[-i-1]=map(int,input().split());v[-i-1]-=1 q=deque() color=[0 for i in range(N)] dp=[-1 for i in range(N)] for t in range(Q): if dp[v[t]]>=d[t]: continue dp[v[t]]=d[t] q.append((v[t],d[t])) while(q): vv,dd=q.popleft() if color[vv]==0: color[vv]=c[t] dd-=1 for y in G[vv]: if dp[y]>=dd: continue dp[y]=dd q.append((y,dd)) for line in color: print(line) ```
output
1
66,344
13
132,689
Provide a correct Python 3 solution for this coding contest problem. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3
instruction
0
66,345
13
132,690
"Correct Solution: ``` n, m = map(int, input().split()) g = {} used = {i:[False for _ in range(11)] for i in range(n)} color = [0 for _ in range(n)] for _ in range(m): u, v = map(int, input().split()) u-=1 v-=1 if u not in g: g[u] = [] if v not in g: g[v] = [] g[u].append(v) g[v].append(u) q = int(input()) Q = [] for _ in range(q): node, dis, col = map(int, input().split()) Q.append([node-1, dis, col]) Q = Q[::-1] def bfs(now, dist, col): if dist < 0: return if used[now][dist]: return used[now][dist] = True if not color[now]: color[now] = col if now in g: for x in g[now]: bfs(x, dist - 1, col) for node, dis, col in Q: bfs(node, dis, col) for x in color: print(x) ```
output
1
66,345
13
132,691
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` import sys input = sys.stdin.readline INF = 10**14 N, M = map(int, input().split()) graph = [[] for _ in range(N)] for _ in range(M): a, b = map(int, input().split()) graph[a-1].append(b-1) graph[b-1].append(a-1) maxd = 0 Q = int(input()) Query = [] Color = [] for _ in range(Q): v, d, c = map(int, input().split()) if d > maxd: maxd = d Query.append((v-1, d)) Color.append(c) Query = Query[::-1] Color = Color[::-1] dp = [[INF]*(maxd+1) for _ in range(N)] for i, (v, d) in enumerate(Query): if i < dp[v][d]: dp[v][d] = i for d in reversed(range(maxd)): for v in range(N): if dp[v][d+1] < dp[v][d]: dp[v][d] = dp[v][d+1] for nv in graph[v]: if dp[v][d+1] < dp[nv][d]: dp[nv][d] = dp[v][d+1] for v in range(N): seq = dp[v][0] if seq == INF: print(0) else: print(Color[seq]) ```
instruction
0
66,346
13
132,692
Yes
output
1
66,346
13
132,693
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` n, m = map(int, input().split()) node = [[] for _ in range(n + 1)] for i in range(m): a, b = map(int, input().split()) node[a].append(b) node[b].append(a) q = int(input()) node_color = [0 for _ in range(n + 1)] vdc = [list(map(int, input().split())) for _ in range(q)] vdc = vdc[::-1] painted = set() visited = [[0] * 11 for _ in range(n + 1)] def dfs(now, dist, color): if dist < 0: return if visited[now][dist]: return visited[now][dist] += 1 if not node_color[now]: node_color[now] = color for x in node[now]: dfs(x, dist - 1, color) for i in vdc: v, d, c = i dfs(v, d, c) for m in range(n): print(node_color[m + 1]) ```
instruction
0
66,347
13
132,694
Yes
output
1
66,347
13
132,695
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` import sys from collections import deque def solve(): def rec(v, d, i): if dp[v][d]: return dp[v][d] = i if d == 0: return rec(v, d - 1, i) for u in Adj[v]: rec(u, d - 1, i) N, M = map(int, sys.stdin.readline().split()) Adj = [[] for i in range(N)] for i in range(M): a, b = map(int, sys.stdin.readline().split()) a, b = a - 1, b - 1 Adj[a].append(b) Adj[b].append(a) Q = int(sys.stdin.readline()) v = [0] * Q d = [0] * Q c = [0] * Q for i in range(Q - 1, -1, -1): v[i], d[i], c[i] = map(int, sys.stdin.readline().split()) v[i] -= 1 dp = [[0]*(10 + 1) for i in range(N)] for i in range(Q): rec(v[i], d[i], i + 1) # for i in range(N): # print(*dp[i]) # print() for i in range(N): if dp[i][0] > 0: print(c[dp[i][0] - 1]) else: print(0) if __name__ == '__main__': solve() ```
instruction
0
66,348
13
132,696
Yes
output
1
66,348
13
132,697
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(pow(10, 6)) def main(): n, m = map(int, input().split()) ab = [tuple(map(int, input().split())) for _ in range(m)] edges = [[] for _ in range(n)] for a, b in ab: edges[a - 1].append(b - 1) edges[b - 1].append(a - 1) q = int(input()) ans = [0 for _ in range(n)] dd = [-1 for _ in range(n)] vdc = [tuple(map(int, input().split())) for _ in range(q)] for v, d, c in vdc[::-1]: if dd[v - 1] >= d: # v - 1 から距離 d の部分は塗りつぶされているため無視 continue node = [] node.append(v - 1) while d >= 0 and len(node) > 0: next_node = [] while len(node) > 0: u = node.pop() if dd[u] >= d: continue dd[u] = d if ans[u] == 0: ans[u] = c for v in edges[u]: if dd[v] < d - 1: next_node.append(v) node = next_node d -= 1 print(*ans, sep='\n') if __name__ == '__main__': main() ```
instruction
0
66,349
13
132,698
Yes
output
1
66,349
13
132,699
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` # coding:utf-8 import sys from collections import deque, defaultdict INF = float('inf') MOD = 10 ** 9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def II(): return int(sys.stdin.readline()) def SI(): return input() def main(): n, m = LI() G = defaultdict(list) for _ in range(m): a, b = LI_() G[a].append(b) G[b].append(a) q = II() Q = [LI() for _ in range(q)] # Q.reverse() if n > 2000: exit() color = [0] * n for v, d, c in Q: v -= 1 q = deque() q.append((v, 0)) visited = set() while q: v, dist = q.pop() visited.add(v) color[v] = c if dist == d: continue for to in G[v]: if to in visited: continue q.append((to, dist + 1)) print(*color, sep='\n') main() ```
instruction
0
66,350
13
132,700
No
output
1
66,350
13
132,701
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` from queue import deque def dijkstra(s, d): queue = deque([(0, s)]) paint = set() while queue: cost, v = queue.popleft() if cost > d: break paint.add(v) queue.extend((cost + 1, u) for u in links[v] if u not in paint) return paint n, m = map(int, input().split()) links = [None] + [set() for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) links[a].add(b) links[b].add(a) q = int(input()) queries = [map(int, input().split()) for _ in range(q)] painted = set() colors = [0] * (n + 1) while queries: v, d, c = queries.pop() paint = dijkstra(v, d) - painted for i in paint: colors[i] = c painted |= paint for c in colors[1:]: print(c) ```
instruction
0
66,351
13
132,702
No
output
1
66,351
13
132,703
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` import numpy as np N,M = map(int,input().split()) nodes = [[False]* N for j in range(N)] for m in range(M): a,b = map(int,input().split()) nodes[a-1][b-1] = True nodes[b-1][a-1] = True mat1 = np.matrix(nodes,dtype=bool) mat2 = mat1.copy() A = [mat1.tolist()] for i in range(10): mat2 = mat2.dot(mat1) a = mat2.tolist() A.append(a) ''' for ai,a in enumerate(A): for k in a: print(k) print(ai) ''' Colour = [0] * N Q = int(input()) for q in range(Q): v,d,c = map(int,input().split()) Colour[v - 1] = c if d == 0: continue for n in range(N): if d == 1 : if (not A[0][v - 1][n]): continue else: Colour[n] = c else: if A[d - 1][v - 1][n] or A[d - 2][v - 1][n] > 0: Colour[n] = c for C in Colour: print(C) ```
instruction
0
66,352
13
132,704
No
output
1
66,352
13
132,705
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Squid loves painting vertices in graphs. There is a simple undirected graph consisting of N vertices numbered 1 through N, and M edges. Initially, all the vertices are painted in color 0. The i-th edge bidirectionally connects two vertices a_i and b_i. The length of every edge is 1. Squid performed Q operations on this graph. In the i-th operation, he repaints all the vertices within a distance of d_i from vertex v_i, in color c_i. Find the color of each vertex after the Q operations. Constraints * 1 ≤ N,M,Q ≤ 10^5 * 1 ≤ a_i,b_i,v_i ≤ N * a_i ≠ b_i * 0 ≤ d_i ≤ 10 * 1 ≤ c_i ≤10^5 * d_i and c_i are all integers. * There are no self-loops or multiple edges in the given graph. Input Input is given from Standard Input in the following format: N M a_1 b_1 : a_{M} b_{M} Q v_1 d_1 c_1 : v_{Q} d_{Q} c_{Q} Output Print the answer in N lines. In the i-th line, print the color of vertex i after the Q operations. Examples Input 7 7 1 2 1 3 1 4 4 5 5 6 5 7 2 3 2 6 1 1 1 2 2 Output 2 2 2 2 2 1 0 Input 14 10 1 4 5 7 7 11 4 10 14 7 14 3 6 14 8 11 5 13 8 3 8 8 6 2 9 7 85 6 9 3 6 7 5 10 3 1 12 9 4 9 6 6 8 2 3 Output 1 0 3 1 5 5 3 3 6 1 3 4 5 3 Submitted Solution: ``` import numpy as np def dp(v, d, c): if memo[v-1][d]: return memo[v-1][d] = True if d == 0: res[v-1] = str(c) return None dp(v, d-1, c) for e in dic[v-1]: dp(e, d-1, c) N, M = tuple(map(int, input().split(' '))) dic = [[] for _ in range(N)] memo = [[False]*11 for _ in range(N)] for m in range(M): a, b = tuple(map(int, input().split(' '))) dic[a-1].append(b) dic[b-1].append(a) Q = int(input()) vdc = [tuple(map(int, input().split(' '))) for _ in range(Q)] res = ['0']*N [dp(v, d, c) for v, d, c in vdc[::-1]] print('\n'.join(res)) ```
instruction
0
66,353
13
132,706
No
output
1
66,353
13
132,707
Provide a correct Python 3 solution for this coding contest problem. Problem A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices. However, one step is to follow one side from one vertex and move to another vertex. Constraints * 2 ≤ N ≤ 105 * 1 ≤ ui, vi ≤ N (1 ≤ i ≤ N-1) * ui ≠ vi * The graph given is concatenated Input The input is given in the following format. N u1 v1 .. .. .. uN−1 vN−1 The first line is given one integer N. In the following N-1 line, the integers ui and vi representing the vertex numbers at both ends of the i-th side are given on the i-th line, separated by blanks. Output Output the shortest number of steps to visit all vertices starting from vertex i on the i-th line from vertex 1 to vertex N. Examples Input 2 1 2 Output 1 1 Input 6 1 2 1 3 3 4 3 5 5 6 Output 7 6 8 7 7 6
instruction
0
66,411
13
132,822
"Correct Solution: ``` from collections import deque N = int(input()) X = [[] for i in range(N)] for i in range(N-1): x, y = map(int, input().split()) X[x-1].append(y-1) X[y-1].append(x-1) P = [-1] * N Q = deque([0]) T = [] while Q: i = deque.popleft(Q) T.append(i) for a in X[i]: if a != P[i]: P[a] = i X[a].remove(i) deque.append(Q, a) BUA = [0] * N # Bottom Up : i以下をすべてまわる BUB = [0] * N # Bottom Up : i以下をすべてまわってiに戻る TDA = [0] * N # Top Down : iの上をすべてまわる TDB = [0] * N # Top Down : iの上をすべてまわってiに戻る for i in T[::-1]: if len(X[i]) == 0: BUA[i] = 0 BUB[i] = 0 continue s = 0 ma = 0 for j in X[i]: s += BUB[j] + 2 ma = max(ma, BUB[j] - BUA[j] + 1) BUA[i] = s - ma BUB[i] = s for i in T: B = [0] * (len(X[i]) + 1) C = [0] * (len(X[i]) + 1) for k, j in enumerate(X[i]): B[k+1] = B[k] + BUB[j] + 2 C[k+1] = max(C[k], BUB[j] - BUA[j] + 2) s = 0 ma = 0 for k in range(len(X[i]))[::-1]: j = X[i][k] TDB[j] = TDB[i] + s + B[k] + 2 TDA[j] = min(TDB[j] - max(ma, C[k]), TDA[i] + s + B[k] + 1) s += BUB[j] + 2 ma = max(ma, BUB[j] - BUA[j] + 2) for t in [min(a+d, b+c) for a, b, c, d in zip(BUA, BUB, TDA, TDB)]: print(t) ```
output
1
66,411
13
132,823
Provide a correct Python 3 solution for this coding contest problem. Problem A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices. However, one step is to follow one side from one vertex and move to another vertex. Constraints * 2 ≤ N ≤ 105 * 1 ≤ ui, vi ≤ N (1 ≤ i ≤ N-1) * ui ≠ vi * The graph given is concatenated Input The input is given in the following format. N u1 v1 .. .. .. uN−1 vN−1 The first line is given one integer N. In the following N-1 line, the integers ui and vi representing the vertex numbers at both ends of the i-th side are given on the i-th line, separated by blanks. Output Output the shortest number of steps to visit all vertices starting from vertex i on the i-th line from vertex 1 to vertex N. Examples Input 2 1 2 Output 1 1 Input 6 1 2 1 3 3 4 3 5 5 6 Output 7 6 8 7 7 6
instruction
0
66,412
13
132,824
"Correct Solution: ``` import sys sys.setrecursionlimit(10 ** 7) def resolve(): def dfs1(r_topo, par): for i in reversed(r_topo): stack = [i] while stack: idx = stack.pop() for to in G[idx]: if to == par[i]: continue dist[idx] = max(dist[idx], dist[to] + 1) def dfs2(idx, d_par, par): stack = [(idx,d_par, par)] while stack: idx, d_par, par = stack.pop() d_child = [] d_child.append((0, -1)) for to in G[idx]: if to == par: d_child.append((d_par + 1, to)) else: d_child.append((dist[to] + 1, to)) d_child.sort(reverse=True) ans[idx] = d_child[0][0] for to in G[idx]: if to == par: continue nx_d_par = d_child[d_child[0][1] == to][0] stack.append((to, nx_d_par, idx)) #dfs2(to, nx_d_par, idx) N = int(input()) if N == 1: return print(0) G = [[] for _ in range(N)] for i in range(N - 1): a, b = map(int, input().split()) a -= 1 b -= 1 G[a].append(b) G[b].append(a) topo = [] P = [-1] * N node = [0] while node: s = node.pop() topo.append(s) for to in G[s]: if to == P[s]: continue P[to] = s node.append(to) dist = [0]*N ans = [0] * N dfs1(topo,P) dfs2(0, 0, -1) for i in range(N): print((N - 1) * 2 - ans[i]) if __name__ == '__main__': resolve() ```
output
1
66,412
13
132,825
Provide a correct Python 3 solution for this coding contest problem. Problem A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices. However, one step is to follow one side from one vertex and move to another vertex. Constraints * 2 ≤ N ≤ 105 * 1 ≤ ui, vi ≤ N (1 ≤ i ≤ N-1) * ui ≠ vi * The graph given is concatenated Input The input is given in the following format. N u1 v1 .. .. .. uN−1 vN−1 The first line is given one integer N. In the following N-1 line, the integers ui and vi representing the vertex numbers at both ends of the i-th side are given on the i-th line, separated by blanks. Output Output the shortest number of steps to visit all vertices starting from vertex i on the i-th line from vertex 1 to vertex N. Examples Input 2 1 2 Output 1 1 Input 6 1 2 1 3 3 4 3 5 5 6 Output 7 6 8 7 7 6
instruction
0
66,413
13
132,826
"Correct Solution: ``` import sys input = sys.stdin.buffer.readline sys.setrecursionlimit(10 ** 7) N = int(input()) edge = [[] for _ in range(N + 1)] for _ in range(N - 1): x, y = map(int, input().split()) x -= 1 y -= 1 edge[x].append(y) edge[y].append(x) topo = [] parent = [-1] * N node = [0] while node: s = node.pop() topo.append(s) for t in edge[s]: if t == parent[s]: continue parent[t] = s node.append(t) memo = [0] * N # ノードiより下の情報をマージしたもの res = [0] * N # 求めたいやつ、ノードiの上に出ていく情報 for s in reversed(topo): for t in edge[s]: if t == parent[s]: continue memo[s] = max(memo[s], res[t]) res[s] = memo[s] + 1 TD = [0] * N # 上からノードiへ向かう辺の情報 for s in topo: acc = TD[s] for t in edge[s]: if t == parent[s]: continue TD[t] = max(TD[t], acc) acc = max(acc, res[t]) acc = 0 for t in reversed(edge[s]): if t == parent[s]: continue TD[t] = max(TD[t], acc) + 1 acc = max(acc, res[t]) res[t] = max(memo[t], TD[t]) + 1 ans = [2 * (N - 1) - res[i] + 1 for i in range(N)] print(*ans, sep="\n") ```
output
1
66,413
13
132,827
Provide a correct Python 3 solution for this coding contest problem. Problem A graph is given in which N vertices, each numbered from 1 to N, are connected by N-1 undirected edges. For each vertex, output the shortest number of steps to start from that vertex and visit all vertices. However, one step is to follow one side from one vertex and move to another vertex. Constraints * 2 ≤ N ≤ 105 * 1 ≤ ui, vi ≤ N (1 ≤ i ≤ N-1) * ui ≠ vi * The graph given is concatenated Input The input is given in the following format. N u1 v1 .. .. .. uN−1 vN−1 The first line is given one integer N. In the following N-1 line, the integers ui and vi representing the vertex numbers at both ends of the i-th side are given on the i-th line, separated by blanks. Output Output the shortest number of steps to visit all vertices starting from vertex i on the i-th line from vertex 1 to vertex N. Examples Input 2 1 2 Output 1 1 Input 6 1 2 1 3 3 4 3 5 5 6 Output 7 6 8 7 7 6
instruction
0
66,414
13
132,828
"Correct Solution: ``` def main(): import sys input = sys.stdin.readline sys.setrecursionlimit(10 ** 9) from collections import deque 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) #直径を求める dist = [-1] * N dist[0] = 0 que = deque() que.append(0) #スタート地点を入れる while len(que) != 0: tmp = que.popleft() for i in G[tmp]: if dist[i] == -1: dist[i] = dist[tmp] + 1 que.append(i) tmp = 0 start = -1 for index, x in enumerate(dist): if tmp < x: start = index tmp = x dist = [-1] * N dist[start] = 0 que = deque() que.append(start) #スタート地点を入れる while len(que) != 0: tmp = que.popleft() for i in G[tmp]: if dist[i] == -1: dist[i] = dist[tmp] + 1 que.append(i) tmp = 0 gpal = -1 for index, x in enumerate(dist): if tmp < x: goal = index tmp = x dist1 = [-1] * N dist1[goal] = 0 que = deque() que.append(goal) #スタート地点を入れる while len(que) != 0: tmp = que.popleft() for i in G[tmp]: if dist1[i] == -1: dist1[i] = dist1[tmp] + 1 que.append(i) # print (dist) # print (dist1) for i in range(N): print (2 * (N - 1) - max(dist[i], dist1[i])) if __name__ == '__main__': main() ```
output
1
66,414
13
132,829
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,572
13
133,144
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.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(io.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() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion N = int(input()) E = [[] for _ in range(N+1)] for _ in range(N-1): v, u = map(int, input().split()) E[v].append(u) E[u].append(v) ans2 = N-1 for v in range(1, N+1): n = 0 for u in E[v]: n += len(E[u]) == 1 ans2 -= max(0, n-1) for start in range(1, N+1): if len(E[start])==1: break q = [start] pa = False Closed = [False] * (N+1) Closed[start] = True ans1 = 1 while q: q_new = [] for v in q: Closed[v] = True v_is_leaf = True for u in E[v]: if Closed[u]: continue v_is_leaf = False q_new.append(u) if pa and v_is_leaf: ans1 = 3 q = q_new pa = not pa print(ans1, ans2) ```
output
1
66,572
13
133,145
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,573
13
133,146
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` from collections import defaultdict, deque import os def get_neighbors(edges): neighbors = defaultdict(set, {}) for v1, v2 in edges: if v1 != v2: neighbors[v1].add(v2) neighbors[v2].add(v1) return dict(neighbors) def is_all_even(adj, root): seen = set() fringe = {root} dist = 1 while fringe: new_fringe = set() for node in fringe: seen.add(node) for n in adj[node]: if len(adj[n]) == 1 and dist % 2 == 1: return False elif n not in seen: new_fringe.add(n) fringe = new_fringe dist += 1 return True def solve(edges): adj = get_neighbors(edges) leaves = [i for i, j in adj.items() if len(j) == 1] m = 1 if is_all_even(adj, leaves[0]) else 3 parents = set(k for l in leaves for k in adj[l]) M = len(adj) - (len(leaves) - len(parents)) - 1 return m, M def pp(input): n = int(input()) edges = [tuple(map(int, input().split(" "))) for _ in range(n - 1)] print(" ".join(map(str, solve(edges)))) if "paalto" in os.getcwd(): from string_source import string_source pp( string_source( """6 1 3 2 3 3 4 4 5 5 6""" ) ) pp( string_source( """6 1 3 2 3 3 4 4 5 4 6""" ) ) pp( string_source( """7 1 2 2 7 3 4 4 7 5 6 6 7""" ) ) else: pp(input) ```
output
1
66,573
13
133,147
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,574
13
133,148
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` import os import sys input = sys.stdin.buffer.readline #sys.setrecursionlimit(int(3e5)) from collections import deque from queue import PriorityQueue import math # list(map(int, input().split())) ##################################################################################### class CF(object): def __init__(self): self.n = int(input()) self.g = [[] for _ in range(self.n)] for _ in range(self.n - 1): x,y = list(map(int, input().split())) x-=1 y-=1 self.g[x].append(y) self.g[y].append(x) pass self.vis = [0] * self.n self.f = [-1] * self.n self.h = [0] * self.n self.leaf = [] for i in range(self.n): if(len(self.g[i]) == 1): self.leaf.append(i) pass self.root = self.leaf[0] def bfs(self): que = deque([self.root]) self.vis[self.root] = True while(que): now = que.popleft() for to in self.g[now]: if(not self.vis[to]): self.h[to] = self.h[now] + 1 self.vis[to] = True self.f[to] = now que.append(to) pass pass def check(self): for i in range(1, len(self.leaf)): if(self.h[self.leaf[i]] % 2 != 0): return False pass return True def main(self): self.bfs() ans_min = None if(self.check()): ans_min = 1 else: ans_min = 3 ans_max = self.n - 1 cnt = 0 self.vis = [0] * self.n for i in range(1, len(self.leaf)): if(self.h[self.leaf[i]] == 2): cnt += 1 else: if(self.vis[self.f[self.leaf[i]]]): cnt+=1 pass self.vis[self.f[self.leaf[i]]] = True pass ans_max = ans_max - cnt print(str(ans_min) + ' '+ str(ans_max)) if __name__ == "__main__": cf = CF() cf.main() pass ```
output
1
66,574
13
133,149
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,575
13
133,150
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` n = int(input()) l = [[] for _ in range(n)] for _ in range(n-1): p1, p2 = map(lambda x : x-1, map(int, input().split())) l[p1].append(p2) l[p2].append(p1) leaf = [] e = [0] * n maxans = n-1 for i in range(n): temp = l[i] if len(temp) == 1: if e[temp[0]] == 1: maxans -= 1 else: e[temp[0]] = 1 leaf.append(i) q = [0] visited = [-1]*n visited[0] = 0 while q: node = q.pop() for i in l[node]: if visited[i] == -1: q.append(i) visited[i] = 1 - visited[node] f = visited[leaf[0]] for i in leaf: if visited[i] != f: minans = 3 break else: minans = 1 print(minans, maxans) ```
output
1
66,575
13
133,151
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,576
13
133,152
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline from collections import deque def prog(): n = int(input()) adj_list = [[] for i in range(n+1)] for i in range(n-1): a,b = map(int,input().split()) adj_list[a].append(b) adj_list[b].append(a) leaves = set() for i in range(1,n+1): if len(adj_list[i]) == 1: leaves.add(i) for i in leaves: root = i break q = deque([root]) dists = [0 for i in range(n+1)] visited = set() while q: curr = q.popleft() for neighbor in adj_list[curr]: if neighbor not in visited: dists[neighbor] = dists[curr] + 1 q.append(neighbor) visited.add(neighbor) odd = False for leave in leaves: if dists[leave] % 2 == 1: odd = True break if odd: minimum = 3 else: minimum = 1 distinct_leaves = 0 for i in range(1,n+1): for neighbor in adj_list[i]: if neighbor in leaves: distinct_leaves += 1 break print(minimum, n-1 - len(leaves) + distinct_leaves) prog() ```
output
1
66,576
13
133,153
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,577
13
133,154
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` from sys import stdin input = stdin.readline class N: def __init__(self, v) -> None: self.v = v self.c = set() self.l = False if __name__ == '__main__': n = int(input()) arr = [N(i) for i in range(n)] es = set() for _ in range(n - 1): x, y = map(int, input().split()) x -= 1 y -= 1 x, y = min(x, y), max(x, y) es.add((x, y)) arr[x].c.add(arr[y]) arr[y].c.add(arr[x]) ps = set() for x in arr: if len(x.c) == 1: x.l = True ps.add(list(x.c)[0]) for p in ps: kept = False rs = [] for c in p.c: if c.l: if kept: x = p.v y = c.v x, y = min(x, y), max(x, y) es.discard((x, y)) rs.append(c) else: kept = True for c in rs: p.c.discard(c) root = ps.pop() stk = [(root, 0)] viz = set() ls = [] while stk: root, l = stk.pop() viz.add(root) for c in root.c: if c not in viz: if c.l: ls.append(l + 1) else: stk.append((c, l + 1)) if len(es) > 1: print(1 + 2 * int(len(set([l % 2 for l in ls])) == 2), len(es)) else: print(1, 1) ```
output
1
66,577
13
133,155
Provide tags and a correct Python 3 solution for this coding contest problem. You have unweighted tree of n vertices. You have to assign a positive weight to each edge so that the following condition would hold: * For every two different leaves v_{1} and v_{2} of this tree, [bitwise XOR](https://en.wikipedia.org/wiki/Bitwise_operation#XOR) of weights of all edges on the simple path between v_{1} and v_{2} has to be equal to 0. Note that you can put very large positive integers (like 10^{(10^{10})}). It's guaranteed that such assignment always exists under given constraints. Now let's define f as the number of distinct weights in assignment. <image> In this example, assignment is valid, because bitwise XOR of all edge weights between every pair of leaves is 0. f value is 2 here, because there are 2 distinct edge weights(4 and 5). <image> In this example, assignment is invalid, because bitwise XOR of all edge weights between vertex 1 and vertex 6 (3, 4, 5, 4) is not 0. What are the minimum and the maximum possible values of f for the given tree? Find and print both. Input The first line contains integer n (3 ≤ n ≤ 10^{5}) — the number of vertices in given tree. The i-th of the next n-1 lines contains two integers a_{i} and b_{i} (1 ≤ a_{i} < b_{i} ≤ n) — it means there is an edge between a_{i} and b_{i}. It is guaranteed that given graph forms tree of n vertices. Output Print two integers — the minimum and maximum possible value of f can be made from valid assignment of given tree. Note that it's always possible to make an assignment under given constraints. Examples Input 6 1 3 2 3 3 4 4 5 5 6 Output 1 4 Input 6 1 3 2 3 3 4 4 5 4 6 Output 3 3 Input 7 1 2 2 7 3 4 4 7 5 6 6 7 Output 1 6 Note In the first example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image> In the second example, possible assignments for each minimum and maximum are described in picture below. The f value of valid assignment of this tree is always 3. <image> In the third example, possible assignments for each minimum and maximum are described in picture below. Of course, there are multiple possible assignments for each minimum and maximum. <image>
instruction
0
66,578
13
133,156
Tags: bitmasks, constructive algorithms, dfs and similar, greedy, math, trees Correct Solution: ``` import sys readline = sys.stdin.readline def parorder(Edge, p): N = len(Edge) par = [0]*N par[p] = -1 stack = [p] order = [] visited = set([p]) ast = stack.append apo = order.append while stack: vn = stack.pop() apo(vn) for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn ast(vf) return par, order def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res N = int(readline()) Edge = [[] for _ in range(N)] for _ in range(N-1): a, b = map(int, readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) Leaf = [i for i in range(N) if len(Edge[i]) == 1] sLeaf = set(Leaf) for i in range(N): if i not in sLeaf: root = i break P, L = parorder(Edge, root) dp = [0]*N used = set([root]) stack = [root] while stack: vn = stack.pop() for vf in Edge[vn]: if vf not in used: used.add(vf) stack.append(vf) dp[vf] = 1-dp[vn] if len(set([dp[i] for i in Leaf])) == 1: mini = 1 else: mini = 3 k = set() for l in Leaf: k.add(P[l]) maxi = N-1 - len(Leaf) + len(k) print(mini, maxi) ```
output
1
66,578
13
133,157