message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a program you want to execute as a set of tasks organized in a dependency graph. The dependency graph is a directed acyclic graph: each task can depend on results of one or several other tasks, and there are no directed circular dependencies between tasks. A task can only be executed if all tasks it depends on have already completed. Some of the tasks in the graph can only be executed on a coprocessor, and the rest can only be executed on the main processor. In one coprocessor call you can send it a set of tasks which can only be executed on it. For each task of the set, all tasks on which it depends must be either already completed or be included in the set. The main processor starts the program execution and gets the results of tasks executed on the coprocessor automatically. Find the minimal number of coprocessor calls which are necessary to execute the given program. Input The first line contains two space-separated integers N (1 ≤ N ≤ 105) — the total number of tasks given, and M (0 ≤ M ≤ 105) — the total number of dependencies between tasks. The next line contains N space-separated integers <image>. If Ei = 0, task i can only be executed on the main processor, otherwise it can only be executed on the coprocessor. The next M lines describe the dependencies between tasks. Each line contains two space-separated integers T1 and T2 and means that task T1 depends on task T2 (T1 ≠ T2). Tasks are indexed from 0 to N - 1. All M pairs (T1, T2) are distinct. It is guaranteed that there are no circular dependencies between tasks. Output Output one line containing an integer — the minimal number of coprocessor calls necessary to execute the program. Examples Input 4 3 0 1 0 1 0 1 1 2 2 3 Output 2 Input 4 3 1 1 1 0 0 1 0 2 3 0 Output 1 Note In the first test, tasks 1 and 3 can only be executed on the coprocessor. The dependency graph is linear, so the tasks must be executed in order 3 -> 2 -> 1 -> 0. You have to call coprocessor twice: first you call it for task 3, then you execute task 2 on the main processor, then you call it for for task 1, and finally you execute task 0 on the main processor. In the second test, tasks 0, 1 and 2 can only be executed on the coprocessor. Tasks 1 and 2 have no dependencies, and task 0 depends on tasks 1 and 2, so all three tasks 0, 1 and 2 can be sent in one coprocessor call. After that task 3 is executed on the main processor.
instruction
0
83,911
13
167,822
Tags: dfs and similar, dp, graphs, greedy Correct Solution: ``` n, m = (int(x) for x in input().strip().split()) coproc = [int(x) for x in input().strip().split()] edges = [] for _ in range(m): edges.append((int(x) for x in input().strip().split())) inorder = [0] * n adj = [[] for _ in range(n)] for u, v in edges: adj[v].append(u) inorder[u] += 1 queue0 = [u for u in range(n) if inorder[u]==0 and not coproc[u]] queue1 = [u for u in range(n) if inorder[u]==0 and coproc[u]] res = 0 while len(queue0)>0 or len(queue1)>0: while queue0: next0 = [] for u in queue0: for v in adj[u]: inorder[v] -= 1 if inorder[v] == 0: if coproc[v]: queue1.append(v) else: next0.append(v) queue0 = next0 if queue1: res += 1 # coproc call while queue1: next1 = [] for u in queue1: for v in adj[u]: inorder[v] -= 1 if inorder[v] == 0: if coproc[v]: next1.append(v) else: queue0.append(v) queue1 = next1 print(res) ```
output
1
83,911
13
167,823
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,060
13
168,120
"Correct Solution: ``` import sys input = sys.stdin.readline """ 次数1のところにちょっかいを出すことを繰り返す。ダブルリーチが実現できたら勝ち。 """ N = int(input()) AB = [tuple(int(x)-1 for x in row.split()) for row in sys.stdin.readlines()] graph = [set() for _ in range(N)] for a,b in AB: graph[a].add(b) graph[b].add(a) deg = [len(x) for x in graph] deg_1 = set(i for i,x in enumerate(deg) if x == 1) bl = False while deg_1: x = deg_1.pop() y = graph[x].pop() graph[y].remove(x) for z in graph[y]: if z == x: continue graph[z].remove(y) if deg[z] == 1: bl = True break deg[z] -= 1 if deg[z] == 1: deg_1.add(z) if bl:break graph[y].clear() if y in deg_1: deg_1.remove(y) answer = 'First' if bl else 'Second' print(answer) ```
output
1
84,060
13
168,121
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,061
13
168,122
"Correct Solution: ``` N = int(input()) if N%2==1: print("First") exit() elif N==2: print("Second") exit() E = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) E[a].append(b) E[b].append(a) E_dim = [len(e) for e in E] E_set = [set(e) for e in E] q = [] for v, (dim, e) in enumerate(zip(E_dim, E)): if dim==1: for u in e: if E_dim[u] == 2: q.append(v) while q: v = q.pop() u = E_set[v].pop() if E_dim[u] == 1: print("Second") exit() E_set[u].remove(v) w = E_set[u].pop() E_set[w].remove(u) E_dim[w] -= 1 if E_dim[w] == 1: x = E_set[w].copy().pop() if E_dim[x] == 2: q.append(w) elif E_dim[w] == 2: for x in E_set[w]: if E_dim[x] == 1: q.append(x) print("First") ```
output
1
84,061
13
168,123
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,062
13
168,124
"Correct Solution: ``` from collections import deque n = int(input()) info = [list(map(int, input().split())) for i in range(n - 1)] tree = [[] for i in range(n)] for a, b in info: a -= 1 b -= 1 tree[a].append(b) tree[b].append(a) root = 0 par = {root: -1} q = deque([root]) topo = [] while q: v = q.popleft() topo.append(v) for nxt_v in tree[v]: if nxt_v in par: continue par[nxt_v] = v q.append(nxt_v) used = [False] * n for v in topo[::-1]: if used[v]: continue else: used[v] = True if par[v] == -1: print("First") exit() if used[par[v]]: print("First") exit() used[par[v]] = True print("Second") ```
output
1
84,062
13
168,125
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,063
13
168,126
"Correct Solution: ``` from collections import deque n=int(input()) E=[[] for i in range(n)] for i in range(n-1): a,b=map(int,input().split()) a=a-1 b=b-1 E[a].append(b) E[b].append(a) D=deque([0]) V=[0]*n V[0]=1 A=[0] P=[-1]*n while len(D)>0: x=D[0] D.popleft() for c in E[x]: if V[c]==0: D.append(c) A.append(c) P[c]=x V[c]=1 A=A[::-1] VV=[0]*n f=0 for c in A: if VV[c]==0: if P[c]==-1 or VV[P[c]]==1: f=1 else: VV[c]=1 VV[P[c]]=1 if f==1: print("First") else: print("Second") ```
output
1
84,063
13
168,127
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,064
13
168,128
"Correct Solution: ``` N = list(map(int,input().split()))[0] lis = [[] for i in range(N)] for a_i,b_i in [ map(int,input().split()) for _ in range(N-1) ]: lis[a_i-1].append(b_i-1) lis[b_i-1].append(a_i-1) while True: sumsum = 0 for x in lis: sumsum += sum(x) if sumsum == 0: print("Second") quit() for i in range(len(lis)): if len(lis[i]) == 1: b = lis[i][0] lis[i].remove(b) lis[b].remove(i) for c in lis[b]: lis[c].remove(b) if len(lis[c]) == 0: print("First") quit() lis[b] = [] ```
output
1
84,064
13
168,129
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,065
13
168,130
"Correct Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/agc014/tasks/agc014_d 白にしか隣接しない白を作れれば勝ちである 黒は、直前に置かれた白に対して対策するような動きをする羽目になる 距離2の葉の対があったら100%可能 ある時点での残りの森を考える(残りのどの点も黒が隣接していないとする) 葉に白を置く→葉において阻止 葉に隣接する点にしろを置く→葉において阻止 それ以外の点は、置いたら横に置くだけ(葉ではないので、隣接頂点が存在する) なので、十分性もおk? 距離2の葉が存在するかだけを判定すればよさそう そうでないとき、 奇数個の頂点の部分木が2つ以上存在したらおk? 検証してみるか """ N = int(input()) lis = [ [] for i in range(N) ] for i in range(N-1): a,b = map(int,input().split()) a -= 1 b -= 1 lis[a].append(b) lis[b].append(a) import sys sys.setrecursionlimit(500000) if N == 2: print ("Second") sys.exit() def dfs(v,p): if len(lis[v]) == 1: return 1,1 pl = 0 cnum = 0 oddc = 0 for nex in lis[v]: if nex != p: lf,nc = dfs(nex,v) pl += lf cnum += nc oddc += nc % 2 if (N-(cnum+1)) % 2 == 1: oddc += 1 if pl >= 2 or oddc >= 2: print ("First") sys.exit() return 0,cnum+1 fi = None for i in range(N): if len(lis[i]) > 1: fi = i break dfs(fi,fi) print ("Second") ```
output
1
84,065
13
168,131
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,066
13
168,132
"Correct Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**9) n=int(input()) Edges=[[] for _ in range(n)] for i in range(n-1): a,b=map(int,input().split()) a-=1 b-=1 Edges[a].append(b) Edges[b].append(a) while sum([len(Edges[i]) for i in range(n)]): for i in range(n): if len(Edges[i])==1: j=Edges[i][0] Edges[i].remove(j) Edges[j].remove(i) for k in Edges[j]: Edges[k].remove(j) if not Edges[k]: print('First') exit() Edges[j]=[] print('Second') ```
output
1
84,066
13
168,133
Provide a correct Python 3 solution for this coding contest problem. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second
instruction
0
84,067
13
168,134
"Correct Solution: ``` def examA(): A, B, C = LI() S = A+B+C cur = 0 for i in range(32): if A%2==1 or B%2==1 or C%2==1: break A = (S-A)//2 B = (S-B)//2 C = (S-C)//2 cur +=1 if cur==32: ans = -1 else: ans = cur print(ans) return def examB(): N, M = LI() cur = [0]*N for i in range(M): a, b = LI() cur[a-1] +=1 cur[b-1] +=1 ans = "YES" for j in cur: if j%2==1: ans = "NO" break print(ans) return def clear_maze(h,w,s,maze): # debug_print(maze) distance = [[inf]*w for _ in range(h)] def bfs(): queue = deque() queue.append(s) distance[s[0]][s[1]] = 0 while len(queue): y, x = queue.popleft() for i in range(4): nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i] if (0<= nx <w and 0<= ny <h and maze[ny][nx] != '#'): if distance[ny][nx]<=distance[y][x]+1: continue queue.append((ny, nx)) distance[ny][nx] = distance[y][x] + 1 return distance return bfs() def examC(): H, W, K = LI() A = [SI() for _ in range(H)] sx = W-1; sy = H-1 for i in range(H): for j in range(W): if A[i][j]=="S": sy = i; sx = j break if sy!=H-1 or sx!=W-1: break D = clear_maze(H,W,[sy,sx],A) # for v in D: # print(v) ans = inf for i in range(H): for j in range(W): if D[i][j]>K: continue cur = min((i+K-1)//K,(j+K-1)//K,(H+K-i-2)//K,(W+K-j-2)//K) ans = min(ans,cur+1) print(ans) return def examD(): def dfs(v, edges, n, visited, matched): for u in edges[v]: if u in visited: continue visited.add(u) if matched[u] == -1 or dfs(matched[u], edges, n, visited, matched): matched[u] = v return True return False N = I() V = [set()for _ in range(N)] for _ in range(N-1): a, b = LI() a -= 1; b -= 1 V[a].add(b) V[b].add(a) cnt = 0 matched = [-1] * N for s in range(N): cnt += dfs(s, V, N, set(), matched) #print(cnt) if cnt<N: print("First") else: print("Second") return import sys,copy,bisect,itertools,heapq,math from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,inf mod = 10**9 + 7 inf = 10**18 if __name__ == '__main__': examD() ```
output
1
84,067
13
168,135
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` from collections import defaultdict, deque, Counter from heapq import heappush, heappop, heapify import math import bisect import random from itertools import permutations, accumulate, combinations, product import sys import string from bisect import bisect_left, bisect_right from math import factorial, ceil, floor from operator import mul from functools import reduce sys.setrecursionlimit(2147483647) INF = 10 ** 13 def LI(): return list(map(int, sys.stdin.buffer.readline().split())) def I(): return int(sys.stdin.buffer.readline()) def LS(): return sys.stdin.buffer.readline().rstrip().decode('utf-8').split() def S(): return sys.stdin.buffer.readline().rstrip().decode('utf-8') def IR(n): return [I() for i in range(n)] def LIR(n): return [LI() for i in range(n)] def SR(n): return [S() for i in range(n)] def LSR(n): return [LS() for i in range(n)] def SRL(n): return [list(S()) for i in range(n)] def MSRL(n): return [[int(j) for j in list(S())] for i in range(n)] mod = 1000000007 n = I() G = [[] for _ in range(n)] for _ in range(n-1): a,b=LI() G[a-1]+=[b-1] G[b - 1] += [a - 1] def dfs(v, visited): """ :param v: X側の未マッチングの頂点の1つ :param visited: 空のsetを渡す(外部からの呼び出し時) :return: 増大路が見つかればTrue """ for u in G[v]: if u in visited: continue visited.add(u) if matched[u] == -1 or dfs(matched[u], visited): matched[u] = v return True return False cnt = 0 matched = [-1] * n for i in range(n): cnt += int(dfs(i, set())) if cnt == n: print("Second") else: print("First") ```
instruction
0
84,068
13
168,136
Yes
output
1
84,068
13
168,137
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` import sys sys.setrecursionlimit(100000) def dfs(v, p): result = sum(dfs(c, v) for c in edges[v] if c != p) if result >= 2: print('First') exit() return not result n = int(input()) if n % 2: print('First') exit() edges = [set() for _ in range(n)] for _ in range(n - 1): a, b = map(int, input().split()) a -= 1 b -= 1 edges[a].add(b) edges[b].add(a) print('First' if dfs(0, None) else 'Second') ```
instruction
0
84,069
13
168,138
Yes
output
1
84,069
13
168,139
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` import sys from collections import deque input = sys.stdin.buffer.readline N = int(input()) adj = [[] for _ in range(N+1)] for _ in range(N-1): a, b = map(int, input().split()) adj[a].append(b) adj[b].append(a) que = deque() que.append(1) seen = [0] * (N+1) seen[1] = 1 par = [0] * (N+1) child_num = [0] * (N+1) while que: v = que.popleft() for u in adj[v]: if seen[u] == 0: seen[u] = 1 par[u] = v child_num[v] += 1 que.append(u) seq = deque() for i in range(1, N+1): if child_num[i] == 0: seq.append(i) while seq: c = seq.pop() seen[c] = 0 if seen[par[c]] == 0: print('First') exit() seen[par[c]] = 0 child_num[par[par[c]]] -= 1 if child_num[par[par[c]]] == 0: seq.append(par[par[c]]) print('Second') ```
instruction
0
84,070
13
168,140
Yes
output
1
84,070
13
168,141
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` import sys input=sys.stdin.readline sys.setrecursionlimit(10**7) N=int(input()) edge=[[] for i in range(N)] for i in range(N-1): a,b=map(int,input().split()) edge[a-1].append(b-1) edge[b-1].append(a-1) ans=[0 for i in range(N)] subtreesize=[0 for i in range(N)] def dfs(v,pv): if edge[v]==[pv]: subtreesize[v]=1 ans[v]+=((N-1)%2==1) return subtreesize[v] a=0 size=1 for nv in edge[v]: if nv==pv: continue else: size+=dfs(nv,v) a+=(subtreesize[nv]%2==1) rest=N-size a+=(rest%2==1) ans[v]=a subtreesize[v]=size return size dfs(0,-1) check=[1]*N if check==ans: print("Second") else: print("First") ```
instruction
0
84,071
13
168,142
Yes
output
1
84,071
13
168,143
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` def examA(): A, B, C = LI() S = A+B+C cur = 0 for i in range(32): if A%2==1 or B%2==1 or C%2==1: break A = (S-A)//2 B = (S-B)//2 C = (S-C)//2 cur +=1 if cur==32: ans = -1 else: ans = cur print(ans) return def examB(): N, M = LI() cur = [0]*N for i in range(M): a, b = LI() cur[a-1] +=1 cur[b-1] +=1 ans = "YES" for j in cur: if j%2==1: ans = "NO" break print(ans) return def clear_maze(h,w,s,maze): # debug_print(maze) distance = [[inf]*w for _ in range(h)] def bfs(): queue = deque() queue.append(s) distance[s[0]][s[1]] = 0 while len(queue): y, x = queue.popleft() for i in range(4): nx, ny = x + [1, 0, -1, 0][i], y + [0, 1, 0, -1][i] if (0<= nx <w and 0<= ny <h and maze[ny][nx] != '#'): if distance[ny][nx]<=distance[y][x]+1: continue queue.append((ny, nx)) distance[ny][nx] = distance[y][x] + 1 return distance return bfs() def examC(): H, W, K = LI() A = [SI() for _ in range(H)] sx = W-1; sy = H-1 for i in range(H): for j in range(W): if A[i][j]=="S": sy = i; sx = j break if sy!=H-1 or sx!=W-1: break D = clear_maze(H,W,[sy,sx],A) # for v in D: # print(v) ans = inf for i in range(H): for j in range(W): if D[i][j]>K: continue cur = min((i+K-1)//K,(j+K-1)//K,(H+K-i-2)//K,(W+K-j-2)//K) ans = min(ans,cur+1) print(ans) return def bfs(n,e,fordfs): #点の数、スタートの点、有向グラフ W = [-1]*n #各点の状態量、最短距離とか,見たかどうかとか W[e] = 0 que = deque() que.append(e) while que: now = que.popleft() for ne in fordfs[now]: if W[ne] == -1: W[ne] = 0 que.append(ne) if len(fordfs[now])==1: W[ne] +=1 return W def examD(): N = I() V = [[]for _ in range(N)] for _ in range(N-1): a, b = LI() V[a-1].append(b-1) V[b-1].append(a-1) W = bfs(N,0,V) # print(W) ans = "Second" for i in W: if i>=2: ans = "First" break if N%2==1: ans = "First" print(ans) return import sys,copy,bisect,itertools,heapq,math from heapq import heappop,heappush,heapify from collections import Counter,defaultdict,deque def I(): return int(sys.stdin.readline()) def LI(): return list(map(int,sys.stdin.readline().split())) def LSI(): return list(map(str,sys.stdin.readline().split())) def LS(): return sys.stdin.readline().split() def SI(): return sys.stdin.readline().strip() global mod,inf mod = 10**9 + 7 inf = 10**18 if __name__ == '__main__': examD() ```
instruction
0
84,072
13
168,144
No
output
1
84,072
13
168,145
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 mod = 10**9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def main(): n = I() d = collections.defaultdict(set) for _ in range(n-1): a,b = LI() d[a].add(b) d[b].add(a) f = collections.defaultdict(bool) rf = False def g(s, h, m): t = list(d[s] - set([m]))[0] if len(d[t]) > 2: if h: if f[t]: return True f[t] = True else: d[t].remove(s) d[s].remove(t) rf = True return False if len(d[t]) == 1: return not h return g(t,not h,s) t = True gf = collections.defaultdict(bool) while t or rf: if rf: gf = collections.defaultdict(bool) f = collections.defaultdict(bool) rf = False t = False for k,v in list(d.items()): if len(v) == 1: if gf[k]: continue gf[k] = True res = g(k, True, -1) if res: return 'First' t = True return 'Second' print(main()) ```
instruction
0
84,073
13
168,146
No
output
1
84,073
13
168,147
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` N = int(input()) arr = [[] for _ in range(N + 1)] for _ in range(N - 1): a, b = map(int, input().split()) arr[a].append(b) arr[b].append(a) ans = 'Second' for i in range(1, N + 1): if ans == 'First': break tmp = arr[i] cnt1 = 0 cnt2 = 0 for v in tmp: if len(arr[v]) == 1: cnt1 += 1 else: cnt2 += 1 if 2 <= cnt1: ans = 'First' elif cnt1 == 1 and 3 <= cnt2: ans = 'First' elif 4 <= cnt2: ans = 'First' print(ans) ```
instruction
0
84,074
13
168,148
No
output
1
84,074
13
168,149
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is a tree with N vertices numbered 1 through N. The i-th of the N-1 edges connects vertices a_i and b_i. Initially, each vertex is uncolored. Takahashi and Aoki is playing a game by painting the vertices. In this game, they alternately perform the following operation, starting from Takahashi: * Select a vertex that is not painted yet. * If it is Takahashi who is performing this operation, paint the vertex white; paint it black if it is Aoki. Then, after all the vertices are colored, the following procedure takes place: * Repaint every white vertex that is adjacent to a black vertex, in black. Note that all such white vertices are repainted simultaneously, not one at a time. If there are still one or more white vertices remaining, Takahashi wins; if all the vertices are now black, Aoki wins. Determine the winner of the game, assuming that both persons play optimally. Constraints * 2 ≤ N ≤ 10^5 * 1 ≤ a_i,b_i ≤ N * a_i ≠ b_i * The input graph is a tree. Input Input is given from Standard Input in the following format: N a_1 b_1 : a_{N-1} b_{N-1} Output Print `First` if Takahashi wins; print `Second` if Aoki wins. Examples Input 3 1 2 2 3 Output First Input 4 1 2 2 3 2 4 Output First Input 6 1 2 2 3 3 4 2 5 5 6 Output Second Submitted Solution: ``` def main(): n = int(input()) ab = [list(map(int, input().split())) for _ in [0]*(n-1)] g = [[] for _ in [0]*n] [g[a-1].append(b-1) for a, b in ab] [g[b-1].append(a-1) for a, b in ab] for root in range(n): if len(g[root]) > 2: break else: if n % 2: print("First") else: print("Second") return d = [-1]*n # 根からの距離 d[root] = 0 q = [root] cnt = 0 while q: # BFS cnt += 1 qq = [] while q: i = q.pop() for j in g[i]: if d[j] == -1: d[j] = cnt qq.append(j) q = qq d2 = sorted([(j, i) for i, j in enumerate(d)])[::-1] end = [False]*n dp = [[] for _ in [0]*n] for _, i in d2: if len(g[i]) > 2: continue elif len(g[i]) == 1: dp[g[i][0]].append(1) if len(dp[g[i][0]]) > 1: end[g[i][0]] = True elif not end[i] and dp[i]: dist = dp[i][0] for j in g[i]: if d[j] < d[i]: dp[j].append(dist+1) dp = [[j % 2 for j in i] for i in dp] one = set() for j, i in enumerate(dp): if i.count(1) > 1: print("First") return elif i.count(1) == 1: one.add(j) for i in one: q = [i] visited = {i} cnt = 1 while q: qq = [] j = q.pop() for k in g[j]: if k in visited: continue visited.add(k) if len(g[k]) > 2: if cnt % 2 == 0: if k in one: print(i, k) print("First") return elif len(g[k]) == 2: qq.append(k) cnt += 1 q = qq print("Second") main() ```
instruction
0
84,075
13
168,150
No
output
1
84,075
13
168,151
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,092
13
168,184
"Correct Solution: ``` import sys stdin = sys.stdin def li(): return map(int, stdin.readline().split()) def li_(): return map(lambda x: int(x)-1, stdin.readline().split()) def lf(): return map(float, stdin.readline().split()) def ls(): return stdin.readline().split() def ns(): return stdin.readline().rstrip() def lc(): return list(ns()) def ni(): return int(stdin.readline()) def nf(): return float(stdin.readline()) from collections import deque def bfs(graph:list, node:int, start:int, k:int) -> list: # 未探索のノードは距離INF INF = float("inf") dist = [INF]*node # 始点ノードの距離を0とし、dfsのためのstackを作成 dist[start] = 0 que = deque([(0,start)]) # 未探索のノードをqueueに入れる # kより大きいの距離のものを数える cnt = 0 while que: cost, cur_node = que.popleft() if cost > k: cnt += 1 for nex_cost, nex_node in graph[cur_node]: if dist[nex_node] != INF: continue else: dist[nex_node] = dist[cur_node] + nex_cost que.append((dist[nex_node], nex_node)) return dist,cnt # 入力, グラフ作成 n,k = li() adj_list = [[] for _ in range(n)] for _ in range(n-1): a,b = li_() adj_list[a].append((1,b)) adj_list[b].append((1,a)) # bfs ans = n if k%2 == 0: for st in range(n): _, cnt = bfs(adj_list, n, st, k//2) ans = min(ans, cnt) else: for st in range(n): for cost, to in adj_list[st]: if to <= st: continue dist1, _ = bfs(adj_list, n, st, (k-1)//2) dist2, _ = bfs(adj_list, n, to, (k-1)//2) cnt = 0 for d1, d2 in zip(dist1, dist2): if min(d1,d2) > (k-1)//2: cnt += 1 ans = min(ans, cnt) print(ans) ```
output
1
84,092
13
168,185
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,093
13
168,186
"Correct Solution: ``` #!/usr/bin/env python3 import sys input = sys.stdin.readline from collections import deque n, k = map(int, input().split()) radius = k // 2 edge = [[] for _ in range(n)] uv = [] for _ in range(n - 1): a, b = map(int, input().split()) a -= 1; b -= 1 edge[a].append(b) edge[b].append(a) uv.append((a, b)) def dfs(p, v, d): ret = 0 st = [] st.append((p, v, d)) while st: p, v, d = st.pop() if d > radius: ret += 1 for nv in edge[v]: if nv == p: continue st.append((v, nv, d+1)) return ret ans = n if k % 2 == 0: for i in range(n): ret = dfs(-1, i, 0) ans = min(ans, ret) else: for u, v in uv: ret = dfs(u, v, 0) + dfs(v, u, 0) ans = min(ans, ret) print(ans) ```
output
1
84,093
13
168,187
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,094
13
168,188
"Correct Solution: ``` import sys reader = (s.rstrip() for s in sys.stdin) input = reader.__next__ sys.setrecursionlimit(10**9) n,k = map(int, input().split()) G = [[] for i in range(n)] edges = [] 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) edges.append((a,b)) cnt = [0] def search(cur, prev, depth, k): if depth > k: cnt[0] += 1 for to in G[cur]: if to != prev: search(to, cur, depth+1, k) ans = float("inf") # 点中心 if k % 2 == 0: for i in range(n): cnt = [0] search(i, -1, 0, k//2) ans = min(ans, cnt[0]) # 辺中心 else: for a, b in edges: cnt = [0] search(a, b, 0, k//2) search(b, a, 0, k//2) ans = min(ans, cnt[0]) print(ans) ```
output
1
84,094
13
168,189
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,095
13
168,190
"Correct Solution: ``` n, k = map(int, input().split()) adj = [[] for _ in range(n)] for _ in range(n-1): a, b = map(int, input().split()) adj[a-1].append(b-1) adj[b-1].append(a-1) def bfs(start, x): vis = [-1 for _ in range(n)] vis[start] = 0 s = [start] cnt = 0 while s: l = s.pop() cnt += 1 if vis[l] < x: for c in adj[l]: if vis[c] < 0: s.append(c) vis[c] = vis[l] + 1 return n - cnt def bfs2(start, nxt, x): vis = [-1 for _ in range(n)] vis[start] = 0 vis[nxt] = 0 s = [start, nxt] cnt = 0 while s: l = s.pop() cnt += 1 if vis[l] < x: for c in adj[l]: if vis[c] < 0: s.append(c) vis[c] = vis[l] + 1 return n - cnt ans = n-2 if k%2 == 0: for i in range(n): ans = min(ans, bfs(i, k//2)) else: for i in range(n): for j in adj[i]: ans = min(ans, bfs2(i, j, k//2)) print(ans) ```
output
1
84,095
13
168,191
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,096
13
168,192
"Correct Solution: ``` # coding:utf-8 import sys from collections import defaultdict, deque INF = float('inf') MOD = 10 ** 9 + 7 def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x) - 1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def II(): return int(sys.stdin.readline()) def SI(): return input() def main(): n, k = LI() G = defaultdict(list) AB = [LI_() for _ in range(n - 1)] for a, b in AB: G[a].append(b) G[b].append(a) def DFS(ss: list, t: int): q = deque() for s in ss: q.append((s, 0)) visited = [0] * n visited[ss[0]] = visited[ss[-1]] = 1 while q: v, d = q.pop() if d >= t: continue for to in G[v]: if visited[to]: continue visited[to] = 1 q.append((to, d + 1)) return n - sum(visited) # 木の性質 # 直径をdとした時 # dが偶数ならば,ある頂点vから他の頂点への距離がD/2となる頂点vが存在する # dが奇数ならば,ある辺eから他の頂点への距離が(D-1)/2となる辺eが存在する res = INF if k % 2: for a, b in AB: res = min(res, DFS([a, b], (k - 1) // 2)) else: for i in range(n): res = min(res, DFS([i], k // 2)) return res print(main()) ```
output
1
84,096
13
168,193
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,097
13
168,194
"Correct Solution: ``` from collections import deque N, K = map(int, input().split()) T = [[] for i in range(N)] E = [] for i in range(N-1): a, b = map(int, input().split()) a, b = a-1, b-1 T[a].append(b) T[b].append(a) E.append((a, b)) def bfs(n): visited = [False] * N dist = [0] * N queue = deque([n]) while queue: node = queue.pop() if visited[node]: continue visited[node] = True for n in T[node]: if not visited[n]: dist[n] = dist[node] + 1 queue.appendleft(n) return dist dist = [] for i in range(N): dist.append(bfs(i)) ans = float('inf') if K % 2 == 0: # 全ての頂点について全探索 for i in range(N): ans = min(ans, len(list(filter(lambda x: K / 2 < x, dist[i])))) else: # 全ての辺について全探索 for a, b in E: adist = [min(d1, d2) for d1, d2 in zip(dist[a], dist[b])] ans = min(ans, len(list(filter(lambda x: (K-1) / 2 < x, adist)))) print(ans) ```
output
1
84,097
13
168,195
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,098
13
168,196
"Correct Solution: ``` from collections import deque N, K, *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) def solve(a, b): D = [-1] * (N + 1) if a == b: Q = deque([a]) r = K // 2 D[a] = 0 else: Q = deque([a, b]) r = (K - 1) // 2 D[a] = D[b] = 0 cnt = len(Q) while Q: v = Q.popleft() d = D[v] + 1 if d > r: break for u in E[v]: if D[u] == -1: cnt += 1 D[u] = d Q.append(u) return N - cnt if K % 2 == 1: print(min(solve(a, b) for a, b in zip(*[iter(AB)] * 2))) else: print(min(solve(a, a) for a in range(1, N + 1))) ```
output
1
84,098
13
168,197
Provide a correct Python 3 solution for this coding contest problem. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0
instruction
0
84,099
13
168,198
"Correct Solution: ``` import sys read = sys.stdin.buffer.read readline = sys.stdin.buffer.readline readlines = sys.stdin.buffer.readlines from collections import deque N,K = map(int,readline().split()) m = map(int,read().split()) AB = list(zip(m,m)) graph = [[] for _ in range(N+1)] for a,b in AB: graph[a].append(b) graph[b].append(a) def F(a,b,K): INF = 10 ** 9 if a == b: # 中心が1点 q = deque([a]) r = K // 2 else: # 中心が辺 q = deque([a,b]) r = (K-1)//2 dist = [INF] * (N+1) for x in q: dist[x] = 0 pop = q.popleft; append = q.append cnt = len(q) while q: v = pop() dw = dist[v] + 1 if dw > r: break for w in graph[v]: if dist[w] == INF: cnt += 1 dist[w] = dw append(w) return N - cnt if K & 1: answer = min(F(a,b,K) for a,b in AB) else: answer = min(F(a,a,K) for a in range(1,N+1)) print(answer) ```
output
1
84,099
13
168,199
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` N,K=map(int,input().split()) L=[[]for i in range(N+1)] l=[] for i in range(N-1): a,b=map(int,input().split()) L[a].append(b) L[b].append(a) l.append([a,b]) ans=N if K%2==0: for i in range(1,N+1): C=[10000 for i in range(N+1)] Q=[[i,0]] cnt=0 for q in range(10000): if q==len(Q): break if C[Q[q][0]]==10000: C[Q[q][0]]=Q[q][1] cnt+=1 if Q[q][1]<K//2: for k in L[Q[q][0]]: if C[k]==10000: Q.append([k,Q[q][1]+1]) if N-cnt<ans: ans=N-cnt #print(i,C) print(max(0,ans)) else: if K==1: print(N-2) exit() for a,b in l: C1=[10000 for i in range(N+1)] C2=[10000 for i in range(N+1)] X=[[a,0]] for q in range(10000): if q==len(X): break if C1[X[q][0]]==10000: C1[X[q][0]]=X[q][1] if X[q][1]<(K-1)//2: for k in L[X[q][0]]: if C1[k]==10000: X.append([k,X[q][1]+1]) Y=[[b,0]] for q in range(10000): if q==len(Y): break if C2[Y[q][0]]==10000: C2[Y[q][0]]=Y[q][1] if Y[q][1]<(K-1)//2: for k in L[Y[q][0]]: if C2[k]==10000: Y.append([k,Y[q][1]+1]) cnt=0 for x in range(1,N+1): if C1[x]<=(K-1)//2 or C2[x]<=(K-1)//2: cnt+=1 #print(a,b,cnt,C1,C2) if N-cnt<ans: ans=N-cnt print(max(0,ans)) ```
instruction
0
84,100
13
168,200
Yes
output
1
84,100
13
168,201
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` import collections n,k=map(int,input().split()) g=[[] for _ in range(n+1)] e=[] for _ in range(n-1): a,b=map(int,input().split()) g[a].append(b) g[b].append(a) e.append((a,b)) ans=0 if k%2==0: for i in range(1,n+1): tmp=0 checked=[0]*(n+1) checked[i]=1 q=collections.deque() q.append((i,0)) while len(q)!=0: v,d=q.popleft() if d<=k//2: tmp+=1 else: break for u in g[v]: if checked[u]==0: checked[u]=1 q.append((u,d+1)) ans=max(ans,tmp) print(n-ans) if k%2==1: for v1,v2 in e: tmp=0 checked=[0]*(n+1) checked[v1]=1 checked[v2]=1 q=collections.deque() q.append((v1,0)) while len(q)!=0: v,d=q.popleft() if d<=k//2: tmp+=1 else: break for u in g[v]: if checked[u]==0: checked[u]=1 q.append((u,d+1)) checked=[0]*(n+1) checked[v1]=1 checked[v2]=1 q=collections.deque() q.append((v2,0)) while len(q)!=0: v,d=q.popleft() if d<=(k-1)//2: tmp+=1 else: break for u in g[v]: if checked[u]==0: checked[u]=1 q.append((u,d+1)) ans=max(ans,tmp) print(n-ans) ```
instruction
0
84,101
13
168,202
Yes
output
1
84,101
13
168,203
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` #!/usr/bin/env python3 import sys sys.setrecursionlimit(10**6) input = sys.stdin.readline from collections import deque n, k = map(int, input().split()) radius = k // 2 edge = [[] for _ in range(n)] uv = [] for _ in range(n - 1): a, b = map(int, input().split()) a -= 1; b -= 1 edge[a].append(b) edge[b].append(a) uv.append((a, b)) def dfs(p, v, d): ret = 0 for nv in edge[v]: if nv == p: continue ret += dfs(v, nv, d+1) if d > radius: return ret + 1 else: return ret ans = n if k % 2 == 0: for i in range(n): ret = dfs(-1, i, 0) ans = min(ans, ret) else: for u, v in uv: ret = dfs(u, v, 0) + dfs(v, u, 0) ans = min(ans, ret) print(ans) ```
instruction
0
84,102
13
168,204
Yes
output
1
84,102
13
168,205
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` """ Writer: SPD_9X2 https://atcoder.jp/contests/agc001/tasks/agc001_c 今度こそ通すぞ!! 制約が小さいので、各頂点に関して最短距離探索するぐらいはできる 直径の中央で全探索する? →距離K//2以内の頂点の数を数え、残りを取り除けばよい →その点を通らない長さK以上のパスは存在しえない Kが偶数なら、1点を中心(深さ0)とし探索 Kが奇数なら、隣接する2点を深さ0とすればよい 計算量はO(N**2) """ from collections import deque N,K = map(int,input().split()) AB = [] lis = [ [] for i in range(N) ] for i in range(N-1): A,B = map(int,input().split()) A -= 1 B -= 1 lis[A].append(B) lis[B].append(A) AB.append([A,B]) ans = float("inf") if K % 2 == 0: #偶数の場合 for st in range(N): q = deque([st]) dis = [float("inf")] * N dis[st] = 0 nps = 0 while len(q) > 0: now = q.popleft() nps += 1 if dis[now] < K//2: for nex in lis[now]: if dis[nex] > dis[now] + 1: dis[nex] = dis[now] + 1 q.append(nex) ans = min(ans , N - nps) else: for i in range(N-1): a,b = AB[i] q = deque([a,b]) dis = [float("inf")] * N dis[a] = 0 dis[b] = 0 nps = 0 while len(q) > 0: now = q.popleft() nps += 1 if dis[now] < K//2: for nex in lis[now]: if dis[nex] > dis[now] + 1: dis[nex] = dis[now] + 1 q.append(nex) ans = min(ans , N - nps) print (ans) ```
instruction
0
84,103
13
168,206
Yes
output
1
84,103
13
168,207
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` n,k = map(int,input().split()) import numpy as np INF = float("inf") edges = [[] for i in range(n)] ega = [] for i in range(n-1): a,b = map(int,input().split()) a = a-1 b = b-1 edges[a].append(b) edges[b].append(a) ega.append([a,b]) def dfs(v): visited = [] INF = float("inf") d=[INF for i in range(n)] q=[] d[v]=0 q.append(v) while len(q): v=q.pop() visited.append(v) for i in edges[v]: if i not in visited: d[i] = d[v] + 1 q.append(i) else: continue return d mi = INF table = [] for i in range(n): table.append(dfs(i)) if k%2 == 0: for i in range(n): disi = table[i] c = 0 for m in range(n): if disi[m] > k/2: c += 1 if mi>c: mi = c print(mi) else: for edge in ega: c = 0 if table[edge[0]] + table[edge[1]] > k-1: c += 1 if mi>c: mi = c print(mi) ```
instruction
0
84,104
13
168,208
No
output
1
84,104
13
168,209
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` import copy N, K = (int(i) for i in input().split()) G = [[] for i in range(N)] E = [] for i in range(N-1): A, B = (int(i) for i in input().split()) E.append((A-1, B-1)) G[A-1].append(B-1) G[B-1].append(A-1) def DFS(u, n, G): q = [u] v = [0]*N d = [0]*N while q: u1 = q.pop() v[u1] += 1 if d[u1] < n: for u2 in G[u1]: if not v[u2]: d[u2] = d[u1] + 1 q.append(u2) return sum(v) def DFS_E(u, v, n, G): q = [u, v] v = [0]*N d = [0]*N while q: u1 = q.pop() v[u1] += 1 if d[u1] < n: for u2 in G[u1]: if not v[u2] and u2 != v: d[u2] = d[u1] + 1 q.append(u2) return sum(v) if K % 2 == 0: ans = 0 for v in range(N): ans = max(ans, DFS(v, K//2, G)) print(N-ans) else: ans = 0 for u, v in E: ans = max(ans, DFS_E(u,v,K//2,G)) print(N-ans) ```
instruction
0
84,105
13
168,210
No
output
1
84,105
13
168,211
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` import sys input = sys.stdin.readline def main(): n, k = map(int, input().split()) T = [[] for _ in range(n)] E = [] for _ in range(n-1): a, b = map(int, input().split()) a -= 1 b -= 1 T[a].append(b) T[b].append(a) E.append((a, b)) d = k//2 def dfs(vs): dist = [-1]*n stack = [] cnt = 0 for v in vs: stack.append(v) dist[v] = 0 while stack: v = stack.pop() for nv in T[v]: if dist[nv] == -1: dist[nv] = dist[v] + 1 if dist[nv] > d: cnt += 1 if cnt >= ans: return cnt stack.append(nv) return cnt ans = n if k%2 == 0: for i in range(n): ans = min(ans, dfs([i])) else: for l in E: ans = min(ans, dfs(l)) print(ans) if __name__ == "__main__": main() ```
instruction
0
84,106
13
168,212
No
output
1
84,106
13
168,213
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given an undirected tree, let the distance between vertices u and v be the number of edges on the simple path from u to v. The diameter of a tree is the maximum among the distances between any two vertices. We will call a tree good if and only if its diameter is at most K. You are given an undirected tree with N vertices numbered 1 through N. For each i (1≦i≦N-1), there is an edge connecting vertices A_i and B_i. You want to remove zero or more vertices from the tree, so that the resulting tree is good. When a vertex is removed, all incident edges will also be removed. The resulting graph must be connected. Find the minimum number of vertices that you need to remove in order to produce a good tree. Constraints * 2≦N≦2000 * 1≦K≦N-1 * 1≦A_i≦N, 1≦B_i≦N * The graph defined by A_i and B_i is a tree. Input The input is given from Standard Input in the following format: N K A_1 B_1 A_2 B_2 : A_{N-1} B_{N-1} Output Print the minimum number of vertices that you need to remove in order to produce a good tree. Examples Input 6 2 1 2 3 2 4 2 1 6 5 6 Output 2 Input 6 5 1 2 3 2 4 2 1 6 5 6 Output 0 Submitted Solution: ``` import sys input = sys.stdin.readline n,k = map(int,input().split()) edge = [[] for i in range(n)] alledge = [] for i in range(n-1): a,b = map(int,input().split()) edge[a-1].append(b-1) edge[b-1].append(a-1) alledge.append([a-1,b-1]) if n==2: print(0) exit() def f(x): #c +=1 for e in edge[x]: #if e != y: #if c > d: # used[e] = 1 f(e) if k % 2 == 0: d = k//2 res = [] for i in range(n): used = [0]*n f(i,-1,0) res.append(sum(used)) print(min(res)) else: d = (k-1)//2 res = [] for e1 in alledge: used = [0]*n f(e1[0]) f(e1[1]) res.append(sum(used)) print(min(res)) ```
instruction
0
84,107
13
168,214
No
output
1
84,107
13
168,215
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,195
13
168,390
"Correct Solution: ``` # Python program to find articulation points in an undirected graph import sys sys.setrecursionlimit(100000) from collections import defaultdict # This class represents an undirected graph # using adjacency list representation class Graph: def __init__(self, vertices): self.V = vertices # No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that find articulation points using DFS traversal u --> The vertex to be visited next visited[] --> keeps tract of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree ap[] --> Store articulation points''' def APUtil(self, u, visited, ap, parent, low, disc): # Count of children in current node children = 0 # Mark the current node as visited and print it visited[u] = True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 # Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False: parent[v] = u children += 1 self.APUtil(v, visited, ap, parent, low, disc) # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more chilren. if parent[u] == -1 and children > 1: ap[u] = True # (2) If u is not root and low value of one of its child is mor # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: ap[u] = True # Update low value of u for parent function calls elif v != parent[u]: low[u] = min(low[u], disc[v]) # The function to do DFS traversal. It uses recursive APUtil() def AP(self): # Mark all the vertices as not visited # and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float("Inf")] * (self.V) low = [float("Inf")] * (self.V) parent = [-1] * (self.V) ap = [False] * (self.V) # To store articulation points # Call the recursive helper function # to find articulation points # in DFS tree rooted with vertex 'i' for i in range(self.V): if visited[i] == False: self.APUtil(i, visited, ap, parent, low, disc) for index, value in enumerate(ap): if value == True: print(index) def main(): V, E = map(int, input().split()) G = Graph(V) for _ in range(E): s, t = map(int, input().split()) G.addEdge(s, t) G.AP() if __name__ == "__main__": main() ```
output
1
84,195
13
168,391
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,196
13
168,392
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 4 0 1 1 2 2 3 3 4 output: 1 2 3 """ import sys sys.setrecursionlimit(int(1e6)) def generate_adj_table(_v_info): for v_detail in _v_info: source, target = map(int, v_detail) init_adj_table[source].append(target) init_adj_table[target].append(source) return init_adj_table def Tarjan(current, parents, visited, disc, low): global timer current_children_count = 0 visited[current] = True disc[current] = low[current] = timer timer += 1 for adj in adj_table[current]: if not visited[adj]: parents[adj] = current current_children_count += 1 Tarjan(adj, parents, visited, disc, low) low[current] = min(low[current], low[adj]) # current is root of DFS tree if parents[current] == -1 and current_children_count > 1: art_set.add(current) elif parents[current] != -1 and low[adj] >= disc[current]: art_set.add(current) elif adj != parents[current]: low[current] = min(low[current], disc[adj]) # print(timer, parents, visited, disc, low) return None def art_points(): parents = [-1] * vertices visited = [False] * vertices disc = [float('inf')] * vertices low = [float('inf')] * vertices for v in range(vertices): Tarjan(v, parents, visited, disc, low) return art_set if __name__ == '__main__': _input = sys.stdin.readlines() vertices, edges = map(int, _input[0].split()) v_info = map(lambda x: x.split(), _input[1:]) init_adj_table = tuple([] for _ in range(vertices)) adj_table = generate_adj_table(v_info) timer = 0 art_set = set() ans = art_points() if ans: print(*sorted(ans), sep='\n') ```
output
1
84,196
13
168,393
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,197
13
168,394
"Correct Solution: ``` #!/usr/bin/env python # -*- coding: utf-8 -*- """ input: 5 4 0 1 1 2 2 3 3 4 output: 1 2 3 """ import sys sys.setrecursionlimit(int(1e6)) def generate_adj_table(_v_info): for v_detail in _v_info: source, target = map(int, v_detail) init_adj_table[source].append(target) init_adj_table[target].append(source) return init_adj_table def Tarjan(current, parents, visited, disc, low): global timer current_children_count = 0 visited[current] = True disc[current] = low[current] = timer timer += 1 for adj in adj_table[current]: if not visited[adj]: parents[adj] = current current_children_count += 1 Tarjan(adj, parents, visited, disc, low) low[current] = min(low[current], low[adj]) # current is root of DFS tree if parents[current] == -1 and current_children_count > 1: art_set.add(current) elif parents[current] != -1 and low[adj] >= disc[current]: art_set.add(current) elif adj != parents[current]: low[current] = min(low[current], disc[adj]) return None def art_points(): parents = [-1] * vertices visited = [False] * vertices disc = [float('inf')] * vertices low = [float('inf')] * vertices for v in range(vertices): if not visited[v]: Tarjan(v, parents, visited, disc, low) return art_set if __name__ == '__main__': _input = sys.stdin.readlines() vertices, edges = map(int, _input[0].split()) v_info = map(lambda x: x.split(), _input[1:]) init_adj_table = tuple([] for _ in range(vertices)) adj_table = generate_adj_table(v_info) timer = 0 art_set = set() ans = art_points() if ans: print(*sorted(ans), sep='\n') ```
output
1
84,197
13
168,395
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,198
13
168,396
"Correct Solution: ``` from sys import stdin readline = stdin.readline def main(): v, e = map(int, readline().split()) from collections import defaultdict g = defaultdict(list) for _ in range(e): s, t = map(int, readline().split()) g[s].append(t) g[t].append(s) visited = set() lowest = [None] * v parent = [None] * v prenum = [None] * v child = defaultdict(list) root = 0 # dfs??§tree????????? stack = [(root, None)] while stack: u, prev = stack.pop() if u not in visited: parent[u] = prev if prev is not None: child[prev].append(u) visited |= {u} prenum[u] = lowest[u] = len(visited) stack.extend([(v, u) for v in g[u] if v not in visited]) # lowest????¨???? from collections import Counter leaf = [i for i in range(v) if not child[i]] unfinished = Counter() for li in leaf: while li is not None: candidate = [prenum[li]] + [prenum[i] for i in g[li] if i != parent[li]] + [lowest[i] for i in child[li]] lowest[li] = min(candidate) li = parent[li] if li is not None and 1 < len(child[li]): unfinished[li] += 1 if unfinished[li] < len(child[li]): break # ??£??????????????? if 2 <= len(child[root]): print(root) for i in range(1, v): if child[i] and any(prenum[i] <= lowest[j] for j in child[i]): print(i) main() ```
output
1
84,198
13
168,397
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,199
13
168,398
"Correct Solution: ``` # Acceptance of input import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) adj_sets = [set() for i in range(V)] for l_i in f_i: s, t = map(int, l_i.split()) adj_sets[s].add(t) adj_sets[t].add(s) # dfs traverse prenum = [0] * V parent = [0] * V lowest = [V] * V import collections path = collections.deque() path.append(0) cnt = 0 while path: u = path[-1] adj_v = adj_sets[u].copy() v_candidate = adj_v.difference(path) if v_candidate: v = v_candidate.pop() cnt += 1 prenum[v] = cnt parent[v] = u path.append(v) adj_sets[u].remove(v) adj_sets[v].remove(u) else: l = min(prenum[u], lowest[u]) for v in adj_v: l = min(l, prenum[v]) adj_sets[u].remove(v) adj_sets[v].remove(u) lowest[u] = l p = parent[u] lowest[p] = min(l, lowest[p]) path.pop() # output ans = set() for u in range(1, V): p = parent[u] if prenum[p] <= lowest[u]: ans.add(p) if parent.count(0) >= 3: ans.add(0) else: ans.discard(0) ans = list(ans) ans.sort() if ans: print(*ans, sep = '\n') ```
output
1
84,199
13
168,399
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,200
13
168,400
"Correct Solution: ``` # Acceptance of input import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) adj = [[] for i in range(V)] for l_i in f_i: s, t = map(int, l_i.split()) adj[s].append(t) adj[t].append(s) # dfs traverse prenum = [1] + [None] * (V - 1) parent = [0] * V lowest = [V] * V import collections path = collections.deque() path.append(0) cnt = 1 while path: u = path[-1] adj_v = adj[u] for v in adj_v: if not prenum[v]: parent[v] = u path.append(v) cnt += 1 prenum[v] = cnt adj[u].remove(v) adj[v].remove(u) break if u == path[-1]: for v in adj_v: lowest[u] = min(lowest[u], prenum[v]) p = parent[u] lowest[p] = min(lowest[u], lowest[p]) path.pop() # output ans = set() for u in range(1, V): p = parent[u] if prenum[p] <= lowest[u]: ans.add(p) if parent.count(0) >= 3: ans.add(0) else: ans.discard(0) ans = list(ans) ans.sort() if ans: print(*ans, sep = '\n') ```
output
1
84,200
13
168,401
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,201
13
168,402
"Correct Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**6) N, M = map(int, input().split()) G = [[] for _ in [0]*N] for _ in [0]*M: a, b = map(int, input().split()) G[a].append(b) G[b].append(a) INF = 10**10 pre = [0]*N visited = [0]*N min_x = [INF]*N is_articulation = [0]*N n_root_children = 0 def dfs(v=0, p=-1, k=0): global n_root_children pre[v] = min_x[v] = mn = k visited[v] = 1 for u in G[v]: if u == p: continue elif visited[u]: x = min_x[u] if x < mn: mn = x continue if v == 0: n_root_children += 1 k += 1 x = dfs(u, v, k) if pre[v] <= x: is_articulation[v] = 1 if x < mn: mn = x min_x[v] = mn return mn dfs() for v, a in enumerate(is_articulation): if v == 0: if n_root_children >= 2: print(v) elif a: print(v) ```
output
1
84,201
13
168,403
Provide a correct Python 3 solution for this coding contest problem. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3
instruction
0
84,202
13
168,404
"Correct Solution: ``` # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(200000) if __name__ == '__main__': n, m = [int(s) for s in input().split()] E = [set() for _ in range(n)] for _ in range(m): s, t = [int(s) for s in input().split(" ")] E[s].add(t) E[t].add(s) def dfs(current, prev): global timer prenum[current] = timer lowest[current] = prenum[current] timer += 1 visited[current] = 1 for v in E[current]: if visited[v] == 0: parent[v] = current dfs(v, current) lowest[current] = min(lowest[current], lowest[v]) elif v != prev: # current -> v is back-edge lowest[current] = min(lowest[current], prenum[v]) prenum = [None] * n parent = [None] * n lowest = [float("inf")] * n timer = 1 visited = [0] * n dfs(0, -1) ap = [] np = 0 for i in range(1, n): p = parent[i] if p == 0: np += 1 elif prenum[p] <= lowest[i]: ap.append(p) if np > 1: ap.append(0) ap = list(set(ap)) ap.sort() if ap: print("\n".join(map(str, ap))) ```
output
1
84,202
13
168,405
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) timer = 0 def dfs(current, prev, g, visited, prenum, parent, lowest): global timer prenum[current] = timer lowest[current] = timer timer += 1 visited[current] = True for i in range(len(g[current])): next_node = g[current][i] if not visited[next_node]: parent[next_node] = current dfs(next_node, current, g, visited, prenum, parent, lowest) lowest[current] = min(lowest[current], lowest[next_node]) elif next_node != prev: lowest[current] = min(lowest[current], prenum[next_node]) def art_points(n, g): visited = [False] * n INFTY = 1 << 20 prenum = [INFTY] * n parent = [INFTY] * n parent[0] = -1 lowest = [INFTY] * n global timer timer = 1 dfs(0, -1, g, visited, prenum, parent, lowest) ap = set() np = 0 for i in range(1, n): p = parent[i] if p == 0: np += 1 elif prenum[p] <= lowest[i]: ap.add(p) if np > 1: ap.add(0) for line in sorted(ap): print(line) if __name__ == '__main__': n, m = [int(v) for v in input().split()] g = [[] for i in range(n)] for i in range(m): s, t = [int(v) for v in input().split()] g[s].append(t) g[t].append(s) art_points(n, g) ```
instruction
0
84,203
13
168,406
Yes
output
1
84,203
13
168,407
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` import sys sys.setrecursionlimit(10**7) def run(): V, E = map(int, input().split()) if V == 1: exit() g = {} for e in range(E): A, B = map(int, input().split()) g.setdefault(B, []).append(A) g.setdefault(A, []).append(B) order = [0]*V count = 0 art = [] def dfs(now, prev): nonlocal count fcount = artflag = 0 count += 1 low_p = order[now-1] = count for nxt in g[now]: if nxt == prev: continue if order[nxt-1] == 0: nxt_low_p = dfs(nxt, now) artflag |= nxt_low_p >= order[now-1] low_p = min(low_p, nxt_low_p) fcount += 1 else: low_p = min(low_p, order[nxt-1]) if (prev == -1 and fcount > 1) or (prev != -1 and artflag): art.append(now) return low_p dfs(1, -1) for a in sorted(art): print(a) if __name__ == '__main__': run() ```
instruction
0
84,204
13
168,408
Yes
output
1
84,204
13
168,409
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` import sys class LowLinks: def __init__(self, edges, v, root=0): self.edges = edges self.root = root self.ord = [None] * v self.low = [None] * v self.cnt = 0 self.bridges = [] self.articulations = set() self.par = [None] * v def build(self): self.search(self.root) def search(self, x): self.ord[x] = self.cnt self.low[x] = self.cnt self.cnt += 1 dim = 0 for to in self.edges[x]: if to == self.par[x]:continue if self.ord[to] != None: self.low[x] = min(self.low[x], self.ord[to]) else: self.par[to] = x self.search(to) dim += 1 self.low[x] = min(self.low[x], self.low[to]) if x != self.root and self.ord[x] <= self.low[to]: self.articulations.add(x) if x == self.root and dim > 1: self.articulations.add(x) if self.ord[x] < self.low[to]: self.bridges.append((x, to)) sys.setrecursionlimit(1000000) v, e = map(int, input().split()) edges = [[] for _ in range(v)] for _ in range(e): s, t = map(int, input().split()) edges[s].append(t) edges[t].append(s) lowlinks = LowLinks(edges, v) lowlinks.build() if lowlinks.articulations: print(*sorted(lowlinks.articulations),sep="\n") ```
instruction
0
84,205
13
168,410
Yes
output
1
84,205
13
168,411
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) def dfs(v, tm): dts[v] = est[v] = tm + 1 child = 0 for i in adj[v]: if est[i] == float('inf'): child += 1 parents[i] = v dfs(i, tm + 1) est[v] = min(est[v], est[i]) if parents[v] is None and child > 1: aps[v] = True if parents[v] is not None and est[i] >= dts[v]: aps[v] = True elif parents[v] != i: est[v] = min(est[v], dts[i]) nv, ne = map(int, input().split(' ')) adj = [[] for _ in range(nv)] est = [float('inf')] * nv parents = [None] * nv aps = [False] * nv dts = [0] * nv for _ in range(ne): s, t = map(int, input().split(' ')) adj[s].append(t) adj[t].append(s) dfs(0, 0) for i in range(nv): if aps[i]: print(i) ```
instruction
0
84,206
13
168,412
Yes
output
1
84,206
13
168,413
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` from sys import stdin readline = stdin.readline v, e = map(int, readline().split()) from collections import defaultdict g = defaultdict(list) for _ in range(e): s, t = map(int, readline().split()) g[s].append(t) g[t].append(s) visited = set() lowest = [None] * v parent = [None] * v prenum = [None] * v child = defaultdict(list) root = 0 # dfs??§tree????????? stack = [(root, None)] while stack: u, prev = stack.pop() if u not in visited: parent[u] = prev if prev is not None: child[prev].append(u) visited |= {u} prenum[u] = lowest[u] = len(visited) stack.extend([(v, u) for v in g[u] if v not in visited]) leaf = [i for i in range(v) if not child[i]] for li in leaf: while li is not None: candidate = [prenum[li]] + [prenum[i] for i in g[li] if i != parent[li]] + [lowest[i] for i in child[i]] lowest[li] = min(candidate) li = parent[li] if 2 <= len(child[root]): print(root) for i in range(1, v): if child[i] and any(prenum[i] <= lowest[j] for j in child[i]): print(i) ```
instruction
0
84,207
13
168,414
No
output
1
84,207
13
168,415
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` from sys import stdin n, m = map(int, input().split()) G = [[] for _ in [0] * n] prenum = [0] * n parent = [0] * n lowest = [0] * n timer = 0 visited = [False] * n for _ in range(m): s, t = map(int, input().split()) G[s].append(t) G[t].append(s) def dfs(current, prev): global timer timer += 1 prenum[current] = lowest[current] = timer visited[current] = True for i in range(len(G[current])): next = G[current][i] if not visited[next]: parent[next] = current dfs(next, current) lowest[current] = min(lowest[current], lowest[next]) elif next != prev: lowest[current] = min(lowest[current], prenum[next]) dfs(0, -1) ap = set() np = 0 for i in range(1, n): p = parent[i] if p == 0: np += 1 elif prenum[p] <= lowest[i]: ap.add(p) if np > 1: print(0) li = sorted(ap) print(*li, sep="\n") ```
instruction
0
84,208
13
168,416
No
output
1
84,208
13
168,417
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` def get_articulation_points(G, N, start=0): v_min = [0]*N; order = [None]*N result = []; count = 0 def dfs(v, prev): nonlocal count r_min = order[v] = count fcnt = 0; p_art = 0 count += 1 for w in G[v]: if w == prev: continue if order[w] is None: ret = dfs(w, v) p_art |= (ret == w) r_min = min(r_min, ret) fcnt += 1 else: r_min = min(r_min, order[w]) if (prev == -1 and fcnt > 1) or (prev != -1 and p_art): result.append(v) return r_min dfs(start, -1) return result n, m = map(int, input().split()) G = [[] for i in range(n)] for i in range(m): s, t = map(int, input().split()) G[s].append(t) G[t].append(s) [*map(print,sorted(get_articulation_points(G, n)))] ```
instruction
0
84,209
13
168,418
No
output
1
84,209
13
168,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Find articulation points of a given undirected graph G(V, E). A vertex in an undirected graph is an articulation point (or cut vertex) iff removing it disconnects the graph. Constraints * 1 ≤ |V| ≤ 100,000 * 0 ≤ |E| ≤ 100,000 * The graph is connected * There are no parallel edges * There are no self-loops Input |V| |E| s0 t0 s1 t1 : s|E|-1 t|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. si and ti represent source and target verticess of i-th edge (undirected). Output A list of articulation points of the graph G ordered by name. Examples Input 4 4 0 1 0 2 1 2 2 3 Output 2 Input 5 4 0 1 1 2 2 3 3 4 Output 1 2 3 Submitted Solution: ``` # Acceptance of input import sys f_i = sys.stdin V, E = map(int, f_i.readline().split()) adj_sets = [set() for i in range(V)] for l_i in f_i: s, t = map(int, l_i.split()) adj_sets[s].add(t) adj_sets[t].add(s) # dfs traverse prenum = [0] * V parent = [0] * V lowest = [V] * V import collections path = collections.deque() path.append(0) cnt = 0 while path: u = path[-1] adj_v = adj_sets[u].copy() v_candidate = adj_v.difference(path) if v_candidate: v = v_candidate.pop() cnt += 1 prenum[v] = cnt parent[v] = u path.append(v) adj_sets[u].remove(v) adj_sets[v].remove(u) else: l = min(prenum[u], lowest[u]) for v in adj_v: l = min(l, prenum[v]) adj_sets[u].remove(v) adj_sets[v].remove(u) lowest[u] = l lowest[parent[u]] = l path.pop() # output if parent.count(0) >= 3: print(0) for u in range(2, V): p = parent[u] if prenum[p] <= lowest[u]: print(p) ```
instruction
0
84,210
13
168,420
No
output
1
84,210
13
168,421
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a directed graph G which can contain loops (edges from a vertex to itself). Multi-edges are absent in G which means that for all ordered pairs (u, v) exists at most one edge from u to v. Vertices are numbered from 1 to n. A path from u to v is a sequence of edges such that: * vertex u is the start of the first edge in the path; * vertex v is the end of the last edge in the path; * for all pairs of adjacent edges next edge starts at the vertex that the previous edge ends on. We will assume that the empty sequence of edges is a path from u to u. For each vertex v output one of four values: * 0, if there are no paths from 1 to v; * 1, if there is only one path from 1 to v; * 2, if there is more than one path from 1 to v and the number of paths is finite; * -1, if the number of paths from 1 to v is infinite. Let's look at the example shown in the figure. <image> Then: * the answer for vertex 1 is 1: there is only one path from 1 to 1 (path with length 0); * the answer for vertex 2 is 0: there are no paths from 1 to 2; * the answer for vertex 3 is 1: there is only one path from 1 to 3 (it is the edge (1, 3)); * the answer for vertex 4 is 2: there are more than one paths from 1 to 4 and the number of paths are finite (two paths: [(1, 3), (3, 4)] and [(1, 4)]); * the answer for vertex 5 is -1: the number of paths from 1 to 5 is infinite (the loop can be used in a path many times); * the answer for vertex 6 is -1: the number of paths from 1 to 6 is infinite (the loop can be used in a path many times). Input The first contains an integer t (1 ≤ t ≤ 10^4) — the number of test cases in the input. Then t test cases follow. Before each test case, there is an empty line. The first line of the test case contains two integers n and m (1 ≤ n ≤ 4 ⋅ 10^5, 0 ≤ m ≤ 4 ⋅ 10^5) — numbers of vertices and edges in graph respectively. The next m lines contain edges descriptions. Each line contains two integers a_i, b_i (1 ≤ a_i, b_i ≤ n) — the start and the end of the i-th edge. The vertices of the graph are numbered from 1 to n. The given graph can contain loops (it is possible that a_i = b_i), but cannot contain multi-edges (it is not possible that a_i = a_j and b_i = b_j for i ≠ j). The sum of n over all test cases does not exceed 4 ⋅ 10^5. Similarly, the sum of m over all test cases does not exceed 4 ⋅ 10^5. Output Output t lines. The i-th line should contain an answer for the i-th test case: a sequence of n integers from -1 to 2. Example Input 5 6 7 1 4 1 3 3 4 4 5 2 1 5 5 5 6 1 0 3 3 1 2 2 3 3 1 5 0 4 4 1 2 2 3 1 4 4 3 Output 1 0 1 2 -1 -1 1 -1 -1 -1 1 0 0 0 0 1 1 2 1
instruction
0
84,492
13
168,984
Tags: dfs and similar, dp, graphs, trees Correct Solution: ``` import sys input = sys.stdin.buffer.readline for _ in range(int(input())): x = input() n,m = map(int,input().split()) adj = [[] for i in range(n+1)] radj = [[] for i in range(n+1)] # setup adj and radj for i in range(m): a,b = map(int,input().split()) adj[a].append(b) radj[b].append(a) toposort = [] vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1,n+1): if not vis[c]: vis[c] = 1 s = [c] while s: c = s[-1] if idx[c] < len(adj[c]): ne = adj[c][idx[c]] if not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: toposort.append(c) s.pop() scc = [0]*(n+1) sccs = [[]] while toposort: c = toposort.pop() if scc[c] == 0: sccs.append([]) s = [c] while s: c = s.pop() if scc[c] == 0: scc[c] = len(sccs)-1 sccs[-1].append(c) for ne in radj[c]: if scc[ne] == 0: s.append(ne) compressed_adj = [[] for i in range(len(sccs))] compressed_radj = [[] for i in range(len(sccs))] cycle = [0] * len(sccs) for a in range(1,n+1): for b in adj[a]: if scc[a] != scc[b]: compressed_adj[scc[a]].append(scc[b]) compressed_radj[scc[b]].append(scc[a]) else: # size > 1 of self loop cycle[scc[a]] = 1 for i in range(1,len(sccs)): if not cycle[i] and len(sccs[i]) > 1: raise RuntimeError ans = [0]*(n+1) for i in range(1,len(sccs)): if 1 in sccs[i]: start = i ''' s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) cycle_on_path = 0 #infinite now removed = [0]*(n+1) while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: cycle_on_path += 1 for i in sccs[c]: if cycle_on_path: ans[i] = -1 else: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: if cycle[c]: cycle_on_path -= 1 removed[c] += 1 if removed[c] != 1: raise RuntimeError s.pop() ''' reachable_cycles = [] s = [start] vis = [0] * (n + 1) idx = [0] * (n + 1) while s: c = s[-1] if not vis[c]: vis[c] = 1 if cycle[c]: reachable_cycles.append(c) else: for i in sccs[c]: ans[i] = 1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() vis = [0] * (n + 1) idx = [0] * (n + 1) for c in reachable_cycles: s = [c] while s: c = s[-1] if not vis[c]: vis[c] = 1 for i in sccs[c]: ans[i] = -1 if idx[c] < len(compressed_adj[c]): ne = compressed_adj[c][idx[c]] if not vis[ne]: # so element gets put on stack only 1 time s.append(ne) idx[c] += 1 else: s.pop() for i in range(1,n+1): if cycle[scc[i]] and not (ans[i] == -1 or ans[i] == 0): raise RuntimeError for i in range(1,n+1): if len(sccs[scc[i]]) > 1 and ans[i] == 1: raise RuntimeError for i in range(len(sccs)): if len(sccs[i]) > 1: for j in sccs[i]: if ans[j] == 1: raise RuntimeError paths = [0]*(n+1) paths[start] = 1 vis = [0] * (n + 1) idx = [0] * (n + 1) for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 if not vis[scc[c]]: vis[scc[c]] = 1 s = [scc[c]] while s: c = s[-1] if len(sccs[c]) > 1: raise RuntimeError if idx[c] < len(compressed_radj[c]): ne = compressed_radj[c][idx[c]] if not cycle[ne] and not vis[ne]: vis[ne] = 1 s.append(ne) idx[c] += 1 else: for ne in compressed_adj[c]: if not cycle[ne]: paths[ne] += paths[c] s.pop() for c in range(1, n + 1): if ans[c] == 1: # all sccs[c] should be of size 1 ans[c] = 2 if paths[scc[c]] > 1 else 1 print(*ans[1:]) ```
output
1
84,492
13
168,985