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. You are given a functional graph. It is a directed graph, in which from each vertex goes exactly one arc. The vertices are numerated from 0 to n - 1. Graph is given as the array f0, f1, ..., fn - 1, where fi — the number of vertex to which goes the only arc from the vertex i. Besides you are given array with weights of the arcs w0, w1, ..., wn - 1, where wi — the arc weight from i to fi. <image> The graph from the first sample test. Also you are given the integer k (the length of the path) and you need to find for each vertex two numbers si and mi, where: * si — the sum of the weights of all arcs of the path with length equals to k which starts from the vertex i; * mi — the minimal weight from all arcs on the path with length k which starts from the vertex i. The length of the path is the number of arcs on this path. Input The first line contains two integers n, k (1 ≤ n ≤ 105, 1 ≤ k ≤ 1010). The second line contains the sequence f0, f1, ..., fn - 1 (0 ≤ fi < n) and the third — the sequence w0, w1, ..., wn - 1 (0 ≤ wi ≤ 108). Output Print n lines, the pair of integers si, mi in each line. Examples Input 7 3 1 2 3 4 3 2 6 6 3 1 4 2 2 3 Output 10 1 8 1 7 1 10 2 8 2 7 1 9 3 Input 4 4 0 1 2 3 0 1 2 3 Output 0 0 4 1 8 2 12 3 Input 5 3 1 2 3 4 0 4 1 2 14 3 Output 7 1 17 1 19 2 21 3 8 1 Submitted Solution: ``` n, k = map(int, input().split()) a = list(map(int, input().split())) b = list(map(int, input().split())) logn = len(bin(n)) - 2 sum_w = [[b[i]]*logn for i in range(n)] min_w = [[b[i]]*logn for i in range(n)] dest = [[a[i]]*logn for i in range(n)] for j in range(1, logn): for i in range(n): dest[i][j] = dest[dest[i][j-1]][j-1] sum_w[i][j] = sum_w[i][j-1] + sum_w[dest[i][j-1]][j-1] min_w[i][j] = min(min_w[i][j-1], min_w[dest[i][j-1]][j-1]) for i in range(n): sum_v, min_v = 0, 10**9 v = i rem = k for j in range(logn): if rem & 1: sum_v += sum_w[v][j] min_v = min(min_v, min_w[v][j]) v = dest[v][j] rem >>= 1 print(sum_v, min_v) ```
instruction
0
77,927
13
155,854
No
output
1
77,927
13
155,855
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,031
13
156,062
"Correct Solution: ``` from collections import deque n,u,v=map(int,input().split()) graph=[[] for i in range(n)] for i in range(n-1): a,b=map(int,input().split()) a-=1;b-=1 graph[a].append(b) graph[b].append(a) Q=deque([v-1]) Vert=[[0,0] for i in range(n)] visited=[False]*n visited[v-1]=True while Q: V=Q.popleft() visited[V]=True for i in graph[V]: if visited[i]:continue if i == V:continue Vert[i][0]=Vert[V][0]+1 Q.append(i) visited=[False]*n visited[u-1]=True Q.append(u-1) while Q: V=Q.popleft() visited[V]=True for i in graph[V]: if visited[i]:continue if i == V:continue Vert[i][1]=Vert[V][1]+1 Q.append(i) ans=0 for i in Vert: if i[0]>i[1]: if i[0]>ans: ans=i[0] print(ans-1) ```
output
1
78,031
13
156,063
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,032
13
156,064
"Correct Solution: ``` import sys sys.setrecursionlimit(200000) n,u,v = map(int,input().split()) edge = [[] for i in range(n+1)] distt = [0 for i in range(n+1)] dista = [0 for i in range(n+1)] for i in range(n-1): a, b = map(int, input().split()) edge[a].append(b) edge[b].append(a) def tdfs(x, last = -1): for to in edge[x]: if(to == last):continue distt[to] = distt[x] + 1 tdfs(to, x) def adfs(x, last = -1): for to in edge[x]: if(to == last):continue dista[to] = dista[x] + 1 adfs(to, x) tdfs(u) adfs(v) ans = 0 for i in range(1, n+1): if distt[i] >= dista[i]:continue l = distt[i] k = dista[i] - distt[i] ans = max(ans, k - 1 + l) print(ans) ```
output
1
78,032
13
156,065
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,033
13
156,066
"Correct Solution: ``` import sys sys.setrecursionlimit(10**7) N, u, v = map(int, input().split()) u -= 1 v -= 1 graph = [[] for _ in range(N)] for i in range(N-1): a, b = map(int, input().split()) a -= 1 b -= 1 graph[a].append(b) graph[b].append(a) dist = [] def dfs(v, depth=0, parent=-1): global dist dist[v] = depth for u in graph[v]: # 親には行かないようにする if u == parent: continue dfs(u, depth + 1, v) def calc_dist(s): global dist dist = [0 for _ in range(N)] dfs(s) return dist distS = calc_dist(u) distT = calc_dist(v) mx = 0 for i in range(N): if distS[i] < distT[i]: mx = max(mx, distT[i]) print(mx - 1) ```
output
1
78,033
13
156,067
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,034
13
156,068
"Correct Solution: ``` from collections import deque N,u,v=map(int,input().split()) u-=1 v-=1 L=[list() for _ in range(N)] for _ in range(N-1): a,b=map(int,input().split()) a-=1 b-=1 L[a].append(b) L[b].append(a) q=deque([(v,0)]) T=[-1]*N A=[-1]*N while q: p,x=q.pop() A[p]=x for to in L[p]: if A[to]==-1: q.append((to,x+1)) q=deque([(u,0)]) while q: p,x=q.pop() T[p]=x for to in L[p]: if T[to]==-1 and A[to]>x+1: q.append((to,x+1)) Tcan=[i for i,x in enumerate(T) if x!=-1] cnt,gi=max([(A[i], i) for i in Tcan]+[(0,0)]) if cnt<=1: print(0) exit() print(A[gi]-1) ```
output
1
78,034
13
156,069
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,035
13
156,070
"Correct Solution: ``` import sys input = sys.stdin.readline # 再帰上限を引き上げる sys.setrecursionlimit(10**6) # G:graph, cr:current node, seen:is seen?, dist:out;each distance def dfs(G,cr,seen,dist): seen[cr] = 1 for i in G[cr]: #G[cr]から行ける各頂点へ if seen[i] == 0: #まだ通っていなかったら dist[i] = dist[cr]+1 dfs(G,i,seen,dist) n,u,v = (int(x) for x in input().split()) u,v = u-1,v-1 a = [[] for i in range(n)] for i in range(n-1): # 配列indexは0開始だからinputは-1 l,m = (int(x)-1 for x in input().split()) a[l].append(m) a[m].append(l) # v視点のdistを調べる dist_u = [0]*n dist_v = [0]*n dfs(a,u,[0]*n,dist_u) # u視点のdistを調べる dfs(a,v,[0]*n,dist_v) for i in range(n): if dist_u[i] >= dist_v[i]: # vが追いつける距離なら dist_v[i] = -1 print(max(dist_v) - 1) ```
output
1
78,035
13
156,071
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,036
13
156,072
"Correct Solution: ``` import sys sys.setrecursionlimit(10**5) N,u,v=map(int,input().split()) du,dv=[0]*-~N,[0]*-~N T=[list() for i in range(-~N)] def dfs(p,t,v,d): d[v]=t for i in T[v]: if i!=p: dfs(v,t+1,i,d) for i in range(N-1): a,b=map(int,input().split()) T[a].append(b) T[b].append(a) dfs(0,0,u,du) dfs(0,0,v,dv) c=0 for i in range(1,-~N): if len(T[i])==1 and i!=v: if du[i]<dv[i]: c=max(c,~-dv[i]) print(c) ```
output
1
78,036
13
156,073
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,037
13
156,074
"Correct Solution: ``` from collections import deque n, u, v = map(int,input().split()) tree = [[] for _ in range(n+1)] for _i in range(n-1): a, b = map(int, input().split()) tree[a].append(b) tree[b].append(a) def solve(x): visit = [-1 for _ in range(n+1)] visit[x] = 0 q = deque([x]) while q: p = q.popleft() for i in tree[p]: if visit[i] < 0: visit[i] = visit[p]+1 q.append(i) return visit visit_a = solve(v) visit_t = solve(u) x, y = [], [] for i in range(1, n+1): if visit_a[i] >= visit_t[i]: x.append(visit_a[i]) y.append(visit_t[i]) p = x.index(max(x)) print(x[p]-1) ```
output
1
78,037
13
156,075
Provide a correct Python 3 solution for this coding contest problem. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5
instruction
0
78,038
13
156,076
"Correct Solution: ``` import sys sys.setrecursionlimit(10**9) f=lambda:map(int,input().split()) n,st,sa=f() st-=1 sa-=1 g=[[] for _ in range(n)] for _ in range(n-1): a,b=f() g[a-1].append(b-1) g[b-1].append(a-1) def dfs(v,p=-1,d=0): l[v]=d for c in g[v]: if c==p: continue dfs(c,v,d+1) def dist(s): global l l=[0]*n dfs(s) return l lt=dist(st) la=dist(sa) m=0 for i in range(n): if lt[i]<la[i]: m=max(m,la[i]) print(m-1) ```
output
1
78,038
13
156,077
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` n,u,v = map(int, input().split( )) u-=1 v-=1 Tr = [[] for _ in range(n)] for i in range(n-1): ai,bi = map(int, input().split( )) ai -=1 bi-=1 Tr[ai].append(bi) Tr[bi].append(ai) Dep_u = [-1] *n Dep_v = [-1] *n Dep_u[u] = 0 Dep_v[v] = 0 from collections import deque ##bfs2回が簡明 def bfs(L,x): Q = deque() Q.append(x) while Q: y = Q.popleft() for z in Tr[y]: if L[z] == -1: L[z] = L[y] + 1 Q.append(z) bfs(Dep_u,u) bfs(Dep_v,v) ans = 0###0から for i in range(n): if Dep_v[i]>Dep_u[i]: ans = max(ans,Dep_v[i]-1)###v print(ans) ```
instruction
0
78,039
13
156,078
Yes
output
1
78,039
13
156,079
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` n, u, v = map(int, input().split()) u -= 1 v -= 1 g = [[] for _ in range(n)] for i in range(n-1): a, b = map(int, input().split()) a, b = a-1, b-1 g[a].append(b) g[b].append(a) from collections import deque q = deque() q.append(u) t = [-1]*n t[u] = 0 while q: x = q.popleft() for new_x in g[x]: if t[new_x] == -1: t[new_x] = t[x]+1 q.append(new_x) q = deque() q.append(v) a = [-1]*n a[v] = 0 while q: x = q.popleft() for new_x in g[x]: if a[new_x] == -1: a[new_x] = a[x]+1 q.append(new_x) max_ = 0 for i in range(n): if t[i] < a[i]: max_ = max(max_, a[i]) print(max_-1) ```
instruction
0
78,040
13
156,080
Yes
output
1
78,040
13
156,081
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` from collections import deque N, T, A, *AB = map(int, open(0).read().split()) E = [[] for _ in range(N + 1)] for a, b in zip(*[iter(AB)] * 2): E[a].append(b) E[b].append(a) takahashi = [-1] * (N + 1) takahashi[T] = 0 Q = deque([T]) while Q: a = Q.popleft() for b in E[a]: if takahashi[b] != -1: continue takahashi[b] = takahashi[a] + 1 Q.append(b) aoki = [-1] * (N + 1) aoki[A] = 0 Q = deque([A]) while Q: a = Q.popleft() for b in E[a]: if aoki[b] != -1: continue aoki[b] = aoki[a] + 1 Q.append(b) ma = 0 for t, a in zip(takahashi[1:], aoki[1:]): if t < a: ma = max(ma, a) print(ma - 1) ```
instruction
0
78,041
13
156,082
Yes
output
1
78,041
13
156,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` n,x,y=map(int,input().split()) s=[[]for i in range(n+1)] for i in range(n-1): a,b=map(int,input().split()) s[a].append(b) s[b].append(a) p=[float("INF")for i in range(n+1)] q=[float("INF")for i in range(n+1)] p[x]=0 q[y]=0 c=set([x]) while c: d=set() for i in c: for j in s[i]: if p[j]>p[i]+1: p[j]=p[i]+1 d.add(j) c=d c=set([y]) while c: d=set() for i in c: for j in s[i]: if q[j]>q[i]+1: q[j]=q[i]+1 d.add(j) c=d a=0 for i in range(1,n+1): if p[i]<q[i]: a=max(a,q[i]-1) print(a) ```
instruction
0
78,042
13
156,084
Yes
output
1
78,042
13
156,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` n, u, v = [int(x) for x in input().split()] adj = [[] for _ in range(0, n + 1)] vs = [False] * (n + 1) for i in range(1, n): a, b = [int(x) for x in input().split()] adj[a].append(b) adj[b].append(a) def dfs(i, d, n): if i == d: return n vs[i] = True for j in adj[i]: r = dfs(j, d, n + 1) if r is not None: return r vs[i] = False return None r = dfs(u, v, 0) print(r) ```
instruction
0
78,043
13
156,086
No
output
1
78,043
13
156,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` from collections import deque import numpy as np n,u,v = map(int, input().split()) neighbors = [[] for _ in range(n)] for _ in range(n-1): a,b = map(int, input().split()) a -= 1 b -= 1 neighbors[a].append(b) neighbors[b].append(a) vds = [-1]*n qp = deque([]) qp.append(v-1) vds[v-1] = 0 while qp: now = qp.pop() for nxt in neighbors[now]: if vds[nxt] == -1: qp.appendleft(nxt) vds[nxt] = vds[now] + 1 uds = [-1]*n qp.append(u-1) uds[u-1] = 1 while qp: now = qp.pop() for nxt in neighbors[now]: if uds[nxt] == -1 and nxt != v-1: qp.appendleft(nxt) uds[nxt] = 1 vds = np.array(vds) uds = np.array(uds) anls = vds*uds print(np.amax(anls)-1) ```
instruction
0
78,044
13
156,088
No
output
1
78,044
13
156,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` N, u, v = map(int, input().split()) points = [list(map(int, input().split())) for i in range(N - 1)] tree = [[] for i in range(N + 1)] for a, b in points: tree[a].append(b) tree[b].append(a) def bfs(node): sta = [node] dis = [-1] * (N + 1) dis[node] = 0 while sta: no = sta.pop(0) tempD = dis[no] + 1 for tempN in tree[no]: if dis[tempN] < 0: dis[tempN] = tempD sta.append(tempN) else: return dis disU = bfs(u) disV = bfs(v) ans = 0 for u_, v_ in zip(disU[1:], disV[1:]): if u_ < v_: ans = max(u_, v_) - 1 else: print(ans) ```
instruction
0
78,045
13
156,090
No
output
1
78,045
13
156,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally. Takahashi is standing at Vertex u, and Aoki is standing at Vertex v. Now, they will play a game of tag as follows: * 1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex. * 2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex. * 3. Go back to step 1. Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible. Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy. It can be proved that the game is bound to end. Constraints * 2 \leq N \leq 10^5 * 1 \leq u,v \leq N * u \neq v * 1 \leq A_i,B_i \leq N * The given graph is a tree. Input Input is given from Standard Input in the following format: N u v A_1 B_1 : A_{N-1} B_{N-1} Output Print the number of moves Aoki will perform before the end of the game. Examples Input 5 4 1 1 2 2 3 3 4 3 5 Output 2 Input 5 4 5 1 2 1 3 1 4 1 5 Output 1 Input 2 1 2 1 2 Output 0 Input 9 6 1 1 2 2 3 3 4 4 5 5 6 4 7 7 8 8 9 Output 5 Submitted Solution: ``` import sys from collections import defaultdict as dd import heapq input = sys.stdin.readline N, u, v = map(int, input().split()) e = dd(list) for _ in range(N - 1): a, b = map(int, input().split()) e[a].append((b, 1)) e[b].append((a, 1)) class dijkstra: def __init__(self, n, e): self.e = e self.n = n def path(self, s, t): d = [float("inf")] * (self.n + 1) vis = set() d[s] = 0 h = [s] while not t in vis and len(h): v = heapq.heappop(h) v1 = v % (10 ** 6) v0 = v // (10 ** 6) if v1 in vis: continue vis.add(v1) for p in self.e[v1]: d[p[0]] = min(d[p[0]], d[v1] + p[1]) if p[0] in vis: continue heapq.heappush(h, d[p[0]] * (10 ** 6) + p[0]) return d d = dijkstra(N, e) p = d.path(v, 0) pp = d.path(u, 0) #print(p) #print(pp) res = -1 ee = dd(list) for k in e.keys(): for x in e[k]: if p[x[0]] > pp[x[0]]: ee[k].append((x[0], 1)) dd = dijkstra(N, ee) ppp = dd.path(u, 0) #print(ppp) t = 0 for i in range(1, N + 1): if ppp[i] != float("inf"): if ppp[i] > res: res = max(ppp[i], p[i]) t = i for x in e[t]: if p[x[0]] == pp[x[0]]: res += 1 break print(res) ```
instruction
0
78,046
13
156,092
No
output
1
78,046
13
156,093
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,263
13
156,526
"Correct Solution: ``` # -*- coding: utf-8 -*- # AC (http://judge.u-aizu.ac.jp/onlinejudge/review.jsp?rid=1850894#1) V, E, r = list(map(int, input().split())) es = [list(map(int, input().split())) for i in range(E)] # 以下を参考にさせていただきました # http://ti2236.hatenablog.com/entry/2012/12/07/175841 # Chu-Liu/Edmonds' Algorithm # 最小全域有向木を再帰的に求める # V: 頂点数, es: 辺集合, r: 根となる頂点番号 def solve(V, es, r): # まず、頂点vに入るものの内、コストが最小の辺を選択する # minsには(最小コスト, その辺のもう一方の頂点番号) mins = [(10**18, -1)]*V for s, t, w in es: mins[t] = min(mins[t], (w, s)) # 根となる頂点rからは何も選択しない mins[r] = (-1, -1) group = [0]*V # 縮約した際に割り振られる頂点番号 comp = [0]*V # 縮約されたgroupか cnt = 0 # 縮約した後の頂点数 # 縮約処理 used = [0]*V for v in range(V): if not used[v]: chain = [] # 探索時に通った頂点番号リスト cur = v # 現在探索中の頂点 while not used[cur] and cur!=-1: chain.append(cur) used[cur] = 1 cur = mins[cur][1] if cur!=-1: # 探索が根の頂点rで終了しなかった場合 # chain = [a0, a1, ..., a(i-1), ai, ..., aj], cur = aiの場合 # a0, ..., a(i-1)までは固有の番号を割り振り # ai, ..., ajまでは閉路であるため、同じ番号を割り振るようにする cycle = 0 for e in chain: group[e] = cnt if e==cur: # 閉路を見つけた cycle = 1 comp[cnt] = 1 if not cycle: cnt += 1 if cycle: cnt += 1 else: # 探索が根の頂点rで終了した場合 # --> 閉路を持たないため、1つずつ新しい番号を割り振っていく for e in chain: group[e] = cnt cnt += 1 # cntがV => 閉路が存在せず、有向木が構築できている if cnt == V: # 根の頂点r以外が選択した辺のコストの和を返す # (+1はmins[r][0]の-1を打ち消すやつ) return sum(map(lambda x:x[0], mins)) + 1 # 閉路が含まれていた場合 # --> 閉路に含まれている頂点が選択した辺のコストの和を計算 res = sum(mins[v][0] for v in range(V) if v!=r and comp[group[v]]) # 再帰的に計算するグラフが持つ辺を構築 n_es = [] for s, t, w in es: # 追加する辺に繋がる頂点は、新しいグラフの頂点番号に変換する gs = group[s]; gt = group[t] if gs == gt: # 同じ閉路に含まれている頂点どうしをつなぐ辺の場合 # --> 追加しない continue if comp[gt]: # ある閉路に含まれている頂点vに入る辺の場合 # --> その辺のコストから、閉路においてその頂点vに入っていた辺のコストを引く n_es.append((gs, gt, w - mins[t][0])) else: # その他 --> 何もせず追加 n_es.append((gs, gt, w)) # 再帰的に求めた最小コストと、さっき計算したコストresを足したものを返す return res + solve(cnt, n_es, group[r]) print(solve(V, es, r)) ```
output
1
78,263
13
156,527
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,264
13
156,528
"Correct Solution: ``` from collections import defaultdict from itertools import chain nv, ne, r = map(int, input().split()) in_edges = defaultdict(set) out_edges = defaultdict(set) while ne: s, t, w = map(int, input().split()) in_edges[t].add((w, s)) out_edges[s].add((w, t)) ne -= 1 def chu_liu_edmond(vertices, cycle_cost): global in_edges, out_edges, nv, r total_cost = cycle_cost prev_v = {v: None for v in vertices} next_vs = {v: set() for v in vertices} for t in vertices: if t == r: continue min_in_w, min_in_s = min(in_edges[t]) total_cost += min_in_w prev_v[t] = min_in_s next_vs[min_in_s].add(t) visited = {r} queue = set(next_vs[r]) while queue: t = queue.pop() visited.add(t) queue.update(next_vs[t]) cycles = [] for i in vertices: if i in visited: continue cycle_vertices = set() while i not in visited: visited.add(i) cycle_vertices.add(i) i = prev_v[i] # Branched single path from cycle if i not in cycle_vertices: continue # Current cycle_vertices are not necessarily cycle (may contain branch from cycle) cycle_vertices, j = {i}, prev_v[i] while j != i: cycle_vertices.add(j) j = prev_v[j] cycles.append(cycle_vertices) if not cycles: return total_cost for cycle in cycles: vertices.difference_update(cycle) vertices.add(nv) for v in cycle: prev_e_cost = min(in_edges[v])[0] cycle_cost += prev_e_cost for w, t in out_edges[v]: if t in vertices: out_edges[nv].add((w, t)) in_edges[t].remove((w, v)) in_edges[t].add((w, nv)) for w, s in in_edges[v]: if s in vertices: new_w = w - prev_e_cost in_edges[nv].add((new_w, s)) out_edges[s].remove((w, v)) out_edges[s].add((new_w, nv)) del in_edges[v] del out_edges[v] nv += 1 return chu_liu_edmond(vertices, cycle_cost) print(chu_liu_edmond(set(range(nv)), 0)) ```
output
1
78,264
13
156,529
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,265
13
156,530
"Correct Solution: ``` # AOJ GRL_2_B # http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_2_B import sys from heapq import heappush, heappop V, E, r = list(map(int, input().split())) Edge = [list(map(int, input().split())) for _ in range(0, E)] def solve(V, Edge, r): if V <= 1: return 0 q = [[] for _ in range(0, V)] for s, t, w in Edge: heappush(q[t], (w, s)) M = [(0, -1) for _ in range(0, V)] for t in range(0, V): if t != r: w, s = heappop(q[t]) M[t] = (w, s) used = [False for _ in range(0, V)] hist = [] cycle = [] for t in range(0, V): w, s = M[t] if s == -1 or used[t] == True: continue if used[t] == False: used[t] = True hist += [t] tt = s while used[tt] == False: used[tt] = True hist += [tt] w, s = M[tt] if s == -1: hist = [] break tt = s if used[tt] == True and s != -1 and 0 < len(hist): try: k = hist.index(tt) cycle = hist[k:] except: continue finally: pass break if len(cycle) == 0: return sum(m[0] for m in M) parent = min(cycle) rn = [0 for _ in range(0, V)] k = 0 for t in range(0, V): if k == parent: k += 1 if t in cycle: rn[t] = parent else: rn[t] = k k += 1 Vp = V - len(cycle) + 1 Ep = [] for s, t, w in Edge: if s in cycle: if t in cycle: continue else: Ep += [[parent, rn[t], w]] else: if t in cycle: Ep += [[rn[s], parent, w - M[t][0]]] else: Ep += [[rn[s], rn[t], w]] r = rn[r] return solve(Vp, Ep, r) + sum(M[t][0] for t in cycle) print(solve(V, Edge, r)) ```
output
1
78,265
13
156,531
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,266
13
156,532
"Correct Solution: ``` from collections import defaultdict nv, ne, r = map(int, input().split()) in_edges = defaultdict(set) out_edges = defaultdict(set) while ne: s, t, w = map(int, input().split()) in_edges[t].add((w, s)) out_edges[s].add((w, t)) ne -= 1 def chu_liu_edmond(vertices, cycle_cost): global in_edges, out_edges, nv, r total_cost = cycle_cost prev_v = defaultdict(int) next_vs = defaultdict(set) for t in vertices: if t == r: continue min_in_w, min_in_s = min(in_edges[t]) total_cost += min_in_w prev_v[t] = min_in_s next_vs[min_in_s].add(t) visited = {r} queue = set(next_vs[r]) while queue: t = queue.pop() visited.add(t) queue.update(next_vs[t]) cycles = [] for i in vertices: if i in visited: continue cycle_vertices = set() while i not in visited: visited.add(i) cycle_vertices.add(i) i = prev_v[i] # Branched single path from cycle if i not in cycle_vertices: continue # Current cycle_vertices are not necessarily cycle only (may contain branch) cycle_vertices, j = {i}, prev_v[i] while j != i: cycle_vertices.add(j) j = prev_v[j] cycles.append(cycle_vertices) if not cycles: return total_cost for cycle in cycles: vertices.difference_update(cycle) vertices.add(nv) for v in cycle: prev_e_cost = min(in_edges[v])[0] cycle_cost += prev_e_cost for w, t in out_edges[v]: if t in vertices: out_edges[nv].add((w, t)) in_edges[t].remove((w, v)) in_edges[t].add((w, nv)) for w, s in in_edges[v]: if s in vertices: new_w = w - prev_e_cost in_edges[nv].add((new_w, s)) out_edges[s].remove((w, v)) out_edges[s].add((new_w, nv)) del in_edges[v] del out_edges[v] nv += 1 return chu_liu_edmond(vertices, cycle_cost) print(chu_liu_edmond(set(range(nv)), 0)) ```
output
1
78,266
13
156,533
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,267
13
156,534
"Correct Solution: ``` import heapq from typing import List, Optional def _find_cycle(incoming_edges: List[List[int]], root: int) -> Optional[List[int]]: in_tree = [False] * v_num in_tree[root] = True for e in incoming_edges: if e: S = [] S.append(e[2]) while True: p = incoming_edges[S[-1]][1] if in_tree[p]: while S: in_tree[S.pop()] = True break elif p in S: return S[S.index(p):] else: S.append(p) return None def _contract_cycle(digraph: List[List[List[int]]], cycle_node: List[int], root: int) -> None: super_node = cycle_node[0] for edges in digraph: if edges: min_weight = edges[0][0] for e in edges: e[0] -= min_weight if e[1] in cycle_node: e[1] = super_node if e[2] in cycle_node: e[2] = super_node contracted_edges: List[List[int]] = [] for n in cycle_node: for e in digraph[n]: if e[1] != super_node: heapq.heappush(contracted_edges, e) digraph[n].clear() digraph[super_node] = contracted_edges def edmonds_branching(digraph: List[List[List[int]]], root: int, weight: int) -> int: min_incoming_edges: List[List[int]] = [[]] * v_num for edges in digraph: if edges: min_edge = edges[0] min_incoming_edges[min_edge[2]] = min_edge weight += min_edge[0] C = _find_cycle(min_incoming_edges, root) if not C: return weight else: _contract_cycle(digraph, C, r) return edmonds_branching(digraph, root, weight) if __name__ == "__main__": v_num, e_num, r = map(lambda x: int(x), input().split()) G: List[List[List[int]]] = [[] for i in range(v_num)] for _ in range(e_num): s, t, w = map(lambda x: int(x), input().split()) if t != r: heapq.heappush(G[t], [w, s, t]) print(edmonds_branching(G, r, 0)) ```
output
1
78,267
13
156,535
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,268
13
156,536
"Correct Solution: ``` def get_cycle(pre, nxt, root): cycles, checked = [], set() # root?????£????????????????????????????????§????????????????????? checked |= {root} que = nxt[root][:] while que: root_linked = que.pop() checked |= {root_linked} if nxt[root_linked]: que.extend(nxt[root_linked]) for i in range(len(pre)): if i in checked: continue # ?????°????????§??????????????????????????? checking = set() while i not in checked: checked |= {i} checking |= {i} i = pre[i] if i not in checking: # ?????°???????????? continue # ??????????????´???????????????????????°??¨????????¢??? checking.clear() while i not in checking: checking |= {i} i = pre[i] cycles.append(checking) return cycles def cycle_cost(cycles, m): return sum(m[ci] for cycle in cycles for ci in cycle) from collections import defaultdict from itertools import product def chi_liu_edmonds(g, v, r): # ?°??????????????????????????±?????????? m = [float('inf')] * v pre = [None] * v for s, t in product(range(v), repeat=2): if g[s][t] < m[t]: m[t] = g[s][t] pre[t] = s nxt = defaultdict(list) for t, s in enumerate(pre): if s is not None: nxt[s].append(t) cycles = get_cycle(pre, nxt, r) # ??¨??¨??£?????????????????´??? if len(cycles) == 0: m[r] = 0 return sum(m) not_cycle = set(range(v)).difference(*cycles) #????´???????????????? abridger = {ni:i for i, ni in enumerate(not_cycle)} abridger.update({ci:i + len(not_cycle) for i, cycle in enumerate(cycles) for ci in cycle}) v_dash = len(not_cycle) + len(cycles) g_dash = [[float('inf')] * v_dash for _ in range(v_dash)] for s, t in product(range(v), repeat=2): s_dash, t_dash = abridger[s], abridger[t] if s_dash != t_dash: d = g[s][t] if t in not_cycle else g[s][t] - g[pre[t]][t] if g_dash[s_dash][t_dash] > d: g_dash[s_dash][t_dash] = d return chi_liu_edmonds(g_dash, v_dash, abridger[r]) + cycle_cost(cycles, m) from sys import stdin readline = stdin.readline v, e, r = map(int, readline().split()) g = [[float('inf')] * v for _ in range(v)] for _ in range(e): s, t, d = map(int, readline().split()) if t == r: continue g[s][t] = d print(chi_liu_edmonds(g, v, r)) ```
output
1
78,268
13
156,537
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,269
13
156,538
"Correct Solution: ``` # Edige Weighted Digraph from collections import namedtuple WeightedEdge = namedtuple('WeightedEdge', ('src', 'dest', 'weight')) class Digraph: def __init__(self, v): self.v = v self._edges = [[] for _ in range(v)] def add(self, edge): self._edges[edge.src].append(edge) def adj(self, v): return self._edges[v] def edges(self): for es in self._edges: for e in es: yield e def mca_chu_liu_edmonds(graph, s): def select_edges(): es = [None] * graph.v for v in range(graph.v): for e in graph.adj(v): w = e.dest if w == s: continue if es[w] is None or e.weight < es[w].weight: es[w] = e return es def find_cycle(es): vs = [0 for _ in range(graph.v)] for e in es: if e is None: continue vs[e.src] += 1 leaves = [v for v, c in enumerate(vs) if c == 0] while leaves: leaf, *leaves = leaves if es[leaf] is not None: w = es[leaf].src vs[w] -= 1 if vs[w] == 0: leaves.append(w) cycle = [] for v, c in enumerate(vs): if c > 0: cycle.append(v) u = es[v].src while u != v: cycle.append(u) u = es[u].src break return cycle def contract(es, vs): vvs = [] vv = 0 c = graph.v - len(vs) for v in range(graph.v): if v in vs: vvs.append(c) else: vvs.append(vv) vv += 1 g = Digraph(c+1) for v in range(graph.v): for e in graph.adj(v): if e.src not in vs or e.dest not in vs: v = vvs[e.src] w = vvs[e.dest] weight = e.weight if e.dest in vs: weight -= es[e.dest].weight e = WeightedEdge(v, w, weight) g.add(e) return g, vvs[s] edges = select_edges() cycle = find_cycle(edges) if cycle: g, ss = contract(edges, cycle) return mca_chu_liu_edmonds(g, ss) + sum(edges[v].weight for v in cycle) else: return sum(e.weight for e in edges if e is not None) def run(): v, e, r = [int(i) for i in input().split()] graph = Digraph(v) for _ in range(e): s, t, w = [int(i) for i in input().split()] graph.add(WeightedEdge(s, t, w)) print(mca_chu_liu_edmonds(graph, r)) if __name__ == '__main__': run() ```
output
1
78,269
13
156,539
Provide a correct Python 3 solution for this coding contest problem. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11
instruction
0
78,270
13
156,540
"Correct Solution: ``` # Acceptance of input import sys file_input = sys.stdin v_num, e_num, r = map(int, file_input.readline().split()) G = [[] for i in range(v_num)] import heapq for line in file_input: s, t, w = map(int, line.split()) if t != r: heapq.heappush(G[t], [w, s, t]) # Edmonds' algorithm def find_cycle(incoming_edges, root): in_tree = [False] * v_num in_tree[root] = True for e in incoming_edges: if e: S = [] S.append(e[2]) while True: p = incoming_edges[S[-1]][1] if in_tree[p]: while S: in_tree[S.pop()] = True break elif p in S: return S[S.index(p):] # return nodes in a cycle else: S.append(p) return None def contract_cycle(digraph, cycle_node, root): super_node = cycle_node[0] for edges in digraph: if edges: min_weight = edges[0][0] for e in edges: e[0] -= min_weight if e[1] in cycle_node: e[1] = super_node if e[2] in cycle_node: e[2] = super_node contracted_edges = [] for n in cycle_node: for e in digraph[n]: if e[1] != super_node: heapq.heappush(contracted_edges, e) digraph[n].clear() digraph[super_node] = contracted_edges def edmonds_branching(digraph, root, weight): min_incoming_edges = [None] * v_num for edges in digraph: if edges: min_edge = edges[0] min_incoming_edges[min_edge[2]] = min_edge weight += min_edge[0] C = find_cycle(min_incoming_edges, root) if not C: return weight else: contract_cycle(digraph, C, r) return edmonds_branching(digraph, root, weight) # output print(edmonds_branching(G, r, 0)) ```
output
1
78,270
13
156,541
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 6 9 0 1 1 0 2 3 1 2 1 1 3 7 2 4 1 1 4 3 3 4 1 3 5 1 4 5 6 output: 5 """ import sys import heapq as hp WHITE, GRAY, BLACK = 0, 1, 2 def generate_adj_table(v_table): for each in v_table: v_from, v_to, edge_weight = map(int, each) init_adj_table[v_from][v_to] = edge_weight # init_adj_table[v_to][v_from] = edge_weight return init_adj_table def prim_span_tree(): distance[init_v] = root distance_heap = [] hp.heappush(distance_heap, (0, init_v)) while distance_heap: current_vertex = hp.heappop(distance_heap)[1] color[current_vertex] = BLACK for adj, cost in adj_table[current_vertex].items(): if color[adj] is not BLACK: if cost < distance[adj]: distance[adj] = cost parent[adj] = current_vertex color[adj] = GRAY hp.heappush(distance_heap, (cost, adj)) return distance if __name__ == '__main__': _input = sys.stdin.readlines() vertices, edges, root = map(int, _input[0].split()) v_info = map(lambda x: x.split(), _input[1:]) parent = [-1] * vertices distance = [float('inf')] * vertices color = [WHITE] * vertices init_v = 0 init_adj_table = tuple(dict() for _ in range(vertices)) adj_table = generate_adj_table(v_info) print(sum(prim_span_tree())) ```
instruction
0
78,271
13
156,542
No
output
1
78,271
13
156,543
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11 Submitted Solution: ``` import heapq as pq n,E,r = map(int, input().split()) M = [[] for i in range(n)] for i in range(E): s,t,w = map(int, input().split()) M[s].append([t,w]) def prim(r): color = [0] * n d = [float("inf")] * n d[r] = 0 H = [] pq.heappush(H, [0, r]) while H: u2,u1 = pq.heappop(H) color[u1] = 1 if d[u1] < u2: continue for v1, v2 in M[u1]: if color[v1] == 1: continue if d[v1] > v2: d[v1] = v2 pq.heappush(H, [d[v1], v1]) return sum(d) print(prim(r)) ```
instruction
0
78,272
13
156,544
No
output
1
78,272
13
156,545
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11 Submitted Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 output: 11 """ import sys import heapq as hp WHITE, GRAY, BLACK = 0, 1, 2 def generate_adj_table(v_table): for each in v_table: v_from, v_to, edge_weight = map(int, each) init_adj_table[v_from][v_to] = edge_weight # init_adj_table[v_to][v_from] = edge_weight return init_adj_table def prim_span_tree(): distance[init_v] = root distance_heap = [] hp.heappush(distance_heap, (0, init_v)) while distance_heap: current_vertex = hp.heappop(distance_heap)[1] color[current_vertex] = BLACK for adj, cost in adj_table[current_vertex].items(): if color[adj] is not BLACK: if cost < distance[adj]: distance[adj] = cost parent[adj] = current_vertex color[adj] = GRAY hp.heappush(distance_heap, (cost, adj)) return distance if __name__ == '__main__': _input = sys.stdin.readlines() vertices, edges, root = map(int, _input[0].split()) v_info = map(lambda x: x.split(), _input[1:]) parent = [-1] * vertices distance = [float('inf')] * vertices color = [WHITE] * vertices init_v = 0 init_adj_table = tuple(dict() for _ in range(vertices)) adj_table = generate_adj_table(v_info) print(sum(prim_span_tree())) ```
instruction
0
78,273
13
156,546
No
output
1
78,273
13
156,547
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find the sum of the weights of edges of the Minimum-Cost Arborescence with the root r for a given weighted directed graph G = (V, E). Constraints * 1 ≤ |V| ≤ 100 * 0 ≤ |E| ≤ 1,000 * 0 ≤ wi ≤ 10,000 * G has arborescence(s) with the root r Input |V| |E| r s0 t0 w0 s1 t1 w1 : s|E|-1 t|E|-1 w|E|-1 , where |V| is the number of vertices and |E| is the number of edges in the graph. The graph vertices are named with the numbers 0, 1,..., |V|-1 respectively. r is the root of the Minimum-Cost Arborescence. si and ti represent source and target verticess of i-th directed edge. wi represents the weight of the i-th directed edge. Output Print the sum of the weights the Minimum-Cost Arborescence. Examples Input 4 6 0 0 1 3 0 2 2 2 0 1 2 3 1 3 0 1 3 1 5 Output 6 Input 6 10 0 0 2 7 0 1 1 0 3 5 1 4 9 2 1 6 1 3 2 3 4 3 4 2 2 2 5 8 3 5 3 Output 11 Submitted Solution: ``` import heapq nv, ne, r = map(int, input().split()) edges = [set() for _ in range(nv)] while ne: s, t, w = map(int, input().split()) edges[s].add((w, t)) ne -= 1 cost = 0 queue = list(edges[r]) heapq.heapify(queue) visited = [False] * nv visited[r] = True while queue: edge_cost, t = heapq.heappop(queue) if visited[t]: continue visited[t] = True cost += edge_cost if all(visited): break for e in edges[t]: if not visited[e[1]]: heapq.heappush(queue, e) print(cost) ```
instruction
0
78,274
13
156,548
No
output
1
78,274
13
156,549
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected graph with n vertices numbered from 1 to n. Initially there are no edges. You are asked to perform some queries on the graph. Let last be the answer to the latest query of the second type, it is set to 0 before the first such query. Then the queries are the following: * 1~x~y (1 ≤ x, y ≤ n, x ≠ y) — add an undirected edge between the vertices (x + last - 1)~mod~n + 1 and (y + last - 1)~mod~n + 1 if it doesn't exist yet, otherwise remove it; * 2~x~y (1 ≤ x, y ≤ n, x ≠ y) — check if there exists a path between the vertices (x + last - 1)~mod~n + 1 and (y + last - 1)~mod~n + 1, which goes only through currently existing edges, and set last to 1 if so and 0 otherwise. Good luck! Input The first line contains two integer numbers n and m (2 ≤ n, m ≤ 2 ⋅ 10^5) — the number of vertices and the number of queries, respectively. Each of the following m lines contains a query of one of two aforementioned types. It is guaranteed that there is at least one query of the second type. Output Print a string, consisting of characters '0' and '1'. The i-th character should be the answer to the i-th query of the second type. Therefore the length of the string should be equal to the number of queries of the second type. Examples Input 5 9 1 1 2 1 1 3 2 3 2 1 2 4 2 3 4 1 2 4 2 3 4 1 1 3 2 4 3 Output 1010 Input 3 9 1 1 2 1 2 3 1 3 1 2 1 3 1 3 2 2 2 3 1 1 2 2 1 2 2 1 2 Output 1101 Note The converted queries in the first example are: * 1 1 2 * 1 1 3 * 2 3 2 * 1 3 5 * 2 4 5 * 1 2 4 * 2 3 4 * 1 2 4 * 2 5 4 The converted queries in the second example are: * 1 1 2 * 1 2 3 * 1 3 1 * 2 1 3 * 1 1 3 * 2 3 1 * 1 2 3 * 2 2 3 * 2 1 2 Submitted Solution: ``` n,m = list(map(int, input().split())) last = 0 string = '' ml = [] for i in range(m): x,y,z = [int(i) for i in input().split()] b = (y + last - 1) % n + 1 c = (z + last - 1) % n + 1 if x == 1: if b not in ml: ml.append(b) if c not in ml: ml.append(c) elif b in ml: if c in ml: ml.remove(b) ml.remove(c) elif x == 2: if b in ml and c in ml: last = 1 else: last = 0 string += str(last) print(string) ```
instruction
0
78,372
13
156,744
No
output
1
78,372
13
156,745
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given k-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints). Let's also define the value of a k-coloring as the sum of weights of saturated edges. Please calculate the maximum possible value of a k-coloring of the given tree. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 5 ⋅ 10^5) – the number of queries. The first line of each query contains two integers n and k (1 ≤ n, k ≤ 5 ⋅ 10^5) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^5) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree. It is guaranteed that sum of all n over all queries does not exceed 5 ⋅ 10^5. Output For each query print one integer — the maximum value of a k-coloring of the given tree. Example Input 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 Output 8 14 Note The tree corresponding to the first query in the example: <image> One of the possible k-colorings in the first example: (1), (1), (2), (2), then the 1-st and the 3-rd edges are saturated and the sum of their weights is 8. The tree corresponding to the second query in the example: <image> One of the possible k-colorings in the second example: (1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6), then the 1-st, 2-nd, 5-th and 6-th edges are saturated and the sum of their weights is 14. Submitted Solution: ``` import os import sys from collections import defaultdict def get_adj(edges): neighbors = defaultdict(set, {}) deg = [0] * (len(edges) + 2) for v1, v2, w in edges: deg[v1] += 1 deg[v2] += 1 neighbors[v1].add((v2, w)) neighbors[v2].add((v1, w)) return dict(neighbors), deg def solve(edges, k): if not edges: return 0 n = len(edges) + 1 adj, deg = get_adj(edges) dp = [[-1, -1] for _ in range(n + 1)] q = [[] for _ in range(n + 1)] root = 1 leaves = [node for node, d in adj.items() if len(d) == 1] for leaf in leaves: dp[leaf][0] = 0 dp[leaf][1] = 0 while leaves != [root]: new_leaves = [] for leaf in leaves: if leaf == root: continue parent, w = next(iter(adj[leaf])) q[parent].append((max(w + dp[leaf][1], dp[leaf][0]), dp[leaf][0])) adj[parent].remove((leaf, w)) if len(adj[parent]) + (parent == root) == 1: new_leaves.append(parent) diffs = sorted([x[0] - x[1] for x in q[parent]], reverse=True)[:k] s = sum(x[1] for x in q[parent]) a = sum(diffs[:-1]) dp[parent][0] = s + a + diffs[-1] dp[parent][1] = s + a leaves = new_leaves return max(dp[root]) solve([[1,2,2]], 6) def pp(input): T = int(input()) for t in range(T): n, k = map(int, input().strip().split()) edges = [tuple(map(int, input().strip().split())) for _ in range(n - 1)] print(solve(edges, k)) if "paalto" in os.getcwd(): from string_source import string_source, codeforces_parse pp(string_source("""9 9 3 7 4 10 6 8 1 1 3 6 2 4 10 2 9 1 5 4 9 3 6 5 1 2 5 2 6 1 2 2 2 4 1 2 8 7 7 4 3 2 6 5 1 3 2 3 3 5 7 7 1 10 1 2 9 3 9 3 2 6 2 1 8 7 10 1 5 9 3 4 2 1 3 6 7 3 9 3 6 3 1 2 3 6 3 2 1 4 4 2 10 3 5 2 3 1 5 2 6 5 1 2 9 8 4 7 7 4 6 2 2 9 9 2 3 5 5 3 3 8 2 2 2 1 1 1 4 4""")) x = """inputCopy 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 outputCopy 8 14""" for q, a in codeforces_parse(x): print("ANSWER") pp(string_source(q)) print("EXPECTED") print(a) print("----") else: pp(sys.stdin.readline) ```
instruction
0
78,373
13
156,746
No
output
1
78,373
13
156,747
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given k-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints). Let's also define the value of a k-coloring as the sum of weights of saturated edges. Please calculate the maximum possible value of a k-coloring of the given tree. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 5 ⋅ 10^5) – the number of queries. The first line of each query contains two integers n and k (1 ≤ n, k ≤ 5 ⋅ 10^5) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^5) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree. It is guaranteed that sum of all n over all queries does not exceed 5 ⋅ 10^5. Output For each query print one integer — the maximum value of a k-coloring of the given tree. Example Input 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 Output 8 14 Note The tree corresponding to the first query in the example: <image> One of the possible k-colorings in the first example: (1), (1), (2), (2), then the 1-st and the 3-rd edges are saturated and the sum of their weights is 8. The tree corresponding to the second query in the example: <image> One of the possible k-colorings in the second example: (1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6), then the 1-st, 2-nd, 5-th and 6-th edges are saturated and the sum of their weights is 14. Submitted Solution: ``` import sys input = sys.stdin.readline from collections import deque q=int(input()) for testcases in range(q): n,k=map(int,input().split()) E=[[] for i in range(n+1)] for j in range(n-1): x,y,w=map(int,input().split()) E[x].append((y,w)) E[y].append((x,w)) #print(E) USE=[0]*(n+1) Q=deque() Q.append(1) USE[1]=1 SORT=[1] P=[(0,0)]*(n+1) while Q: x=Q.pop() for to,w in E[x]: if USE[to]==0: USE[to]=1 SORT.append(to) Q.append(to) P[to]=(x,w) #print(SORT) SORT.reverse() VSC=[[] for i in range(n+1)] for s in SORT: pa,w=P[s] VSC[s].sort(key=lambda x:x[1]-x[0]) #print(VSC[s]) LEN=len(VSC[s]) SC0=0 for j in range(min(k,LEN)): SC0+=VSC[s][j][0] for j in range(k,LEN): SC0+=VSC[s][j][1] SC1=w for j in range(min(k-1,LEN)): SC1+=VSC[s][j][0] for j in range(k,LEN): SC1+=VSC[s][j][1] VSC[pa].append((SC1,SC0)) print(max(VSC[0][0][0],VSC[0][0][1])) ```
instruction
0
78,374
13
156,748
No
output
1
78,374
13
156,749
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given k-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints). Let's also define the value of a k-coloring as the sum of weights of saturated edges. Please calculate the maximum possible value of a k-coloring of the given tree. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 5 ⋅ 10^5) – the number of queries. The first line of each query contains two integers n and k (1 ≤ n, k ≤ 5 ⋅ 10^5) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^5) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree. It is guaranteed that sum of all n over all queries does not exceed 5 ⋅ 10^5. Output For each query print one integer — the maximum value of a k-coloring of the given tree. Example Input 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 Output 8 14 Note The tree corresponding to the first query in the example: <image> One of the possible k-colorings in the first example: (1), (1), (2), (2), then the 1-st and the 3-rd edges are saturated and the sum of their weights is 8. The tree corresponding to the second query in the example: <image> One of the possible k-colorings in the second example: (1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6), then the 1-st, 2-nd, 5-th and 6-th edges are saturated and the sum of their weights is 14. Submitted Solution: ``` import sys from collections import Counter readline = sys.stdin.readline def getpar(Edge, p): N = len(Edge) par = [0]*N par[0] = -1 par[p] -1 stack = [p] visited = set([p]) while stack: vn = stack.pop() for vf in Edge[vn]: if vf in visited: continue visited.add(vf) par[vf] = vn stack.append(vf) return par def topological_sort_tree(E, r): Q = [r] L = [] visited = set([r]) while Q: vn = Q.pop() L.append(vn) for vf in E[vn]: if vf not in visited: visited.add(vf) Q.append(vf) return L def getcld(p): res = [[] for _ in range(len(p))] for i, v in enumerate(p[1:], 1): res[v].append(i) return res Q = int(readline()) Ans = [None]*Q for qu in range(Q): N, K = map(int, input().split()) Edge = [[] for _ in range(N)] C = Counter() candi = [[] for _ in range(N)] for _ in range(N-1): a, b, c = map(int, sys.stdin.readline().split()) a -= 1 b -= 1 Edge[a].append(b) Edge[b].append(a) C[(a, b)] = c C[(b, a)] = c P = getpar(Edge, 0) L = topological_sort_tree(Edge, 0) dp1 = [0]*N dp2 = [0]*N for l in (L[::-1])[:-1]: p = P[l] res1 = 0 res2 = 0 if candi[l]: candi[l].sort(reverse = True) res1 = sum(candi[l][:K]) res2 = sum(candi[l][:K-1]) dp1[l] += res1 dp2[l] += res2 cnt = C[(l, p)] - dp1[l] + dp2[l] candi[p].append(max(0, cnt)) dp1[p] += dp1[l] dp2[p] += dp1[l] Ans[qu] = dp1[0] + sum(candi[0][:K]) print('\n'.join(map(str, Ans))) ```
instruction
0
78,375
13
156,750
No
output
1
78,375
13
156,751
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a weighted tree consisting of n vertices. Recall that a tree is a connected graph without cycles. Vertices u_i and v_i are connected by an edge with weight w_i. Let's define the k-coloring of the tree as an assignment of exactly k colors to each vertex, so that each color is used no more than two times. You can assume that you have infinitely many colors available. We say that an edge is saturated in the given k-coloring if its endpoints share at least one color (i.e. there exists a color that is assigned to both endpoints). Let's also define the value of a k-coloring as the sum of weights of saturated edges. Please calculate the maximum possible value of a k-coloring of the given tree. You have to answer q independent queries. Input The first line contains one integer q (1 ≤ q ≤ 5 ⋅ 10^5) – the number of queries. The first line of each query contains two integers n and k (1 ≤ n, k ≤ 5 ⋅ 10^5) — the number of vertices in the tree and the number of colors to assign to each vertex, respectively. Each of the next n - 1 lines describes an edge of the tree. Edge i is denoted by three integers u_i, v_i and w_i (1 ≤ u_i, v_i ≤ n, u_i ≠ v_i, 1 ≤ w_i ≤ 10^5) — the labels of vertices it connects and the weight of the edge. It is guaranteed that the given edges form a tree. It is guaranteed that sum of all n over all queries does not exceed 5 ⋅ 10^5. Output For each query print one integer — the maximum value of a k-coloring of the given tree. Example Input 2 4 1 1 2 5 3 1 2 3 4 3 7 2 1 2 5 1 3 4 1 4 2 2 5 1 2 6 2 4 7 3 Output 8 14 Note The tree corresponding to the first query in the example: <image> One of the possible k-colorings in the first example: (1), (1), (2), (2), then the 1-st and the 3-rd edges are saturated and the sum of their weights is 8. The tree corresponding to the second query in the example: <image> One of the possible k-colorings in the second example: (1, 2), (1, 3), (2, 4), (5, 6), (7, 8), (3, 4), (5, 6), then the 1-st, 2-nd, 5-th and 6-th edges are saturated and the sum of their weights is 14. Submitted Solution: ``` # -*- coding: utf-8 -*- from sys import stdin input = stdin.readline def graph(E): global G G = {} for v1, v2 in E: w = E[(v1, v2)] if v1 not in G: G[v1] = {v2:w} else: G[v1][v2] = w if v2 not in G: G[v2] = {v1:w} else: G[v2][v1] = w return G def Input(n): global A,Flag E = {} for _ in range(n-1): a,b,w = map(int,input().split()) a,b = min(a,b),max(a,b) E[a,b] = int(w) A = graph(E) Flag = [False]*(n + 1) def Ans(k): cout = 0 for i in sorted(A): F = list(A[i].items()) F.sort( key = lambda x: x[1], reverse= True) if Flag[i]: k1 = k - 1 else: k1 = k Flag[i] = True j = 0 for p in F: if j == k1 : break else: j += 1 cout += p[1] Flag[p[0]] = True Result.append(str(cout)) def main(): global Result,k Result=[] for _ in range(int(input())): n,k = map(int,input().split()) Input(n) Ans(k) print('\n'.join(Result)) if __name__ == '__main__': main() ```
instruction
0
78,376
13
156,752
No
output
1
78,376
13
156,753
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,641
13
157,282
Tags: dfs and similar, dp, trees Correct Solution: ``` mod=10**9+7 n=int(input()) edges=list(map(int,input().split())) colored=list(map(int,input().split())) childs=[[] for i in range(n)] for i in range(1,n): childs[edges[i-1]].append(i) dp = [[0,0] for i in range(n)] for i in range(n-1,-1,-1): prod=1 for child in childs[i]: prod*=sum(dp[child]) if colored[i]: dp[i]=[0,prod%mod] else: sec=0 for child in childs[i]: now=dp[child][1]*prod//sum(dp[child]) sec+=now dp[i]=[prod%mod,sec%mod] print(dp[0][1]) ```
output
1
78,641
13
157,283
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,642
13
157,284
Tags: dfs and similar, dp, trees Correct Solution: ``` MOD = 1000000007 n = int(input()) p = [int(x) for x in input().split()] x = [int(x) for x in input().split()] children = [[] for x in range(n)] for i in range(1,n): children[p[i-1]].append(i) #print(children) count = [(0,0) for i in range(n)] for i in reversed(range(n)): prod = 1 for ch in children[i]: prod *= count[ch][0]+count[ch][1] if x[i]: count[i] = (0,prod % MOD) else: tot = 0 for ch in children[i]: cur = count[ch][1]*prod // (count[ch][0]+count[ch][1]) tot += cur count[i] = (prod % MOD, tot % MOD) print(count[0][1]) ```
output
1
78,642
13
157,285
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,643
13
157,286
Tags: dfs and similar, dp, trees Correct Solution: ``` n = int(input()) edges = [int(x) for x in input().split()] color = [int(x) for x in input().split()] graph = [[] for _ in range(n)] for a,b in enumerate(edges): graph[a+1].append(b) graph[b].append(a+1) dp = [[0]*2 for _ in range(n)] visited = [0]*n stack = [0] while stack: v = stack[-1] visited[v] = -1 cn = 0 for u in graph[v]: if visited[u] is not 0: continue else: cn += 1 stack.append(u) if not cn: dp[v][0] = 1 dp[v][1] = 0 for u in graph[v]: if visited[u] is -1: continue dp[v][1] *= dp[u][0] dp[v][1] += dp[v][0] * dp[u][1] dp[v][0] *= dp[u][0] dp[v][1] %= 1000000007 dp[v][0] %= 1000000007 if color[v] is 1: dp[v][1] = dp[v][0] else: dp[v][0] += dp[v][1] dp[v][0] %= 1000000007 visited[v] = 1 stack.pop() # def dfs(v): # dp[v][0] = 1 # dp[v][1] = 0 # visited[v] = True # for u in graph[v]: # if visited[u] is True: # continue # dfs(u) # dp[v][1] *= dp[u][0] # dp[v][1] += dp[v][0] * dp[u][1] # dp[v][0] *= dp[u][0] # dp[v][1] %= 1000000007 # dp[v][0] %= 1000000007 # if color[v] is 1: # dp[v][1] = dp[v][0] # else: # dp[v][0] += dp[v][1] # dp[v][0] %= 1000000007 # dfs(0) ans = dp[0][1] print(ans) ```
output
1
78,643
13
157,287
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,644
13
157,288
Tags: dfs and similar, dp, trees Correct Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO,IOBase def main(): mod = 10**9+7 n = int(input()) path = [[] for _ in range(n)] for ind,i in enumerate(map(int,input().split())): path[i].append(ind+1) path[ind+1].append(i) col = list(map(int,input().split())) dp = [[1,0] for _ in range(n)] for i in range(n): dp[i][col[i]] = 1 dp[i][col[i]^1] = 0 # number of ways to construct subtree # no black vertex ; one black vertex st,poi,visi = [0],[0]*n,[1]+[0]*(n-1) while len(st): x,y = st[-1],path[st[-1]] if poi[x] != len(y) and visi[y[poi[x]]]: poi[x] += 1 if poi[x] == len(y): if not col[st.pop()]: dp[x][1] = (dp[x][1]*dp[x][0])%mod if len(st): if col[st[-1]]: dp[st[-1]][0] = 0 dp[st[-1]][1] = (dp[st[-1]][1]*sum(dp[x]))%mod else: dp[st[-1]][0] = (dp[st[-1]][0]*sum(dp[x]))%mod dp[st[-1]][1] = (dp[st[-1]][1]+dp[x][1]*pow(sum(dp[x]),mod-2,mod))%mod else: i = y[poi[x]] st.append(i) visi[i] = 1 poi[x] += 1 print(dp[0][1]) # Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self,file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd,max(os.fstat(self._fd).st_size,BUFSIZE)) self.newlines = b.count(b"\n")+(not b) ptr = self.buffer.tell() self.buffer.seek(0,2),self.buffer.write(b),self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd,self.buffer.getvalue()) self.buffer.truncate(0),self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self,file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s:self.buffer.write(s.encode("ascii")) self.read = lambda:self.buffer.read().decode("ascii") self.readline = lambda:self.buffer.readline().decode("ascii") sys.stdin,sys.stdout = IOWrapper(sys.stdin),IOWrapper(sys.stdout) input = lambda:sys.stdin.readline().rstrip("\r\n") if __name__ == "__main__": main() ```
output
1
78,644
13
157,289
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,645
13
157,290
Tags: dfs and similar, dp, trees Correct Solution: ``` import os import sys from io import BytesIO, IOBase from types import GeneratorType from collections import defaultdict BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") sys.setrecursionlimit(2*10**5) def bootstrap(f, stack=[]): def wrappedfunc(*args, **kwargs): if stack: return f(*args, **kwargs) else: to = f(*args, **kwargs) while True: if type(to) is GeneratorType: stack.append(to) to = next(to) else: stack.pop() if not stack: break to = stack[-1].send(to) return to return wrappedfunc @bootstrap def dfs(u): whites = 1 k = [] for j in adj[u]: res = yield dfs(j) k.append(res) whites *= (res[0] + res[1]) black = 0 for j in k: black += (j[1] * ((whites) // (j[0] + j[1]))) if color[u]: yield [0,whites%p] else: yield [whites%p,black%p] p=10**9+7 n=int(input()) b=list(map(int,input().split())) color=list(map(int,input().split())) adj=[[] for i in range(n)] for j in range(n-1): adj[b[j]].append(j+1) print(dfs(0)[1]) ```
output
1
78,645
13
157,291
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,646
13
157,292
Tags: dfs and similar, dp, trees Correct Solution: ``` from collections import UserDict class Tree(UserDict): def __init__(self, g): super().__init__() for name, value in enumerate(g, 1): self[value] = name def __setitem__(self, name, value): if name in self: if value is not None: self[name].add(value) self[value] = None else: if value is None: super().__setitem__(name, set()) else: super().__setitem__(name, {value}) self[value] = None if __name__ == '__main__': n = int(input()) tree = Tree(int(i) for i in input().split()) colors = [int(i) for i in input().split()] t = [()] * n def dfs(v): stack = [v] visited = set() while stack: v = stack.pop() if v not in visited: visited.add(v) stack.append(v) stack.extend(tree[v]) else: t[v] = (1, colors[v]) for u in tree[v]: t[v] = ( (t[v][0] * t[u][1] + t[v][0] * t[u][0] * (not colors[u])) % (10**9 + 7), (t[v][1] * t[u][1] + t[v][0] * t[u][1] * (not colors[v]) + t[v][1] * t[u][0] * (not colors[u])) % (10**9 + 7) ) dfs(0) print(t[0][1]) ```
output
1
78,646
13
157,293
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,647
13
157,294
Tags: dfs and similar, dp, trees Correct Solution: ``` from collections import UserDict class Tree(UserDict): def __init__(self, g): super().__init__() for name, value in enumerate(g, 1): self[value] = name def __setitem__(self, name, value): if name in self: if value is not None: self[name].add(value) self[value] = None else: if value is None: super().__setitem__(name, set()) else: super().__setitem__(name, {value}) self[value] = None if __name__ == '__main__': n = int(input()) tree = Tree(int(i) for i in input().split()) colors = [int(i) for i in input().split()] t = [()] * n def dfs(v): stack = [v] visited = set() while stack: v = stack.pop() if v not in visited: visited.add(v) stack.append(v) stack.extend(tree[v]) else: t[v] = (1, colors[v]) for u in tree[v]: t[v] = ( (t[v][0] * t[u][1] + t[v][0] * t[u][0] * (not colors[u])) % (10**9 + 7), (t[v][1] * t[u][1] + t[v][0] * t[u][1] * (not colors[v]) + t[v][1] * t[u][0] * (not colors[u])) % (10**9 + 7) ) dfs(0) print(t[0][1]) # Made By Mostafa_Khaled ```
output
1
78,647
13
157,295
Provide tags and a correct Python 3 solution for this coding contest problem. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27
instruction
0
78,648
13
157,296
Tags: dfs and similar, dp, trees Correct Solution: ``` MOD = 10**9 + 7 def topo_compute(childrens, colors, parents): def f(node, connected_to_black): if colors[node] == 1 and connected_to_black: return 0 children = childrens[node] if colors[node] == 1 or connected_to_black: ret = 1 for child in children: x = dp_conn[child] + dp_not_conn[child] x %= MOD ret *= x ret %= MOD return ret s = 1 prefix_prod = [] for child in children: x = dp_conn[child] + dp_not_conn[child] x %= MOD s *= x s %= MOD prefix_prod.append(s) s = 1 suffix_prod = [] for child in reversed(children): x = dp_conn[child] + dp_not_conn[child] x %= MOD s *= x s %= MOD suffix_prod.append(s) suffix_prod = list(reversed(suffix_prod)) ret = 0 for i in range(len(children)): pre = prefix_prod[i - 1] if i > 0 else 1 suf = suffix_prod[i + 1] if i + 1 < len(suffix_prod) else 1 x = pre * suf x %= MOD x *= dp_not_conn[children[i]] x %= MOD ret += x ret %= MOD return ret ######################## num_childrens = [len(x) for x in childrens] N = len(childrens) dp_conn = [None] * N dp_not_conn = [None] * N stack = [i for i in range(N) if num_childrens[i] == 0] while True: node = stack.pop() dp_conn[node] = f(node, True) dp_not_conn[node] = f(node, False) parent = parents[node] if parent is None: return dp_not_conn[node] num_childrens[parent] -= 1 if num_childrens[parent] == 0: stack.append(parent) def build_tree(d, root): childrens = [None] * len(d) parents = [None] * len(d) stack = [(root, None)] while len(stack) > 0: node, parent = stack.pop() children = [x for x in d[node] if x != parent] childrens[node] = children parents[node] = parent for child in children: stack.append((child, node)) return childrens, parents def main(): import sys n = sys.stdin.readline() n = int(n) p = map(int, sys.stdin.readline().split(" ")) d = {} for i in range(n): d[i] = [] for i, b in enumerate(p): a = i + 1 d[a].append(b) d[b].append(a) colors = map(int, sys.stdin.readline().split(" ")) colors = list(colors) for i in range(n - 1): line = sys.stdin.readline() if line == "": break a, b = map(int, line.split(" ")) d[a].append(b) d[b].append(a) childrens, parents = build_tree(d, 0) ans = topo_compute(childrens, colors, parents) print(ans) if __name__ == '__main__': main() ```
output
1
78,648
13
157,297
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27 Submitted Solution: ``` def main(): n = int(input()) g = [[] for _ in range(n)] for pos, val in enumerate(map(int, input().split())): g[pos + 1].append(val) g[val].append(pos + 1) colors = list(map(int, input().split())) visit = [0] * n b = [0] * n w = [0] * n def dfs(v, parent): if colors[v]: nonlocal b b[v] = 1 else: nonlocal w w[v] = 1 for u in g[v]: if u == parent: continue dfs(u, v) w0, b0 = 0, 0 # if attaching u w0 += w[u] * w[v] b0 += b[u] * w[v] + w[u] * b[v] # not attaching u w0 += w[v] * b[u] b0 += b[v] * b[u] nonlocal b nonlocal w w[v], b[v] = w0, b0 dfs(0, -1) print(b[0]) if __name__ == "__main__": main() ```
instruction
0
78,649
13
157,298
No
output
1
78,649
13
157,299
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27 Submitted Solution: ``` n = int(input()) l = list(map(int, input().split())) l.sort() ans = sum(l) for i in range(n-1): t = l.pop(0) ans += t ans += sum(l) print(ans) ```
instruction
0
78,650
13
157,300
No
output
1
78,650
13
157,301
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27 Submitted Solution: ``` n = int(input()) edges = [int(x) for x in input().split()] color = [int(x) for x in input().split()] graph = [[] for _ in range(n)] for a,b in enumerate(edges): graph[a+1].append(b) graph[b].append(a+1) dp = [[0]*2 for _ in range(n)] visited = [False for _ in range(n)] def dfs(v): dp[v][0] = 1 dp[v][1] = 0 visited[v] = True for u in graph[v]: if visited[u] is True: continue dfs(u) dp[v][1] *= dp[u][0] dp[v][1] += dp[v][0] * dp[u][1] dp[v][0] *= dp[u][0] dp[v][1] %= 1000000007 dp[u][1] %= 1000000007 if color[v] is 1: dp[v][1] = dp[v][0] else: dp[v][0] += dp[v][1] dp[v][1] %= 1000000007 dfs(0) ans = dp[0][1] print(ans) ```
instruction
0
78,651
13
157,302
No
output
1
78,651
13
157,303
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Appleman has a tree with n vertices. Some of the vertices (at least one) are colored black and other vertices are colored white. Consider a set consisting of k (0 ≤ k < n) edges of Appleman's tree. If Appleman deletes these edges from the tree, then it will split into (k + 1) parts. Note, that each part will be a tree with colored vertices. Now Appleman wonders, what is the number of sets splitting the tree in such a way that each resulting part will have exactly one black vertex? Find this number modulo 1000000007 (109 + 7). Input The first line contains an integer n (2 ≤ n ≤ 105) — the number of tree vertices. The second line contains the description of the tree: n - 1 integers p0, p1, ..., pn - 2 (0 ≤ pi ≤ i). Where pi means that there is an edge connecting vertex (i + 1) of the tree and vertex pi. Consider tree vertices are numbered from 0 to n - 1. The third line contains the description of the colors of the vertices: n integers x0, x1, ..., xn - 1 (xi is either 0 or 1). If xi is equal to 1, vertex i is colored black. Otherwise, vertex i is colored white. Output Output a single integer — the number of ways to split the tree modulo 1000000007 (109 + 7). Examples Input 3 0 0 0 1 1 Output 2 Input 6 0 1 1 0 4 1 1 0 0 1 0 Output 1 Input 10 0 1 2 1 4 4 4 0 8 0 0 0 1 0 1 1 0 0 1 Output 27 Submitted Solution: ``` from collections import UserDict class Tree(UserDict): def __init__(self, g): super().__init__() for name, value in enumerate(g, 1): self[value] = name def __setitem__(self, name, value): if name in self: if value is not None: self[name].add(value) self[value] = None else: if value is None: super().__setitem__(name, set()) else: super().__setitem__(name, {value}) self[value] = None if __name__ == '__main__': n = int(input()) tree = Tree(int(i) for i in input().split()) colors = [int(i) for i in input().split()] t = [()] * n def dfs(v): t[v] = (1, colors[v]) for u in tree[v]: dfs(u) t[v] = ( t[v][0] * t[u][1] + t[v][0] * t[u][0] * (not colors[u]), t[v][1] * t[u][1] + t[v][0] * t[u][1] * (not colors[v]) + t[v][1] * t[u][0] * (not colors[u]) ) dfs(0) print(t[0][1]) ```
instruction
0
78,652
13
157,304
No
output
1
78,652
13
157,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You're given a tree with n vertices rooted at 1. We say that there's a k-ary heap of depth m located at u if the following holds: * For m = 1 u itself is a k-ary heap of depth 1. * For m > 1 vertex u is a k-ary heap of depth m if at least k of its children are k-ary heaps of depth at least m - 1. Denote dpk(u) as maximum depth of k-ary heap in the subtree of u (including u). Your goal is to compute <image>. Input The first line contains an integer n denoting the size of the tree (2 ≤ n ≤ 3·105). The next n - 1 lines contain two integers u, v each, describing vertices connected by i-th edge. It's guaranteed that the given configuration forms a tree. Output Output the answer to the task. Examples Input 4 1 3 2 3 4 3 Output 21 Input 4 1 2 2 3 3 4 Output 22 Note Consider sample case one. For k ≥ 3 all dpk will be equal to 1. For k = 2 dpk is 2 if <image> and 1 otherwise. For k = 1 dpk values are (3, 1, 2, 1) respectively. To sum up, 4·1 + 4·1 + 2·2 + 2·1 + 3 + 1 + 2 + 1 = 21. Submitted Solution: ``` def BFS(n, Adj): L = [(0, 0, -1)] Levels = [[] for l in range(n)] Parents = [-1 for v in range(n)] while L: u, l, p = L.pop() #print('{} at level {}'.format(u, l), end = ' ') Levels[l].append(u) for v in Adj[u]: if v != p: L.append( (v, l+1, u) ) Parents[v] = u #print(v, end = ' ') #print() return [level for level in Levels if level], Parents if __name__ == '__main__': n = int(input()) Adj = [ [] for v in range(n) ] for e in range(n-1): u, v = map( lambda x: int(x)-1, input().split() ) Adj[u].append(v) Adj[v].append(u) # DP[k][u] maximum depth of a k-ary heap rooted at u DP = [ [1 for u in range(n)] for k in range(n) ] Levels, Parents = BFS(n, Adj) for l in Levels[len(Levels)-2::-1]: for u in l: # T[k][d] number of k-ary children with depth k T = [ [0 for d in range(n)] for k in range(n)] for v in Adj[u]: if v != Parents[u]: for k in range(n): DP[k][u] = max(DP[k][u], DP[k][v]) T[k][ DP[k][v]-1 ] += 1 #for k in range(n): # print(k, end=': ') # for d in range(n): # print((d, T[k][d]), end= ' ') # print() for k in range(n-1, -1, -1): numchildren = 0 for d in range(n-1, -1, -1): numchildren += T[k][d] if numchildren > k: for k2 in range(k+1): DP[k2][u] = max(DP[k2][u], d+2) break #print(u, ':', [ DP[k][u] for k in range(n)]) print( sum( [ sum(DP[k]) for k in range(n)] ) ) ```
instruction
0
78,858
13
157,716
No
output
1
78,858
13
157,717
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 of n vertices. You are to select k (not necessarily distinct) simple paths in such a way that it is possible to split all edges of the tree into three sets: edges not contained in any path, edges that are a part of exactly one of these paths, and edges that are parts of all selected paths, and the latter set should be non-empty. Compute the number of ways to select k paths modulo 998244353. The paths are enumerated, in other words, two ways are considered distinct if there are such i (1 ≤ i ≤ k) and an edge that the i-th path contains the edge in one way and does not contain it in the other. Input The first line contains two integers n and k (1 ≤ n, k ≤ 10^{5}) — the number of vertices in the tree and the desired number of paths. The next n - 1 lines describe edges of the tree. Each line contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b) — the endpoints of an edge. It is guaranteed that the given edges form a tree. Output Print the number of ways to select k enumerated not necessarily distinct simple paths in such a way that for each edge either it is not contained in any path, or it is contained in exactly one path, or it is contained in all k paths, and the intersection of all paths is non-empty. As the answer can be large, print it modulo 998244353. Examples Input 3 2 1 2 2 3 Output 7 Input 5 1 4 1 2 3 4 5 2 1 Output 10 Input 29 29 1 2 1 3 1 4 1 5 5 6 5 7 5 8 8 9 8 10 8 11 11 12 11 13 11 14 14 15 14 16 14 17 17 18 17 19 17 20 20 21 20 22 20 23 23 24 23 25 23 26 26 27 26 28 26 29 Output 125580756 Note In the first example the following ways are valid: * ((1,2), (1,2)), * ((1,2), (1,3)), * ((1,3), (1,2)), * ((1,3), (1,3)), * ((1,3), (2,3)), * ((2,3), (1,3)), * ((2,3), (2,3)). In the second example k=1, so all n ⋅ (n - 1) / 2 = 5 ⋅ 4 / 2 = 10 paths are valid. In the third example, the answer is ≥ 998244353, so it was taken modulo 998244353, don't forget it! Submitted Solution: ``` import unittest from itertools import combinations def problem_h(n, k, b, c): # map roses to their weight # shop = zip(b, c) # roses stack by color if len(set(c)) == 1: return -1 whites, reds, oranges = list(), list(), list() for beauty, color in zip(b, c): if color == 'R': reds.append((color, beauty)) elif color == 'O': oranges.append((color, beauty)) else: whites.append((color, beauty)) # sort by their beauty # whites.sort(reverse=True) # oranges.sort(reverse=True) # reds.sort(reverse=True) # check if the monotone possible_compositions = [] whites_and_oranges = whites + oranges reds_and_oranges = reds + oranges w_o_combinations = list(combinations(whites_and_oranges, k)) r_o_combinations = list(combinations(reds_and_oranges, k)) for combination in w_o_combinations: if len(set([x[0] for x in combination])) == 1: continue possible_compositions.append(sum(x[1] for x in combination)) for combination in r_o_combinations: if len(set([x[0] for x in combination])) == 1: continue possible_compositions.append(sum(x[1] for x in combination)) try: return max(possible_compositions) except: # the number of possible compositions is 0, can not create bouquet return -1 def main(): n, k = [int(x) for x in input().split(' ')] b = [int(x) for x in input().split(' ')] c = input() print(problem_h(n, k, b, c)) class Codeforces926TestCase(unittest.TestCase): def test_example_1(self): self.assertEqual(11, problem_h(5, 3, [4, 3, 4, 1, 6], 'RROWW')) def test_example_2(self): self.assertEqual(-1, problem_h(5, 2, [10, 20, 14, 20, 11], 'RRRRR')) self.assertEqual(-1, problem_h(5, 2, [10, 20, 14, 20, 11], 'OOOOO')) self.assertEqual(-1, problem_h(5, 2, [10, 20, 14, 20, 11], 'WWWWW')) def test_example_3(self): self.assertEqual(28, problem_h(11, 5, [5, 6, 3, 2, 3, 4, 7, 5, 4, 5, 6], 'RWOORWORROW')) def test_not_possible(self): self.assertEqual(-1, problem_h(1, 1, [10], 'R')) self.assertEqual(-1, problem_h(1, 1, [10], 'O')) self.assertEqual(-1, problem_h(1, 1, [10], 'W')) if __name__ == '__main__': main() ```
instruction
0
78,859
13
157,718
No
output
1
78,859
13
157,719
Provide a correct Python 3 solution for this coding contest problem. There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them. Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are connected when one can reach from one of those points to the other by traveling only on the line segments. The number of the connected parts here is the number of the connected components in the graph with 2N vertices, corresponding to the 2N points, where every pair of vertices corresponding to two connected points is connected with an edge. Snuke has already decided K of the pairs, and the i-th of them is a pair of Point A_i and Point B_i. He is thinking of trying all possible ways to make the remaining N-K pairs and counting the number of the connected parts for each of those ways. Find the sum of those numbers of the connected parts. As the answer can be extremely large, compute the sum modulo 10^9+7. Constraints * 1 \leq N \leq 300 * 0 \leq K \leq N * 1 \leq A_i,B_i \leq 2N * A_1,\ A_2,\ ...\ A_K,\ B_1,\ B_2,\ ...\ B_K are all distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_K B_K Output Print the sum of the numbers of the connected parts for all possible ways to make the remaining N-K pairs. Examples Input 2 0 Output 5 Input 4 2 5 2 6 1 Output 6 Input 20 10 10 18 11 17 14 7 4 6 30 28 19 24 29 22 25 32 38 34 36 39 Output 27087418
instruction
0
78,940
13
157,880
"Correct Solution: ``` #! /usr/bin/env python # -*- coding: utf-8 -*- # vim:fenc=utf-8 # """ AGC028 D """ import itertools from functools import reduce from functools import lru_cache nn, k = map(int, input().split()) n = 2*nn abli = [] for i in range(k): a, b = map(int, input().split()) if a < b: abli.append((a, b)) else: abli.append((b, a)) flattenabli = itertools.chain.from_iterable(abli) cut = 10**9+7 unused = [1 for i in range(n+1)] for a in flattenabli: unused[a] -= 1 unusedacum = list(itertools.accumulate(unused)) def modInverse(a, b, divmod=divmod): r0, r1, s0, s1 = a, b, 1, 0 while r1 != 0: q, rtmp = divmod(r0, r1) stmp = s0-q*s1 r0, s0 = r1, s1 r1, s1 = rtmp, stmp return s0 % cut @lru_cache(maxsize=None) def doubleFactorial(x): return reduce(lambda y, z: y*z % cut, range(x, 0, -2)) @lru_cache(maxsize=None) def isSandwiched(i, j): return any(map(lambda k: abli[k][0] < i <= abli[k][1] <= j or i <= abli[k][0] <= j < abli[k][1], range(k))) nonSandwichedNums = [[] for i in range(n+1)] for i in range(1, n+1): for j in range(i+1, n+1): if not isSandwiched(i, j): nonSandwichedNums[i].append(j) def numberUnderterminedBetween(i, j): return unusedacum[j]-unusedacum[i-1] def pairCombinations(x): if x == 0: return 1 elif x % 2 == 0: return doubleFactorial(x-1) else: return 0 def g(i, j): x = numberUnderterminedBetween(i, j) return pairCombinations(x) undetermined = numberUnderterminedBetween(1, n) ggg = [[0]*(i+1) for i in range(n+1)] for i in range(1, n+1): for j in range(i+1, n+1): ggg[i].append(g(i, j)) ans = 0 dp = [[0]*(n+1) for i in range(n+1)] for i in range(1, n+1): for j in nonSandwichedNums[i]: gg = ggg[i][j] if gg != 0: dp[i][j] = (ggg[i][j]-sum([dp[i][kk]*ggg[kk+1][j] for kk in nonSandwichedNums[i] if kk < j])) % cut else: dp[i][j] = 0 ans = (ans + dp[i][j]*pairCombinations(undetermined-numberUnderterminedBetween(i, j))) % cut print(ans) ```
output
1
78,940
13
157,881
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are 2N points evenly spaced on the circumference of a circle. These points are numbered 1 to 2N in clockwise order, starting from some of them. Snuke will divide these points into N pairs, then for each pair, he will draw a line segment connecting the two points. After the line segments are drawn, two points are connected when one can reach from one of those points to the other by traveling only on the line segments. The number of the connected parts here is the number of the connected components in the graph with 2N vertices, corresponding to the 2N points, where every pair of vertices corresponding to two connected points is connected with an edge. Snuke has already decided K of the pairs, and the i-th of them is a pair of Point A_i and Point B_i. He is thinking of trying all possible ways to make the remaining N-K pairs and counting the number of the connected parts for each of those ways. Find the sum of those numbers of the connected parts. As the answer can be extremely large, compute the sum modulo 10^9+7. Constraints * 1 \leq N \leq 300 * 0 \leq K \leq N * 1 \leq A_i,B_i \leq 2N * A_1,\ A_2,\ ...\ A_K,\ B_1,\ B_2,\ ...\ B_K are all distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_K B_K Output Print the sum of the numbers of the connected parts for all possible ways to make the remaining N-K pairs. Examples Input 2 0 Output 5 Input 4 2 5 2 6 1 Output 6 Input 20 10 10 18 11 17 14 7 4 6 30 28 19 24 29 22 25 32 38 34 36 39 Output 27087418 Submitted Solution: ``` import itertools import sys import socket from functools import lru_cache, reduce import random import numpy as np import pprint if socket.gethostname() in ['N551J', 'F551C']: sys.stdin = open('d1.in') def read_int_list(): return list(map(int, input().split())) def read_int(): return int(input()) def read_str_list(): return input().split() def read_str(): return input() def solve2(N, K, A, B): n = 2 * N abli = [] for i in range(K): a, b = A[i], B[i] if a < b: abli.append((a, b)) else: abli.append((b, a)) flattenabli = itertools.chain.from_iterable(abli) cut = 10 ** 9 + 7 unused = [1 for i in range(n + 1)] for a in flattenabli: unused[a] -= 1 unusedacum = list(itertools.accumulate(unused)) def modInverse(a, b, divmod=divmod): r0, r1, s0, s1 = a, b, 1, 0 while r1 != 0: q, rtmp = divmod(r0, r1) stmp = s0 - q * s1 r0, s0 = r1, s1 r1, s1 = rtmp, stmp return s0 % cut @lru_cache(maxsize=None) def doubleFactorial(x): return reduce(lambda y, z: y * z % cut, range(x, 0, -2)) @lru_cache(maxsize=None) def isSandwiched(i, j): return any(map(lambda k: abli[k][0] < i <= abli[k][1] <= j or i <= abli[k][0] <= j < abli[k][1], range(K))) nonSandwichedNums = [[] for i in range(n + 1)] for i in range(1, n + 1): for j in range(i + 1, n + 1): if not isSandwiched(i, j): nonSandwichedNums[i].append(j) def numberUnderterminedBetween(i, j): return unusedacum[j] - unusedacum[i - 1] def pairCombinations(x): if x == 0: return 1 elif x % 2 == 0: return doubleFactorial(x - 1) else: return 0 def g(i, j): x = numberUnderterminedBetween(i, j) return pairCombinations(x) undetermined = numberUnderterminedBetween(1, n) ggg = [[0] * (i + 1) for i in range(n + 1)] for i in range(1, n + 1): for j in range(i + 1, n + 1): ggg[i].append(g(i, j)) ans = 0 dp = [[0] * (n + 1) for i in range(n + 1)] for i in range(1, n + 1): for j in nonSandwichedNums[i]: gg = ggg[i][j] if gg != 0: dp[i][j] = (ggg[i][j] - sum( [dp[i][kk] * ggg[kk + 1][j] for kk in nonSandwichedNums[i] if kk < j])) % cut else: dp[i][j] = 0 ans = (ans + dp[i][j] * pairCombinations(undetermined - numberUnderterminedBetween(i, j))) % cut return ans def solve1(N, K, a, b): n = 2 * N a = [u - 1 for u in a] b = [u - 1 for u in b] # print('N, n, K, a, b:', N, n, K, a, b) M = 10 ** 9 + 7 g = [0] * (n + 1) g[0] = 1 for x in range(2, n + 1, 2): g[x] = (x - 1) * g[x - 2] # Number of paired points inside the interval [i, j] x = [[0] * n for i in range(n)] # Number of paired points strcitly outside [i, j] y = [[0] * n for i in range(n)] ok = [[True] * n for i in range(n)] for i in range(n): for j in range(i + 1, n): for l in range(K): inside = (i <= a[l] <= j) + (i <= b[l] <= j) outside = 2 - inside ok[i][j] &= inside == 2 or outside == 2 x[i][j] += inside y[i][j] += outside # print() # print('x') # pprint.pprint(x) # print() # print('y') # pprint.pprint(y) # print() # print('ok') # pprint.pprint(ok) dp = [[0] * n for i in range(n)] for k in range(1, n): for i in range(n): j = i + k if j < n: if ok[i][j]: rem_x = j - i + 1 - x[i][j] rem_y = n - j + i - 1 - y[i][j] dp[i][j] += g[rem_x] * g[rem_y] dp[i][j] %= M for l in range(i + 1, j): rem_z = j - l - x[l + 1][j] dp[i][j] -= dp[i][l] * g[rem_z] * g[rem_y] dp[i][j] %= M # print() # print('dp') # pprint.pprint(dp) res = 0 for i in range(n): for j in range(i + 1, n): res += dp[i][j] res %= M return res def solve(): N, K = read_int_list() rows = [read_int_list() for i in range(K)] a = [] b = [] if rows: a, b = map(list, zip(*rows)) return solve1(N, K, a, b) def main(): res = solve() print(res) def check(): Nmax = 10 steps = 10000 best_N = None best_K = None best_a = None best_b = None for step in range(steps): N = random.randint(1, Nmax) K = random.randint(1, N) l = np.random.choice(range(1, 2 * N + 1), size=2 * K, replace=False) l = list(map(int, l)) a, b = l[:K], l[K:] output = solve1(N, K, a, b) expected = solve2(N, K, a, b) if output == expected: continue if best_N is None or (N, K, a, b) < (best_N, best_K, best_a, best_b): best_N, best_K, best_a, best_b = N, K, a, b print(N, K, a, b) print('output, expected:', output, ',', expected) if __name__ == '__main__': random.seed(2) # check() main() ```
instruction
0
78,941
13
157,882
No
output
1
78,941
13
157,883