message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` from math import gcd import sys def inp(): return sys.stdin.readline().strip() t=int(inp()) for _ in range(t): n,p =map(int, inp().split()) num=2*n+p a=1 b=2 ans=[] for i in range(num): ans.append((a,b)) b+=1 if(b>n): a+=1 b=a+1 for i in ans: print(*i) ```
instruction
0
18,050
13
36,100
Yes
output
1
18,050
13
36,101
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` def solve(n, p): cnt = 2 * n + p for i in range(1, n+1): for j in range(i+1, n+1): print(i, j) cnt -= 1 if cnt == 0: return def main(): t = int(input()) for _ in range(t): n, p = map(int, input().split()) solve(n, p) if __name__ == "__main__": main() ```
instruction
0
18,051
13
36,102
Yes
output
1
18,051
13
36,103
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` for j in range(int(input())): n, p = map(int, input().split()) k = [str(i) + ' ' + str(i + 1) for i in range(1, n)] + ['1 ' + str(n), '1 ' + str(n - 1), '2 ' + str(n)] + \ [str(i) + ' ' + str(i + 2) for i in range(1, n - 1)] for i in range(1, n - 2): if p == 0: break for j in range(i + 3, n + int(i > 1) - (i < 3)): k += [str(i) + ' ' + str(j)] p -= 1 if p == 0: break print('\n'.join(sorted(k))) ```
instruction
0
18,052
13
36,104
Yes
output
1
18,052
13
36,105
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` t = int(input()) for test in range(t): n,p = map(int,input().split()) s = "" for i in range(n): s+=str(i+1)+' '+str((i+1)%n+1)+'\n' s+=str(i+1)+' '+str((i+2)%n+1)+'\n' if p > 0: for i in range(n): for j in range(i+3,min(n,i-2+n)): s+=str(i+1)+' '+str(j+1)+'\n' p-=1 if p <= 0: break if p <= 0: break print(s,end='') ```
instruction
0
18,053
13
36,106
Yes
output
1
18,053
13
36,107
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` import sys T=int(input()) Ans="" for t in range(T): n,p=map(int,input().split()) x=2*n+p ind=0 while(x>0): x-=1 s=str(ind+1) ind+=1 if(ind==n): ind%=n s+=" "+str(ind+1)+"\n" Ans+=s ind+=1 if(ind==n): ind%=n sys.stdout.write(Ans) ```
instruction
0
18,054
13
36,108
No
output
1
18,054
13
36,109
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` t = int(input()) for _ in range(t): n, p = map(int, input().split()) k = 2*n + p pre =1 while(k > 0): for i in range(pre+1, n+1): print(pre, i) k = k-1 pre+=1 ```
instruction
0
18,055
13
36,110
No
output
1
18,055
13
36,111
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` t = int(input()) for z in range(t): n, p = [int(x) for x in input().split()] cur = 0 for i in range(1, n): j = i + 1 while (j <= n) and (cur <= n*2): print(i, j) j += 1 cur += 1 ```
instruction
0
18,056
13
36,112
No
output
1
18,056
13
36,113
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Let's call an undirected graph of n vertices p-interesting, if the following conditions fulfill: * the graph contains exactly 2n + p edges; * the graph doesn't contain self-loops and multiple edges; * for any integer k (1 ≤ k ≤ n), any subgraph consisting of k vertices contains at most 2k + p edges. A subgraph of a graph is some set of the graph vertices and some set of the graph edges. At that, the set of edges must meet the condition: both ends of each edge from the set must belong to the chosen set of vertices. Your task is to find a p-interesting graph consisting of n vertices. Input The first line contains a single integer t (1 ≤ t ≤ 5) — the number of tests in the input. Next t lines each contains two space-separated integers: n, p (5 ≤ n ≤ 24; p ≥ 0; <image>) — the number of vertices in the graph and the interest value for the appropriate test. It is guaranteed that the required graph exists. Output For each of the t tests print 2n + p lines containing the description of the edges of a p-interesting graph: the i-th line must contain two space-separated integers ai, bi (1 ≤ ai, bi ≤ n; ai ≠ bi) — two vertices, connected by an edge in the resulting graph. Consider the graph vertices numbered with integers from 1 to n. Print the answers to the tests in the order the tests occur in the input. If there are multiple solutions, you can print any of them. Examples Input 1 6 0 Output 1 2 1 3 1 4 1 5 1 6 2 3 2 4 2 5 2 6 3 4 3 5 3 6 Submitted Solution: ``` t=int(input()) for i in range(t): n,p=map(int,input().split()) c=0 z=(2*n)+p print(z) for i in range(1,n+1): for j in range(i+1,n+1): if(c>=z): break else: print(i,j) c=c+1 ```
instruction
0
18,057
13
36,114
No
output
1
18,057
13
36,115
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given a connected weighted graph with n vertices and m edges. The graph doesn't contain loops nor multiple edges. Consider some edge with id i. Let's determine for this edge the maximum integer weight we can give to it so that it is contained in all minimum spanning trees of the graph if we don't change the other weights. You are to determine this maximum weight described above for each edge. You should calculate the answer for each edge independently, it means there can't be two edges with changed weights at the same time. Input The first line contains two integers n and m (2 ≤ n ≤ 2·105, n - 1 ≤ m ≤ 2·105), where n and m are the number of vertices and the number of edges in the graph, respectively. Each of the next m lines contains three integers u, v and c (1 ≤ v, u ≤ n, v ≠ u, 1 ≤ c ≤ 109) meaning that there is an edge between vertices u and v with weight c. Output Print the answer for each edge in the order the edges are given in the input. If an edge is contained in every minimum spanning tree with any weight, print -1 as the answer. Examples Input 4 4 1 2 2 2 3 2 3 4 2 4 1 3 Output 2 2 2 1 Input 4 3 1 2 2 2 3 2 3 4 2 Output -1 -1 -1 Submitted Solution: ``` def f(x): return int(x)-1 n, m = list(map(int,input().split())) if m == n-1: print(' '.join(['-1']*m)) else: e = [] for i in range(m): e.append(list(map(f,input().split()))) e[-1][2]+=1 l = 0 r = 10**9 while r > l: check = (r+l)//2 adj = [] for i in range(n): adj.append([]) for i in e: if i[2] <= check: adj[i[0]].append(i[1]) adj[i[1]].append(i[0]) toDo = [True]*n toCheck = [0] toDo[0]=False num = 1 while len(toCheck) > 0: nex = toCheck.pop(0) for i in adj[nex]: if toDo[i]: toDo[i] = False toCheck.append(i) num += 1 if num == n: r = check else: l = check + 1 ans = l e2 = [] for i in range(m): if e[i][2] <= ans: e2.append(e[i][:2]+[i]) adj = [] for i in range(n): adj.append([]) for i in e2: adj[i[0]].append(i[1]) adj[i[1]].append(i[0]) bridges = [] toDo = [True]*n order = [-1]*n low = [-1]*n lead = [0] toDo[0]=False order[0] = 0 low[0] = 0 num = 1 while len(lead) > 0: lad = lead[0] if len(adj[lad]) == 0: if lad == 0: break lead.pop(0) low[lead[0]] = min(low[lead[0]],low[lad]) if low[lead[0]] == order[lead[0]]: bridges.append([lead[0],lad]) else: nex = adj[lad].pop() if toDo[nex]: toDo[nex] = False order[nex] = num low[nex] = num num += 1 lead = [nex]+lead elif len(lead) > 1 and nex != lead[1]: low[nex] = min(low[nex],order[lad]) fBridge = [] for i in range(n): fBridge.append([]) for i in bridges: fBridge[i[0]].append(i[1]) fBridge[i[1]].append(i[0]) bridge = [] for i in e2: if i[1] in fBridge[i[0]]: bridge.append(i[2]) out = [ans-1]*m for i in bridge: out[i] += 1 print(' '.join(list(map(str,out)))) ```
instruction
0
18,215
13
36,430
No
output
1
18,215
13
36,431
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,323
13
36,646
"Correct Solution: ``` def main(): from collections import deque n,m,*t=map(int,open(0).read().split()) i,o=[0]*n,[[]for _ in range(n)] for a,b in zip(*[iter(t)]*2): o[a-1]+=b-1, i[b-1]+=1 q=deque(v for v in range(n)if i[v]<1) r=[] while q: v=q.popleft() r+=v, for w in o[v]: i[w]-=1 if i[w]==0:q+=w, print(-(len(r)==n)) main() ```
output
1
18,323
13
36,647
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,324
13
36,648
"Correct Solution: ``` import sys sys.setrecursionlimit(100000) N, M = list(map(int, input().split())) AB = [list(map(int, input().split())) for _ in range(M)] R = {} for a, b in AB: if a in R: R[a].append(b) else: R[a] = [b] def nasu(x, e): D[x] = 1 if x not in R: return [] for i in R[x]: if i == e: return [i] if D[i] == 0: t = nasu(i, e) if t != []: return [i] + t return [] for i in range(1, N + 1): D = [0] * (N + 1) L = nasu(i, i) if L != []: break else: print(-1) exit() D = [0] * (N + 1) for i in L: D[i] = 1 LEN = len(L) L = L + L i = 0 while i < LEN: for j in range(i + LEN - 1, i, -1): if D[L[j]] != 0 and L[j] in R[L[i]]: for k in range(j - 1, i, -1): D[L[k]] = 0 i = j break A = [] for i in range(LEN): if D[L[i]] == 1: A.append(L[i]) print(len(A)) for i in A: print(i) ```
output
1
18,324
13
36,649
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,325
13
36,650
"Correct Solution: ``` import sys input = sys.stdin.readline n,m = map(int,input().split()) edge = [[] for _ in [0]*n] back = [[] for _ in [0]*n] for _ in [0]*m: a,b = map(int,input().split()) edge[a-1].append(b-1) back[b-1].append(a-1) res = [None]*(n+1) for end in range(n): for start in edge[end]: cost = [-1]*n cost[start] = 0 new = [start] tank = [] judge = True while len(new) > 0 and judge: tank = [] for fr in new: for go in edge[fr]: if cost[go] < 0: cost[go] = cost[fr] + 1 tank.append(go) if go == end: judge = False new = tank if cost[end] >= 0 and cost[end] < len(res): p = end res = [p+1] while p != start: for e in back[p]: if cost[p] == cost[e]+1: p = e res.append(p+1) break if res[0] == None: print(-1) else: print(len(res)) for e in res: print(e) ```
output
1
18,325
13
36,651
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,326
13
36,652
"Correct Solution: ``` n, m = map(int, input().split()) ans = [0] * (n + 1) import collections g = collections.defaultdict(set) for _ in range(m): a, b = map(int, input().split()) g[a-1].add(b-1) def minCircle(s): f = [None] * n visited = set() q = [] q.append(s) while q: node = q.pop() for nei in g[node]: if nei not in visited: f[nei] = node visited.add(nei) q.append(nei) if s in visited: break p = f[s] ret = [] ret.append(s) while p is not None and p!= s: ret.append(p) p = f[p] return ret for i in range(n): t = minCircle(i) if len(t) > 1 and len(t) < len(ans): ans = t if len(ans) == n + 1: print(-1) else: print(len(ans)) for i in ans: print(i+1) ```
output
1
18,326
13
36,653
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,327
13
36,654
"Correct Solution: ``` N,M=map(int,input().split()) AB=[list(map(int,input().split())) for i in range(M)] c=[[] for i in range(N)] for a,b in AB: c[a-1].append(b-1) from collections import deque import sys sys.setrecursionlimit(10**9) def f2(q): s=set(q) for a,b in AB: if a in s and b in s: i=q.index(b) if q[i-1]!=a: break if a in s and b in s and q[i-1]!=a: q2=deque([a,b]) while q[(i+1)%len(q)]!=a: q2.append(q[(i+1)%len(q)]) i+=1 f2(q2) print(len(q),*q,sep='\n') exit() v=[0]*N w=[0]*N def f(p,v,q): v[p]=1 w[p]=1 q.append(p+1) for n in c[p]: if v[n]: f2(q) else: f(n,v,q) q.pop() v[p]=0 for p in range(N): if w[p]==0: f(p,v,deque()) print(-1) ```
output
1
18,327
13
36,655
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,328
13
36,656
"Correct Solution: ``` from collections import deque def resolve(): N, M = map(int, input().split()) G = [[] for _ in range(N)] for _ in range(M): a, b = map(lambda x: int(x) - 1, input().split()) G[a].append(b) shortest = N + 1 res = [] for s in range(N): dist = [-1] * N pre = [-1] * N q = deque() q.append(s) dist[s] = 0 while q: v = q.popleft() for to in G[v]: if dist[to] == -1: dist[to] = dist[v] + 1 pre[to] = v q.append(to) for t in range(N): if t == s or dist[t] == -1: continue for to in G[t]: if to == s: # サイクルになっている頂点 tmp = [s] cur = t while cur != s: tmp.append(cur) cur = pre[cur] if shortest > len(tmp): shortest = len(tmp) res = tmp if shortest == N + 1: print(-1) else: print(len(res)) res.sort() for v in res: print(v + 1) if __name__ == "__main__": resolve() ```
output
1
18,328
13
36,657
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,329
13
36,658
"Correct Solution: ``` from collections import deque import sys sys.setrecursionlimit(10**6) class DirectedGraph: def __init__(self, adj): self.n = len(adj) self.adj = adj self.is_asyclic = False self.max_path_len = None def topological_sort(self): indegree = [0] * self.n for i, vs in enumerate(self.adj): for dest in vs: indegree[dest] += 1 zero_v = [] for v, indeg in enumerate(indegree): if indeg == 0: zero_v.append(v) max_path_len = 1 tp_sorted = [] to_be_added = [] while True: while zero_v: v = zero_v.pop() tp_sorted.append(v) for dest in self.adj[v]: indegree[dest] -= 1 if indegree[dest] == 0: to_be_added.append(dest) if len(to_be_added) > 0: zero_v += to_be_added to_be_added = [] max_path_len += 1 else: break if len(tp_sorted) == self.n: self.is_asyclic = True self.max_path_len = max_path_len return tp_sorted else: self.is_asyclic = False return None def extract_cycle(self): self.seen = [0] * self.n self.checked = [0] * self.n self.hist = deque() self.node_in_cycle = -1 def dfs(v): self.seen[v] = 1 self.hist.append(v) for nv in self.adj[v]: if self.checked[nv]: continue if self.seen[nv] and not self.checked[nv]: self.node_in_cycle = nv return dfs(nv) if self.node_in_cycle != -1: return self.hist.pop() self.checked[v] = 1 for i in range(self.n): if not self.checked[i]: dfs(i) if self.node_in_cycle != -1: break if self.node_in_cycle == -1: return [] else: cycle = [] while self.hist: t = self.hist.pop() cycle.append(t) if t == self.node_in_cycle: break cycle.reverse() return cycle n, m = [int(item) for item in input().split()] edge = [[] for _ in range(n)] for i in range(m): a, b = [int(item) - 1 for item in input().split()] edge[a].append(b) DG = DirectedGraph(edge) cycle = DG.extract_cycle() if len(cycle) == 0: print(-1) exit() while True: in_cycle = set(cycle) deg = [0] * n for item in cycle: for v in edge[item]: if v in in_cycle: deg[v] += 1 ok = True for i, item in enumerate(cycle): if deg[item] > 1: ok = False cur_id = start = i if ok: print(len(cycle)) print("\n".join([str(item + 1) for item in cycle])) exit() ncycle = [] cur = cycle[cur_id] while True: ncycle.append(cur) if cycle[start] in edge[cur]: break cur_id = (cur_id + 1) % len(cycle) cur = cycle[cur_id] cycle = ncycle[:] ```
output
1
18,329
13
36,659
Provide a correct Python 3 solution for this coding contest problem. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5
instruction
0
18,330
13
36,660
"Correct Solution: ``` from collections import deque def solve_f(n, g): for i in range(n): parent = [-1] * n queue = deque([i]) done = False answer = [] # bfs while len(queue) > 0: p = queue.popleft() for q in g[p]: if q == i: r_list = [] r = p while r != -1: r_list.append(r) r = parent[r] # check check = 1 for r in r_list: check = max(len(set(g[r]).intersection(r_list)), check) if check == 1: return [len(r_list)] + [r + 1 for r in r_list] elif parent[q] == -1: parent[q] = p queue.append(q) return [-1] def main(): n, m = map(int, input().split()) g = [[] for _ in range(n)] for _ in range(m): a, b = map(int, input().split()) g[a - 1].append(b - 1) res = solve_f(n, g) for r in res: print(r) if __name__ == "__main__": main() ```
output
1
18,330
13
36,661
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` import sys input = sys.stdin.readline from collections import defaultdict def DD(arg): return defaultdict(arg) INF = float('inf') N,M = list(map(int,input().split())) graph = {i:[] for i in range(N)} for _ in range(M): a,b = list(map(int,input().split())) graph[a-1].append(b-1) p = [None for i in range(N)] def detect_cycle(graph): N = len(graph) Q = [i for i in range(N)] cycle = [] while Q: state = [-1 for i in range(N)] s = Q.pop() if p[s] != None: continue p[s] = -1 q = [s] while q: x = q.pop() if x < 0: state[~x] = 0 continue q.append(~x) for y in graph[x]: state[x] = 1 if state[y] == 0: continue elif state[y] == -1: p[y] = x q.append(y) else: p[y] = x now = x while now != y: cycle.append(now) now = p[now] cycle.append(y) return cycle return cycle def squeeze(l): check = [0 for i in range(N)] for i in l: check[i] = 1 global graph edges = [] subgraph = {k:[] for k in l} data = DD(lambda:DD(int)) i = 0 for k in l: for y in graph[k]: if check[y]: subgraph[k].append(y) edges.append([0,k,y]) data[k][y] = i i += 1 graph = subgraph s = l[0] i = data[p[s]][s] edges[i][0] = 1 now = p[s] heiro = [s] while now != s: heiro.append(now) i = data[p[now]][now] edges[i][0] = 1 now = p[now] if len(heiro)==len(edges): print(len(heiro)) for x in heiro: print(x+1) exit() else: for b,k,y in edges: if not b: p[y] = k now = p[y] heiro = [y] while now != y: heiro.append(now) now = p[now] squeeze(heiro) c = detect_cycle(graph) if not c: print(-1) else: squeeze(c) ```
instruction
0
18,331
13
36,662
Yes
output
1
18,331
13
36,663
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` import sys sys.setrecursionlimit(500000) def scc(N, G, RG): # https://tjkendev.github.io/procon-library/python/graph/scc.html order = [] used = [0]*N group = [None]*N def dfs(s): used[s] = 1 for t in G[s]: if not used[t]: dfs(t) order.append(s) def rdfs(s, col): group[s] = col used[s] = 1 for t in RG[s]: if not used[t]: rdfs(t, col) for i in range(N): if not used[i]: dfs(i) used = [0]*N label = 0 for s in reversed(order): if not used[s]: rdfs(s, label) label += 1 return label, group from collections import Counter N, M = map(int, input().split()) E = [[] for _ in range(N+1)] E_set = [set() for _ in range(N+1)] E_rev = [[] for _ in range(N+1)] E_rev_set = [set() for _ in range(N+1)] for _ in range(M): a, b = map(int, input().split()) E[a].append(b) E_set[a].add(b) E_rev[b].append(a) E_rev_set[b].add(a) label, group = scc(N+1, E, E_rev) cnt = Counter(group) Closed = [False] * (N+1) grooo = [set() for _ in range(N+1)] for v, gr in enumerate(group): grooo[gr].add(v) from random import random haaaaaaaaaaaaaaaaaaaaaaa = enumerate(group) if random() > 0.5 else zip(range(N, 0, -1), group[::-1]) for v, gr in haaaaaaaaaaaaaaaaaaaaaaa: if Closed[gr]: continue Closed[gr] = True if cnt[gr]==1: continue #print(gr, cnt[gr]) groo = grooo[gr] path = [v] path_set = {v} while True: #print("v=",v) aaa = E_set[v]&path_set if aaa: break u = (groo&E_set[v]).pop() #print("u=",u) while E_rev_set[u]-{v} & path_set: path_set.remove(path.pop()) path.append(u) path_set.add(u) v = u #print(path) for i, v in enumerate(path): if v in aaa: aaa.remove(v) if len(aaa)==0: break ans = path[i:] print(len(ans)) print("\n".join(map(str, ans))) exit() print(-1) ```
instruction
0
18,332
13
36,664
Yes
output
1
18,332
13
36,665
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` N, M = [int(x) for x in input().strip().split(" ")] def dfs(v): pvs = set([v]) path = [v] def _dfs(v, path): for u in d[v]: if u in pvs: for i, c in enumerate(path): if c == u: break return path[i+1:] + [u] if u in vs: continue pvs.add(u) vs.add(u) loop = _dfs(u, path + [u]) pvs.remove(u) if loop: return loop return False return _dfs(v, path) vs = set() def dfs_w(v, d): # dfs while版 pvs = set([]) stack = [v] path = [] while True: if len(stack) == 0: break v = stack.pop() if v < 0: pvs.remove(path[-1]) path.pop() else: path.append(v) pvs.add(v) vs.add(v) for u in d[v]: if u in pvs: for i, c in enumerate(path): if c == u: break return path[i+1:] + [u] if u in vs: continue stack += [-v, u] return False d = [set() for _ in range(N+1)] for _ in range(M): a, b = [int(x) for x in input().strip().split(" ")] d[a].add(b) for i in range(N): i += 1 if i in vs: continue loop = dfs_w(i, d) if loop: break if not loop: print(-1) import sys sys.exit() v2i = [-1 for _ in range(N+1)] for i, v in enumerate(loop): v2i[v] = i nloop, pvs = [], set() v = loop[0] f = False while True: nloop.append(v) pvs.add(v) max_i = max_i_l = -1 for u in d[v]: if v2i[u] == -1: continue if v2i[v] > v2i[u] and u in pvs: f = True max_i_l = max(max_i_l, v2i[u]) if v2i[u] > v2i[v]: max_i = max(max_i, v2i[u]) if f: nloop.append(loop[max_i_l]) break v = loop[max_i] for i, x in enumerate(nloop): if x == nloop[-1]: break nloop = nloop[i+1:] print(len(nloop)) for v in nloop: print(v) ```
instruction
0
18,333
13
36,666
Yes
output
1
18,333
13
36,667
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` import sys input = sys.stdin.readline sys.setrecursionlimit(10**7) n, m = map(int, input().split()) G = [[] for _ in range(n)] for i in range(m): a, b = map(int, input().split()) a -= 1 b -= 1 G[a].append(b) seen = [False]*n def dfs(v): seen[v] = True for nv in G[v]: nxt[v] = nv if seen[nv]: return nv s = dfs(nv) if s != -1: return s seen[v] = False return -1 for i in range(n): nxt = [-1]*n s = dfs(i) if s != -1: break else: print(-1) exit() while True: used = set() L = [] while s not in used: used.add(s) L.append(s) s = nxt[s] L.append(s) for i in range(len(L)-1): a, b = L[i], L[i+1] for nv in G[a]: if nv != b and nv in used: nxt[a] = nv s = a break else: continue break else: print(len(used)) for v in used: print(v+1) break ```
instruction
0
18,334
13
36,668
Yes
output
1
18,334
13
36,669
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` from collections import deque N, M = map(int, input().split()) edges = [[] for i in range(N)] for _ in range(M): a, b = map(int, input().split()) edges[a-1].append(b-1) def BFS(s): prev = [-1]*N que = deque([s]) while que: v = que.pop() for nv in edges[v]: if nv == s: return (s, prev) if prev[nv]<0: que.append(nv) prev[nv] = v return (-1, prev) for v in range(N): v0, prev = BFS(v) if v0>0: break if v0<0: print(-1) exit() while True: circle = [False]*N circle[v0] = True l = 1 pv = prev[v0] while pv != v0: circle[pv] = True pv = prev[pv] l+=1 update = False for v in range(l): if circle[v]: for nv in edges[v]: if circle[nv] and prev[nv] != v: prev[nv] = v v0 = v update = True if not update: break print(l) for i in range(N): if circle[i]: print(i+1) ```
instruction
0
18,335
13
36,670
No
output
1
18,335
13
36,671
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` def examA(): class Dijkstra(object): """ construct: O(ElogV) """ def __init__(self, edges, start=0): """ :param list of list of list of int edges: :param int start=0: """ self.__dist = [inf] * len(edges) self.__dist[start] = 0 self.__calculate(edges, start) @property def dist(self): return self.__dist def __calculate(self, edges, start): Q = [(0, start)] # (dist,vertex) while (Q): dist, v = heapq.heappop(Q) if self.dist[v] < dist: continue # 候補として挙がったd,vだが、他に短いのがある for u, cost in edges[v]: if self.dist[u] > self.dist[v] + cost: self.__dist[u] = self.dist[v] + cost heapq.heappush(Q, (self.dist[u], u)) N, L = LI() V, D = LI() X = [LI()for _ in range(N)] X.append([0,V,D]) X.append([L,0,0]) X.sort() V = [[]for _ in range(N+2)] for i in range(N+1): x1, v1, d1 = X[i] r = x1 + d1 for j in range(i+1,N+2): x2, v2, d2 = X[j] if r<x2: break cost = (x2-x1)/v1 V[i].append((j,cost)) dij = Dijkstra(V, 0) ans = dij.dist[-1] if ans>=inf: print("impossible") return print('{:.18f}'.format(ans)) return def examB(): N, K = LI() H = 11; W = 7 S = [[0]*(W+1) for _ in range(H+3)] for h in range(H+2): for w in range(W): S[h+1][w+1] = (S[h][w+1] + S[h+1][w] - S[h][w] + (7*h+w+1)) #print(S) base = 0 for h in range(H): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: base += 1 #print(h,w) ans = base * ((N-2)//11) #print(ans) rest = (N-2)%11 for h in range(rest): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: ans += 1 #print(h,w) print(ans) return def examC(): N, K = LI() A = LI() loop = 2**N ans = inf for i in range(loop): cnt = 0 need = 0 highest = 0 for j in range(N): if i&(1<<j)==0: if highest<A[j]: need = inf break continue cnt += 1 if highest>=A[j]: need += (highest+1-A[j]) highest = highest + 1 else: highest = A[j] if cnt>=K and need<ans: ans = need #print(need) print(ans) return def examD(): # 参考 https://qiita.com/maskot1977/items/e1819b7a1053eb9f7d61 def cycle(neighbor, start, ring_size, node, visitable): stack = [] stack.append(start) path = [{} for _ in range(node)] path[start] = {start} while (stack): last = stack.pop() curr_path = path[last] if len(curr_path) > ring_size: continue for nei in neighbor[last]: if nei in curr_path: if start == nei: return curr_path else: return cycle(neighbor,nei,ring_size-1,node, visitable) if nei not in visitable: continue visited.add(nei) path[nei] = curr_path | {nei} stack.append(nei) return -1 N, M = LI() V = [[]for _ in range(N)] for _ in range(M): a,b = LI() a -= 1; b -= 1 V[a].append(b) #print(V) loop = -1 visitable = set([i for i in range(N)]) for i in range(N): loop = cycle(V,i,N,N,visitable) if type(loop) is set: break visitable.discard(i) if type(loop) is not set: print(-1) return #print(loop) while(True): visitable = deepcopy(loop) next = -1 for k in loop: next = cycle(V,k,len(loop)-1,N,visitable) if type(next) is set: break visitable.discard(k) if type(next) is not set: break loop = next ans = loop print(len(ans)) for v in ans: print(v+1) return import sys,bisect,itertools,heapq,math,random from copy import copy,deepcopy 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,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = 10**(-12) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**6) if __name__ == '__main__': examD() ```
instruction
0
18,336
13
36,672
No
output
1
18,336
13
36,673
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` def examA(): class Dijkstra(object): """ construct: O(ElogV) """ def __init__(self, edges, start=0): """ :param list of list of list of int edges: :param int start=0: """ self.__dist = [inf] * len(edges) self.__dist[start] = 0 self.__calculate(edges, start) @property def dist(self): return self.__dist def __calculate(self, edges, start): Q = [(0, start)] # (dist,vertex) while (Q): dist, v = heapq.heappop(Q) if self.dist[v] < dist: continue # 候補として挙がったd,vだが、他に短いのがある for u, cost in edges[v]: if self.dist[u] > self.dist[v] + cost: self.__dist[u] = self.dist[v] + cost heapq.heappush(Q, (self.dist[u], u)) N, L = LI() V, D = LI() X = [LI()for _ in range(N)] X.append([0,V,D]) X.append([L,0,0]) X.sort() V = [[]for _ in range(N+2)] for i in range(N+1): x1, v1, d1 = X[i] r = x1 + d1 for j in range(i+1,N+2): x2, v2, d2 = X[j] if r<x2: break cost = (x2-x1)/v1 V[i].append((j,cost)) dij = Dijkstra(V, 0) ans = dij.dist[-1] if ans>=inf: print("impossible") return print('{:.18f}'.format(ans)) return def examB(): N, K = LI() H = 11; W = 7 S = [[0]*(W+1) for _ in range(H+3)] for h in range(H+2): for w in range(W): S[h+1][w+1] = (S[h][w+1] + S[h+1][w] - S[h][w] + (7*h+w+1)) #print(S) base = 0 for h in range(H): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: base += 1 #print(h,w) ans = base * ((N-2)//11) #print(ans) rest = (N-2)%11 for h in range(rest): for w in range(W-2): cur = S[h+3][w+3] - S[h+3][w] - S[h][w+3] + S[h][w] if cur%11==K: ans += 1 #print(h,w) print(ans) return def examC(): N, K = LI() A = LI() loop = 2**N ans = inf for i in range(loop): cnt = 0 need = 0 highest = 0 for j in range(N): if i&(1<<j)==0: if highest<A[j]: need = inf break continue cnt += 1 if highest>=A[j]: need += (highest+1-A[j]) highest = highest + 1 else: highest = A[j] if cnt>=K and need<ans: ans = need #print(need) print(ans) return def examD(): # 参考 https://qiita.com/maskot1977/items/e1819b7a1053eb9f7d61 def cycle(neighbor, start, ring_size, node): visited = set() stack = [] stack.append(start) path = [{} for _ in range(node)] path[start] = {start} visited.add(start) while (stack): last = stack.pop() curr_path = path[last] if len(curr_path) > ring_size: continue for nei in neighbor[last]: if nei in curr_path: if start == nei: return curr_path else: return cycle(neighbor,nei,ring_size-1,node) if nei in visited: continue visited.add(nei) path[nei] = curr_path | {nei} stack.append(nei) return -1,visited N, M = LI() V = [[]for _ in range(N)] for _ in range(M): a,b = LI() a -= 1; b -= 1 V[a].append(b) #print(V) loop = -1 visited = [False]*N for i in range(N): if visited[i]: continue loop = cycle(V,i,N,N) if type(loop) is set: break for v in loop[1]: visited[v] = True if type(loop) is not set: print(-1) return while(True): visited = [False] * N next = -1 for k in loop: if visited[k]: continue next = cycle(V,k,len(loop)-1,N) if type(next) is set: break for v in next[1]: visited[v] = True if type(next) is not set: break loop = next ans = loop print(len(ans)) for v in ans: print(v+1) return import sys,bisect,itertools,heapq,math,random from copy import copy,deepcopy 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,mod2,inf,alphabet,_ep mod = 10**9 + 7 mod2 = 998244353 inf = 10**18 _ep = 10**(-12) alphabet = [chr(ord('a') + i) for i in range(26)] sys.setrecursionlimit(10**6) if __name__ == '__main__': examD() ```
instruction
0
18,337
13
36,674
No
output
1
18,337
13
36,675
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given is a directed graph G with N vertices and M edges. The vertices are numbered 1 to N, and the i-th edge is directed from Vertex A_i to Vertex B_i. It is guaranteed that the graph contains no self-loops or multiple edges. Determine whether there exists an induced subgraph (see Notes) of G such that the in-degree and out-degree of every vertex are both 1. If the answer is yes, show one such subgraph. Here the null graph is not considered as a subgraph. Constraints * 1 \leq N \leq 1000 * 0 \leq M \leq 2000 * 1 \leq A_i,B_i \leq N * A_i \neq B_i * All pairs (A_i, B_i) are distinct. * All values in input are integers. Input Input is given from Standard Input in the following format: N M A_1 B_1 A_2 B_2 : A_M B_M Output If there is no induced subgraph of G that satisfies the condition, print `-1`. Otherwise, print an induced subgraph of G that satisfies the condition, in the following format: K v_1 v_2 : v_K This represents the induced subgraph of G with K vertices whose vertex set is \\{v_1, v_2, \ldots, v_K\\}. (The order of v_1, v_2, \ldots, v_K does not matter.) If there are multiple subgraphs of G that satisfy the condition, printing any of them is accepted. Examples Input 4 5 1 2 2 3 2 4 4 1 4 3 Output 3 1 2 4 Input 4 5 1 2 2 3 2 4 1 4 4 3 Output -1 Input 6 9 1 2 2 3 3 4 4 5 5 6 5 1 5 2 6 1 6 2 Output 4 2 3 4 5 Submitted Solution: ``` def cycle_detection(V, E, s): prev = [-1] * len(V) stack = [s] while stack: v = stack.pop() for u in E[v]: if u == s: prev[u] = v return (s, prev) if prev[u] == -1: stack.append(u) prev[u] = v return (-1, prev) N, M = map(int, input().split()) V = list(range(N)) E = [[] for _ in range(N)] edges = [] for _ in range(M): a, b = map(int, input().split()) E[a-1].append(b-1) edges.append((a-1, b-1)) dag = False for v in range(N): s, prev = cycle_detection(V, E, v) if s != -1: break else: dag = True if dag: print(-1) else: # construct a directed cycle cycle = set() cycle.add(s) pv = prev[s] while pv != s: cycle.add(pv) pv = prev[pv] # shrink the directed cycle print(len(cycle)) print(*[v + 1 for v in cycle], sep='\n') """ for a, b in edges: if a in cycle and b in cycle and prev[b] != a: pv = prev[b] while pv != a: cycle.remove(pv) pv = prev[pv] prev[b] = a print(len(cycle)) print(*[v + 1 for v in cycle], sep='\n') """ ```
instruction
0
18,338
13
36,676
No
output
1
18,338
13
36,677
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,533
13
37,066
"Correct Solution: ``` import sys class Node: __slots__ = ['key', 'left', 'right'] def __init__(self, key): self.key = key self.left = self.right = None root = None def insert(key): global root x, y = root, None while x: y = x if key < x.key: x = x.left else: x = x.right if y is None: root = Node(key) elif key < y.key: y.left = Node(key) else: y.right = Node(key) def find(key): global root x = root while x: if key < x.key: x = x.left elif key == x.key: return "yes" else: x = x.right return "no" def inorder(node): return inorder(node.left) + f' {node.key}' + inorder(node.right) if node else '' def preorder(node): return f' {node.key}' + preorder(node.left) + preorder(node.right) if node else '' n = int(input()) for e in sys.stdin: if e[0] == 'i': insert(int(e[7:])) elif e[0] == "f": print(find(int(e[5:]))) else: print(inorder(root)) print(preorder(root)) ```
output
1
18,533
13
37,067
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,534
13
37,068
"Correct Solution: ``` import sys input = sys.stdin.readline print = sys.stdout.write class Node: __slots__ = ["data", "left", "right"] def __init__(self, data): self.data = data self.left = None self.right = None class BinarySearchTree: __slots__ = ["root"] def __init__(self): self.root = None def insert(self, data): parent = self.root if parent is None: self.root = Node(data) return while parent: parent_old = parent parent = parent.left if data < parent.data else parent.right if data < parent_old.data: parent_old.left = Node(data) else: parent_old.right = Node(data) def find(self, data): parent = self.root if parent is None: print("no\n") return while parent: if parent.data == data: print("yes\n") return parent = parent.left if data < parent.data else parent.right print("no\n") return def print_preorder(node): print(" {}".format(node.data)) if node.left: print_preorder(node.left) if node.right: print_preorder(node.right) def print_inorder(node): if node.left: print_inorder(node.left) print(" {}".format(node.data)) if node.right: print_inorder(node.right) if __name__ == "__main__": n = int(input()) binary_search_tree = BinarySearchTree() for _ in range(n): operation, *num = input().split() if operation[0] == "i": binary_search_tree.insert(int(num[0])) elif operation[0] == "f": binary_search_tree.find(int(num[0])) elif binary_search_tree.root is not None: print_inorder(binary_search_tree.root) print("\n") print_preorder(binary_search_tree.root) print("\n") ```
output
1
18,534
13
37,069
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,535
13
37,070
"Correct Solution: ``` import sys NIL = -1 class Node: def __init__(self, key): self.key = key self.parent = NIL self.left = NIL self.right = NIL class Tree: def __init__(self): self.root = NIL def insert(self, z): y = NIL x = self.root while x != NIL: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y if y == NIL: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, value, node): if node == NIL: return False elif node.key == value: return True elif value < node.key: # print('go to left') return self.find(value, node=node.left) else: # print('go to right') return self.find(value, node=node.right) def inorder_walk(self, node): if node == NIL: return None if node.left != NIL: self.inorder_walk(node=node.left) print(' ' + str(node.key), end='') if node.right != NIL: self.inorder_walk(node=node.right) def preorder_walk(self, node): if node == NIL: return None print(' ' + str(node.key), end='') if node.left != NIL: self.preorder_walk(node=node.left) if node.right != NIL: self.preorder_walk(node=node.right) def show(self): self.inorder_walk(self.root) print() self.preorder_walk(self.root) print() n = int(sys.stdin.readline()) T = Tree() for i in range(n): line = sys.stdin.readline().split() if len(line) == 1: T.show() elif line[0] == 'find': value = int(line[1]) print('yes' if T.find(value, T.root) else 'no') else: key = int(line[1]) T.insert(Node(key)) ```
output
1
18,535
13
37,071
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,536
13
37,072
"Correct Solution: ``` class Node: def __init__(self): self.key, self.left, self.right, self.parent = 0, None, None, None class BST: def __init__(self): self.root = None def insert(self, key): x, y = self.root, None z = Node() z.key = key while x != None: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y if y == None: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, key): r = self.root while r != None: if key == r.key: break elif key < r.key: r = r.left else: r = r.right return r def preOrder(self, r = -1): if r == -1: r = self.root if r == None: return print("", r.key, end = '') self.preOrder(r.left) self.preOrder(r.right) def inOrder(self, r = -1): if r == -1: r = self.root if r == None: return self.inOrder(r.left) print("", r.key, end = '') self.inOrder(r.right) tree = BST() for _ in range(int(input())): s = input() if s[0] == 'i': tree.insert(int(s[7:])) elif s[0] == 'p': tree.inOrder() print("") tree.preOrder() print("") else: print(['no', 'yes'][tree.find(int(s[5:])) != None]) ```
output
1
18,536
13
37,073
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,537
13
37,074
"Correct Solution: ``` class node: def __init__(self): self.p = -1 self.l = -1 self.r = -1 def preParse(u): if u == -1: return print(" " + str(u), end = '') preParse(T[u].l) preParse(T[u].r) def inParse(u): if u == -1: return inParse(T[u].l) print(" " + str(u), end = '') inParse(T[u].r) def postParse(u): if u == -1: return postParse(T[u].l) postParse(T[u].r) print(" " + str(u), end = '') root = -1 def insert(T, z): global root parent = -1 u = root while u != -1: parent = u if z < u: u = T[u].l else: u = T[u].r T[z].p = parent if parent == -1: root = z elif z < parent: T[parent].l = z else: T[parent].r = z def find(T, k): u = root while u != -1 and k != u: if k < u: u = T[u].l else: u = T[u].r return "no" if u == -1 else "yes" n = int(input()) cmdList = [input() for _ in range(n)] T = {int(cmd[7:]): node() for cmd in cmdList if cmd[0] == "i"} for cmd in cmdList: if cmd[0] == "p": inParse(root) print("") preParse(root) print("") elif cmd[0] == "f": print(find(T, int(cmd[5:]))) else: insert(T, int(cmd[7:])) ```
output
1
18,537
13
37,075
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,538
13
37,076
"Correct Solution: ``` class node(): def __init__(self, key, parent, left, right): self.key = key self.parent = parent self.left = left self.right = right root = None def insert(z): global root y = None x = root while x != None: y = x if z.key < x.key: x = x.left else: x = x.right z.parent = y if y == None: root = z elif z.key < y.key: y.left = z else: y.right = z def find(key): x = root answer = "no" while x != None: if key == x.key: answer = "yes" break if key < x.key: x = x.left else: x = x.right return answer def Inorder_TreeWalk(node): if node is None: return Inorder_TreeWalk(node.left) print(" " + str(node.key), end="") Inorder_TreeWalk(node.right) def Preorder_TreeWalk(node): if node is None: return print(" " + str(node.key), end="") Preorder_TreeWalk(node.left) Preorder_TreeWalk(node.right) def Main(): n = int(input()) global root for i in range(n): inp = input().split() ope = inp[0] if ope == "insert": insert(node(int(inp[1]), None, None, None)) elif ope == "find": print(find(int(inp[1]))) elif ope == "print": Inorder_TreeWalk(root) print() Preorder_TreeWalk(root) print() else: pass Main() ```
output
1
18,538
13
37,077
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,539
13
37,078
"Correct Solution: ``` # -*- coding: utf-8 -*- import sys sys.setrecursionlimit(100000) def insert(k, node): if k < node: if tree[node]["left"] == None: tree[node]["left"] = k tree[k] = {"parent": node, "left": None, "right": None} return else: insert(k, tree[node]["left"]) else: if tree[node]["right"] == None: tree[node]["right"] = k tree[k] = {"parent": node, "left": None, "right": None} return else: insert(k, tree[node]["right"]) def pre_order(n): result = [] if n == None: return [] result.append(str(n)) result.extend(pre_order(tree[n]["left"])) result.extend(pre_order(tree[n]["right"])) return result def in_order(n): result = [] if n == None: return [] result.extend(in_order(tree[n]["left"])) result.append(str(n)) result.extend(in_order(tree[n]["right"])) return result def find(k, node): while node != None and node != k: if k < node: node = tree[node]["left"] else: node = tree[node]["right"] return node M = int(input()) root = None while root == None: inp = [n for n in input().split()] if inp[0] == "print": print() print() else: root = int(inp[1]) tree = {root:{"parent": None, "left": None, "right": None}} for i, _ in enumerate(range(M-1)): inp = [n for n in input().split()] if inp[0] == "print": in_text = "" pre_text = "" print(" " + " ".join(in_order(root))) print(" " + " ".join(pre_order(root))) elif inp[0] == "find": res = find(int(inp[1]), root) if res == None: print("no") else: print("yes") else: insert(int(inp[1]), root) #if i%1000 == 0: # print("done {}/{}".format(i, M)) ```
output
1
18,539
13
37,079
Provide a correct Python 3 solution for this coding contest problem. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88
instruction
0
18,540
13
37,080
"Correct Solution: ``` class Tree(): def __init__(self): self.nodes = {} self.root = None def add_node(self, key): if key not in self.nodes: self.nodes[key] = Node(key) def insert(self, z_key): self.add_node(z_key) z = self.nodes[z_key] y = None # xの親 x = self.root while x is not None: y = x # 親を設定 if z.key < x.key: x = x.left else: x = x.right z.parent = y if y is None: self.root = z elif z.key < y.key: y.left = z else: y.right = z def find(self, key): x = self.root while x is not None: if key < x.key: x = x.left elif key > x.key: x = x.right else: print('yes') return print('no') return def __str__(self): ans_in, ans_pre = [], [] self.root.in_walk(ans_in) self.root.pre_walk(ans_pre) str_in = ' ' + ' '.join(map(str, ans_in)) str_pre = ' ' + ' '.join(map(str, ans_pre)) return str_in + '\n' + str_pre class Node(): def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def pre_walk(self, ans): ans.append(self.key) if self.left: self.left.pre_walk(ans) if self.right: self.right.pre_walk(ans) def in_walk(self, ans): if self.left: self.left.in_walk(ans) ans.append(self.key) if self.right: self.right.in_walk(ans) # ここからmain tree = Tree() n = int(input()) for i in range(n): line = list(map(str, input().split())) if line[0] == 'insert': key = int(line[1]) tree.insert(key) elif line[0] == 'find': key = int(line[1]) tree.find(key) else: print(tree) ```
output
1
18,540
13
37,081
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` from typing import Optional class Node: def __init__(self, arg_parent: Optional["Node"], arg_key: int, arg_left: Optional["Node"], arg_right: Optional["Node"]): self.parent = arg_parent self.key = arg_key self.left = arg_left self.right = arg_right def print_preorder(node: Node) -> None: print(f" {node.key}", end="") if node.left is not None: print_preorder(node.left) if node.right is not None: print_preorder(node.right) def print_inorder(node: Node) -> None: if node.left is not None: print_inorder(node.left) print(f" {node.key}", end="") if node.right is not None: print_inorder(node.right) def insert(root: Optional[Node], node: Node) -> Node: y: Optional[Node] = None x = root while x is not None: y = x if node.key < x.key: x = x.left else: x = x.right node.parent = y if y is None: root = node elif node.key < y.key: y.left = node else: y.right = node assert root is not None return root def find(root: Node, key: int) -> None: x: Optional[Node] = root while x is not None: if key == x.key: print("yes") return elif key < x.key: x = x.left else: x = x.right print("no") if __name__ == "__main__": root: Optional[Node] = None node_num = int(input()) for _ in range(node_num): command, *value = input().split() if "insert" == command: root = insert(root, Node(None, int(value[0]), None, None)) elif "find" == command: assert root is not None find(root, int(value[0])) elif "print" == command: assert root is not None print_inorder(root) print() print_preorder(root) print() else: pass ```
instruction
0
18,541
13
37,082
Yes
output
1
18,541
13
37,083
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` if __name__ == '__main__': import sys input = sys.stdin.readline NIL = -1 m = int(input()) root = NIL def insert(k): global root y = NIL x = root z = {'key':k, 'left':NIL, 'right':NIL} while x != NIL: y = x if z['key'] < x['key']: x = x['left'] else: x = x['right'] z['parent'] = y if y == NIL: root = z elif z['key'] < y['key']: y['left'] = z else: y['right'] = z def find(u, k): while u != NIL and k != u['key']: if k < u['key']: u = u['left'] else: u = u['right'] return u def inorder(u): if u == NIL: return inorder(u['left']) print(' ' + str(u['key']), end='') inorder(u['right']) def preorder(u): if u == NIL: return print(' ' + str(u['key']), end='') preorder(u['left']) preorder(u['right']) for _ in range(m): command = input() if command[0] == 'f': _, x = command.split() x = int(x) t = find(root, x) if t != NIL: print('yes') else: print('no') elif command[:6] == 'insert': _, x = command.split() x = int(x) insert(x) else: inorder(root) print('') # pythonのprintは最後に改行記号をつけてくれるので、これで改行できる preorder(root) print('') ```
instruction
0
18,542
13
37,084
Yes
output
1
18,542
13
37,085
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` from sys import stdin class Node: def __init__(self, v, parent=None, left=None, right=None): self.value = v self.parent = parent self.left = left self.right = right class BST: def __init__(self): self.root = None def insert(self, v): cur = self.root cur_p = None while cur != None: cur_p = cur if v < cur.value: cur = cur.left elif v > cur.value: cur = cur.right n = Node(v, cur_p) if cur_p == None: self.root = n elif v < cur_p.value: cur_p.left = n else: cur_p.right = n def preorder(self): def rec_preorder(t=self.root): if t != None: print(" ", t.value, sep="", end="") rec_preorder(t.left) rec_preorder(t.right) rec_preorder() print() def inorder(self): def rec_inorder(t=self.root): if t != None: rec_inorder(t.left) print(" ", t.value, sep="", end="") rec_inorder(t.right) rec_inorder() print() def find(self, x): def rec_find(t=self.root): if t == None: return False elif x > t.value: return rec_find(t.right) elif x < t.value: return rec_find(t.left) else: return True return rec_find() m = int(stdin.readline().rstrip()) t = BST() for _ in range(m): q = stdin.readline().rstrip().split() if q[0] == "insert": t.insert(int(q[1])) elif q[0] == "find": if t.find(int(q[1])): print("yes") else: print("no") elif q[0] == "print": t.inorder() t.preorder() ```
instruction
0
18,543
13
37,086
Yes
output
1
18,543
13
37,087
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` def insert(tree,node): parent=None child=root while child is not None: parent=child if node<child:child=tree[parent][0] else:child=tree[parent][1] if node<parent:tree[parent][0]=node else:tree[parent][1]=node def In_order(node): if node is None:return In_order(tree[node][0]) print(" {}".format(node), end="") In_order(tree[node][1]) def Pre_order(node): if node is None:return print(" {}".format(node), end="") Pre_order(tree[node][0]) Pre_order(tree[node][1]) def find(x,key): while x is not None and key!=x: if key<x:x=tree[x][0] else:x=tree[x][1] return x n=int(input()) tree,root={},None for i in range(n): order=input().split() if order[0]=="print": In_order(root);print() Pre_order(root);print() elif order[0]=="find": if find(root,int(order[1])) is not None:print("yes") else:print("no") elif order[0]=="insert": num=int(order[1]) if root is None: root=num tree[root]=[None,None] else: tree[num]=[None,None] insert(tree,num) ```
instruction
0
18,544
13
37,088
Yes
output
1
18,544
13
37,089
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` from collections import deque from enum import Enum, auto class Color(Enum): WHITE = auto() GRAY = auto() BLACK = auto() class BinaryTreeNode(): def __init__(self, parent=None, left=None, right=None, val=None): self.parent = parent self.left = left self.right = right self.val = val self.color = Color.WHITE class BinarySearchTree(): def __init__(self): self.root = None self.nodes = deque([]) def set_root(self, val): node = BinaryTreeNode(val=val) self.root = len(self.nodes) self.nodes.append(node) def insert(self, val): y = None x = self.root while x != None: y = x if val < self.nodes[x].val: x = self.nodes[x].left else: x = self.nodes[x].right node = BinaryTreeNode(val=val, parent=y) if y == None: self.set_root(val) elif node.val < self.nodes[y].val: self.nodes[y].left = len(self.nodes) self.nodes.append(node) else: self.nodes[y].right = len(self.nodes) self.nodes.append(node) def find(self, val): x = self.root while x != None: if self.nodes[x].val == val: return True elif self.nodes[x].val < val: x = self.nodes[x].right else: x = self.nodes[x].left return False def init_color(self): for node in self.nodes: node.color = Color.WHITE def preorder(self): preordered = [] self.init_color() def preorder_bfs(s): preordered.append(self.nodes[s].val) self.nodes[s].color = Color.GRAY if self.nodes[s].left != None and self.nodes[self.nodes[s].left].color == Color.WHITE: preorder_bfs(self.nodes[s].left) if self.nodes[s].right != None and self.nodes[self.nodes[s].right].color == Color.WHITE: preorder_bfs(self.nodes[s].right) self.nodes[s].color = Color.BLACK preorder_bfs(self.root) return preordered def inorder(self): inordered = [] self.init_color() inorder_stack = deque([]) def inorder_dfs_init(s): inorder_stack.append(s) inorder_dfs() def inorder_dfs(): u = inorder_stack.pop() self.nodes[u].color = Color.GRAY if self.nodes[u].left != None and self.nodes[self.nodes[u].left].color == Color.WHITE: inorder_stack.append(u) inorder_stack.append(self.nodes[u].left) inorder_dfs() inordered.append(self.nodes[u].val) if self.nodes[u].right != None and self.nodes[self.nodes[u].right].color == Color.WHITE: inorder_stack.append(self.nodes[u].right) inorder_dfs() self.nodes[u].color = Color.BLACK inorder_dfs_init(self.root) return inordered def print_elements(ordered): for ele in ordered: print(' {}'.format(ele), end='') print('') m = int(input()) bst = BinarySearchTree() for i in range(m): op = input() if op == 'print': print_elements(bst.inorder()) print_elements(bst.preorder()) continue ope, num = op.split(' ') num = int(num) if ope == 'insert': bst.insert(num) elif ope == 'find': if bst.find(num): print('yes') else: print('no') ```
instruction
0
18,545
13
37,090
No
output
1
18,545
13
37,091
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` m = int(input()) class Node: def __init__(self, key, left ,right): self.key = key self.left = left self.right = right class BinaryTree(): def __init__(self): self.root = None def getRoot(self): return self.root def setRoot(self, v): self.root = v def inorder(self, v=None): if v is None: v = self.root if v.left is not None: self.inorder(v.left) print(' ' + str(v.key), end='') if v.right is not None: self.inorder(v.right) def preorder(self, v=None): if v is None: v = self.root print(' ' + str(v.key), end='') if v.left is not None: self.preorder(v.left) if v.right is not None: self.preorder(v.right) def insert(T, z): y = None x = T.getRoot() while x is not None: y = x if z.key < x.key: x = x.left else: x = x.right z.p = y if y is None: T.setRoot(z) elif z.key < y.key: y.left = z else: y.right = z def find(T, k): x = T.getRoot() while x is not None: if x.key == k: print('yes') return elif x.key < k: x = x.right else: x = x.left print('no') T = BinaryTree() for i in range(m): inp = input().split() if inp[0] == 'print': T.inorder() print() T.preorder() elif inp[0] == 'find': find(T, int(inp[1])) else: v = Node(int(inp[1]), None, None) insert(T, v) ```
instruction
0
18,546
13
37,092
No
output
1
18,546
13
37,093
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` from io import StringIO class BinaryTree: class Node: def __init__(self, key): self.key = key self.left = None self.right = None self.parent = None def __init__(self): self.root = None self.output = StringIO() def insert(self, key): if self.root is None: self.root = self.Node(key) else: root = self.root temp = None while True: temp = root if key > root.key: root = root.right if root is None: temp.right = self.Node(key) break else: root = root.left if root is None: temp.left = self.Node(key) break def ini_print_inorder(self): self.output = StringIO() self.print_inorder(self.root) return self.output.getvalue() def ini_print_preorder(self): self.output = StringIO() self.print_preorder(self.root) return self.output.getvalue() def print_inorder(self, node): if node is not None: self.print_inorder(node.left) print(node.key, end = " ", file = self.output) self.print_inorder(node.right) def print_preorder(self, node): if node is not None: print(node.key, end = " ", file = self.output) self.print_preorder(node.left) self.print_preorder(node.right) def test_insert(self, keys): for k in keys: self.insert(k) def ini_find(self, key): print(self.find(key)) def find(self, key): root = self.root while root is not None: if key == root.key: return "yes" elif key < root.key: root = root.left else: root = root.right return "no" length = int(input()) b = BinaryTree() for _ in range(length): comm = input() if comm[0] == "i": com, num = comm.split(" ") b.insert(int(num)) elif comm[0] == "f": print(" ", end = "") print((b.ini_print_inorder())[:-1]) print(" ", end = "") print(b.ini_print_preorder()[:-1]) else: com, num = comm.split(" ") b.ini_find(num) ```
instruction
0
18,547
13
37,094
No
output
1
18,547
13
37,095
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Write a program which performs the following operations to a binary search tree $T$ by adding the find operation to A: Binary Search Tree I. * insert $k$: Insert a node containing $k$ as key into $T$. * find $k$: Report whether $T$ has a node containing $k$. * print: Print the keys of the binary search tree by inorder tree walk and preorder tree walk respectively. Constraints * The number of operations $\leq 500,000$ * The number of print operations $\leq 10$. * $-2,000,000,000 \leq key \leq 2,000,000,000$ * The height of the binary tree does not exceed 100 if you employ the above pseudo code. * The keys in the binary search tree are all different. Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k$, find $k$ or print are given. Output For each find $k$ operation, print "yes" if $T$ has a node containing $k$, "no" if not. In addition, for each print operation, print a list of keys obtained by inorder tree walk and preorder tree walk in a line respectively. Put a space character before each key. Example Input 10 insert 30 insert 88 insert 12 insert 1 insert 20 find 12 insert 17 insert 25 find 16 print Output yes no 1 12 17 20 25 30 88 30 12 1 20 17 25 88 Submitted Solution: ``` class BinarySearchTree: def __init__(self): self.root = None def insert(self, z): p = None x = self.root while x != None: p = x if z.key < x.key : x = x.left else : x = x.right z.p = p if p == None : self.root = z elif z.key < p.key: p.left = z else : p.right = z def get_inorder_list(self): def _get_inorder_list(root): l = root.left r = root.right if l: yield from _get_inorder_list(l) yield root.key if r: yield from _get_inorder_list(r) yield from _get_inorder_list(self.root) def get_preorder_list(self): def _get_preorder_list(root): l = root.left r = root.right yield root.key if l: yield from _get_preorder_list(l) if r: yield from _get_preorder_list(r) yield from _get_preorder_list(self.root) def find(self, k): def _find(k, x): if x == None : return False if x.key == k: return True return _find(k, x.left) or _find(k, x.right) return _find(k, self.root) class Node: def __init__(self, k): self.key = k self.p = None self.left = None self.right = None if __name__=='__main__': m = int(input()) T = BinarySearchTree() for _ in range(m): op = input().split() if op[0] == 'insert': T.insert( Node(int(op[1])) ) elif op[0] == 'find': print("yes" if T.find(int(op[1])) else "no") else: print("",*T.get_inorder_list()) print("",*T.get_preorder_list()) ```
instruction
0
18,548
13
37,096
No
output
1
18,548
13
37,097
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster. To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains n vertices, enumerated from 1 through n. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices S and T, along with any vertex v that you like. Then, Mikaela will count and give you the number of pairs of vertices (s, t) where s ∈ S and t ∈ T such that the simple path from s to t contains v. Mikaela the Goddess is busy and will be available to answer at most 11 111 questions. This is your only chance. Your task is to determine the tree and report its edges. Input The first line contains an integer n (2 ≤ n ≤ 500) — the number of vertices in the tree. Output When program has realized the tree and is ready to report the edges, print "ANSWER" in a separate line. Make sure that all letters are capitalized. Then, print n-1 lines, each containing two space-separated integers, denoting the vertices that are the endpoints of a certain edge. Each edge should be reported exactly once. Your program should then immediately terminate. Interaction For each question that you wish to ask, interact as follows. 1. First, print the size of S in its own line. In the following line, print |S| space-separated distinct integers, denoting the vertices in S. 2. Similarly, print the size of T in its own line. In the following line, print |T| space-separated distinct integers, denoting the vertices in T. 3. Then, in the final line, print v — the vertex that you choose for this question. 4. Read Mikaela's answer from input. Be reminded that S and T must be disjoint and non-empty. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If your program asks too many questions, asks an invalid question or does not correctly follow the interaction guideline above, it may receive an arbitrary verdict. Otherwise, your program will receive the Wrong Answer verdict if it reports an incorrect tree. Note that the tree is fixed beforehand and does not depend on your queries. Hacks Hacks should be formatted as follows. The first line should contain a single integer n (2 ≤ n ≤ 500) — the number of vertices in the tree. The following n-1 lines should each contain two space-separated integers u and v, denoting the existence of an undirected edge (u, v) (1 ≤ u, v ≤ n). Example Input 5 5 Output 3 1 2 3 2 4 5 2 ANSWER 1 2 2 3 3 4 2 5 Note In the sample, the tree is as follows. <image> n = 5 is given to the program. The program then asks Mikaela a question where S = \{1, 2, 3\}, T = \{4, 5\}, and v = 2, to which she replies with 5 (the pairs (s, t) are (1, 4), (1, 5), (2, 4), (2, 5), and (3, 5)). Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnyali_lk' import sys def query(s,t,v): print(len(s)) for i in s: print(i,end=' ') print() print(len(t)) for i in t: print(i,end=' ') print() print(v) sys.stdout.flush() return int(input()) n=int(input()) d=[0]*(n+1) for i in range(2,n+1): d[i]=query(list(range(2,i))+list(range(i+1,n+1)),[1],i) v=list(range(2,n+1)) v.sort(key=lambda x:d[x]) nofa=[] ans=[] for i in v: if len(nofa): for t in range(query([1],nofa,i)): l,r=1,len(nofa) while l<=r: mid=(l+r)//2 if query([1],nofa[:mid],i)>0: r=mid-1 else: l=mid+1 w=nofa[r] nofa.remove(w) ans.append((w,i)) nofa.append(i) for i in nofa: ans.append((i,1)) print("ANSWER") for i in ans: print(i[0],i[1]) ```
instruction
0
18,606
13
37,212
No
output
1
18,606
13
37,213
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. This is an interactive problem. A legendary tree rests deep in the forest. Legend has it that individuals who realize this tree would eternally become a Legendary Grandmaster. To help you determine the tree, Mikaela the Goddess has revealed to you that the tree contains n vertices, enumerated from 1 through n. She also allows you to ask her some questions as follows. For each question, you should tell Mikaela some two disjoint non-empty sets of vertices S and T, along with any vertex v that you like. Then, Mikaela will count and give you the number of pairs of vertices (s, t) where s ∈ S and t ∈ T such that the simple path from s to t contains v. Mikaela the Goddess is busy and will be available to answer at most 11 111 questions. This is your only chance. Your task is to determine the tree and report its edges. Input The first line contains an integer n (2 ≤ n ≤ 500) — the number of vertices in the tree. Output When program has realized the tree and is ready to report the edges, print "ANSWER" in a separate line. Make sure that all letters are capitalized. Then, print n-1 lines, each containing two space-separated integers, denoting the vertices that are the endpoints of a certain edge. Each edge should be reported exactly once. Your program should then immediately terminate. Interaction For each question that you wish to ask, interact as follows. 1. First, print the size of S in its own line. In the following line, print |S| space-separated distinct integers, denoting the vertices in S. 2. Similarly, print the size of T in its own line. In the following line, print |T| space-separated distinct integers, denoting the vertices in T. 3. Then, in the final line, print v — the vertex that you choose for this question. 4. Read Mikaela's answer from input. Be reminded that S and T must be disjoint and non-empty. After printing a query do not forget to output end of line and flush the output. Otherwise you will get Idleness limit exceeded. To do this, use: * fflush(stdout) or cout.flush() in C++; * System.out.flush() in Java; * flush(output) in Pascal; * stdout.flush() in Python; * see documentation for other languages. If your program asks too many questions, asks an invalid question or does not correctly follow the interaction guideline above, it may receive an arbitrary verdict. Otherwise, your program will receive the Wrong Answer verdict if it reports an incorrect tree. Note that the tree is fixed beforehand and does not depend on your queries. Hacks Hacks should be formatted as follows. The first line should contain a single integer n (2 ≤ n ≤ 500) — the number of vertices in the tree. The following n-1 lines should each contain two space-separated integers u and v, denoting the existence of an undirected edge (u, v) (1 ≤ u, v ≤ n). Example Input 5 5 Output 3 1 2 3 2 4 5 2 ANSWER 1 2 2 3 3 4 2 5 Note In the sample, the tree is as follows. <image> n = 5 is given to the program. The program then asks Mikaela a question where S = \{1, 2, 3\}, T = \{4, 5\}, and v = 2, to which she replies with 5 (the pairs (s, t) are (1, 4), (1, 5), (2, 4), (2, 5), and (3, 5)). Submitted Solution: ``` #!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'cnyali_lk' import sys def query(s,t,v): print(len(s)) for i in s: print(i,end=' ') print() print(len(t)) for i in t: print(i,end=' ') print() print(v) sys.stdout.flush() return int(input()) n=int(input()) d=[0]*(n+1) for i in range(2,n+1): d[i]=query(list(range(2,i))+list(range(i+1,n+1)),[1],i) v=list(range(2,n+1)) v.sort(key=lambda x:d[x]) nofa=[] ans=[] for i in v: if len(nofa): for t in range(query([1],nofa,i)): l,r=0,len(nofa)-1 while l<=r: mid=(l+r)//2 if query([1],nofa[:mid],i)>0: r=mid-1 else: l=mid+1 w=nofa[r+1] nofa.remove(w) ans.append((w,i)) nofa.append(i) for i in nofa: ans.append((i,1)) print("ANSWER") for i in ans: print(i[0],i[1]) ```
instruction
0
18,607
13
37,214
No
output
1
18,607
13
37,215
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any integer number x and add x to values written on all edges on the simple path between u and v. Note that in previous subtask x was allowed to be any real, here it has to be integer. For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -1 on the path from 4 to 5. <image> You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section. Leave is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice. Input The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of nodes in a tree. Each of the next n-1 lines contains three integers u, v, val (1 ≤ u, v ≤ n, u ≠ v, 0 ≤ val ≤ 10 000), meaning that there is an edge between nodes u and v with val written on it. It is guaranteed that these edges form a tree. It is guaranteed that all val numbers are pairwise different and even. Output If there aren't any sequences of operations which lead to the given configuration, output "NO". If it exists, output "YES" in the first line. In the second line output m — number of operations you are going to apply (0 ≤ m ≤ 10^5). Note that you don't have to minimize the number of the operations! In the next m lines output the operations in the following format: u, v, x (1 ≤ u, v ≤ n, u not = v, x — integer, -10^9 ≤ x ≤ 10^9), where u, v — leaves, x — number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above. Examples Input 5 1 2 2 2 3 4 3 4 10 3 5 18 Output NO Input 6 1 2 6 1 3 8 1 4 12 2 5 2 2 6 4 Output YES 4 3 6 1 4 6 3 3 4 7 4 5 2 Note The configuration from the first sample is drawn below, and it is impossible to achieve. <image> The sequence of operations from the second sample is illustrated below. <image> Submitted Solution: ``` #! /usr/bin/env python3 import sys try: # for methods Graph.gen_rand_tree() & Graph.draw() import networkx as nx from random import randint, random import matplotlib.pyplot as plt from matplotlib import MatplotlibDeprecationWarning from warnings import filterwarnings filterwarnings("ignore", category=MatplotlibDeprecationWarning) # for testing import os except: pass class Node: def __init__(self, num): self.num = num self.neighbs = [] self.nedges = [] self.marker = False self.val = None def add_neigh(self, oth, edge_weight=None): self.neighbs.append(oth) oth.neighbs.append(self) e = Edge(self, oth, edge_weight) self.nedges.append(e) oth.nedges.append(e) return e def is_leaf(self): return len(self.neighbs) == 1 def __repr__(self): return '({}: {}{}{})'.format( self.num, [i.num for i in self.neighbs], ', val: {}'.format(self.val) if self.val != None else '', ', Marked' if self.marker else '', ) class Edge: def __init__(self, n0, n1, weight=None): self.ends = [n0, n1] self.weight = weight self.marker = False def __repr__(self): return '<{} -- {}{}{}>'.format( self.ends[0].num, self.ends[1].num, ', weight: {}'.format(self.weight) if self.weight != None else '', ', Marked' if self.marker else '', ) class Graph: def __init__(self, N=None, E=None): self.N = N self.E = E self.nodes = [] self.edges = [] self.OFFSET = 1 def read_edges(self, file=sys.stdin): nodes = {} for _ in range(self.E): # read line vals_arr = file.readline().split() i, j = tuple(int(x) for x in vals_arr[:2]) if len(vals_arr) > 2: try: val = int(vals_arr[2]) except ValueError: val = float(vals_arr[2]) else: val = None # create nodes if i not in nodes: nodes[i] = Node(i) if j not in nodes: nodes[j] = Node(j) # connect nodes e = nodes[i].add_neigh(nodes[j], val) self.edges.append(e) self.nodes = [nodes[i] for i in range(self.OFFSET, len(nodes) + self.OFFSET)] if self.N == None: self.N = len(self.nodes) else: assert self.N == len(self.nodes), \ 'N = {}, len = {}'.format(self.N, len(self.nodes)) def read_nodes(self, file=sys.stdin): self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for i in range(self.OFFSET, self.N + self.OFFSET): ni = self.nodes[i-self.OFFSET] ints = tuple(int(x) for x in file.readline().split()) for j in ints: nj = self.nodes[j-self.OFFSET] if nj not in ni.neighbs: e = ni.add_neigh(nj) self.edges.append(e) if self.E == None: self.E = len(self.edges) else: assert self.E == len(self.edges), \ 'E = {}, len = {}'.format(self.E, len(self.edges)) def write_edges(self, file=sys.stdout): for e in self.edges: print('{} {}{}'.format( e.ends[0].num, e.ends[1].num, ' {}'.format(e.weight) if e.weight != None else ''), file=file) def write_nodes(self, file=sys.stdout): sorted_nodes = sorted(self.nodes, key = lambda x: x.num) for n in sorted_nodes: print(' '.join(str(x.num) for x in n.neighbs), file=file) def gen_rand_tree(self, weighted=False, is_weights_int=True): if self.E != None: print('Number of edges will be changed') # Make tree tries = max(1000, self.N ** 2) g = nx.random_powerlaw_tree(self.N, tries=tries) relabel_map = {i: i+1 for i in range(self.N)} nx.relabel_nodes(g, relabel_map) # Store data to self. fields self.E = len(g.edges()) self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for nx_e in g.edges(): i, j = nx_e[0], nx_e[1] ni, nj = self.nodes[i], self.nodes[j] e = ni.add_neigh(nj) self.edges.append(e) # Set random weights if weighted: for e in self.edges: w = randint(0, 10) if is_weights_int else round(random()*10, 1) e.weight = w def check(self): assert len(self.nodes) == self.N assert len(self.edges) == self.E self.drop_edge_markers() for node in self.nodes: assert len(node.neighbs) == len(node.nedges), \ ('Incorrect node {}'.format(node) + '\nlen(.neighbs): ' '{}'.format(len(node.neighbs)) + '\nlen(.nedges): ' '{}'.format(len(node.nedges))) for neith, nedge in zip(node.neighbs, node.nedges): assert len(nedge.ends) == 2, \ 'Too many ends of edge {}:\n{}'.format(nedge, nedge.ends) assert node in nedge.ends, \ ('Edge {}'.format(nedge) + ' exists in node ' '{}'.format(node) + ' neighbors list, ' 'but not vice versa') oth_end = \ nedge.ends[0] if node is nedge.ends[1] else nedge.ends[1] assert neith is oth_end, \ ('Node {}'.format(neith) + ' should be the end of edge ' '{}'.format(nedge) + ' instead of {}'.format(oth_end)) nedge.marker = True for e in self.edges: assert e.marker, 'Isolated edge {}'.format(e) e.marker = False #TODO: del_node, del_edge, change_end def drop_node_markers(self): for node in self.nodes: node.marker = False def init_node_vals(self, val): for node in self.nodes: node.val = val def drop_edge_markers(self): for edge in self.edges: edge.marker = False def init_edge_weights(self, val): for edge in self.edges: edge.val = val def draw(self, weighted=False, dot_output=False, interactive=True): # Make graph & fill data for .dot output g = nx.Graph() for n in self.nodes: g.add_node(n.num, color = 'red' if n.marker else 'black') for e in self.edges: if weighted: g.add_edge(e.ends[0].num, e.ends[1].num, label=e.weight, color = 'red' if e.marker else 'black') else: g.add_edge(e.ends[0].num, e.ends[1].num, color = 'red' if e.marker else 'black') # Fill data for NetworkX draw pos = nx.spring_layout(g) ecol_map = ['red' if e.marker else 'black' for e in self.edges] ncol_map = ['red' if n.marker else 'gray' for n in self.nodes] nx.draw_networkx(g, pos=pos, node_color=ncol_map, edge_color=ecol_map, with_labels=True) if weighted: elab_map = nx.get_edge_attributes(g,'label') nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=elab_map) # Save & show if dot_output: nx.drawing.nx_pydot.write_dot(g, 'fig.dot') plt.axis('off') plt.savefig('fig.png') if interactive: plt.show() plt.clf() def __repr__(self): return '\n'.join(str(node) for node in self.nodes) def __getitem__(self, i): return self.nodes[i - self.OFFSET] def solve_ABC(A, B, C, edge, NEXT, actions, w=0): actions.append((A.num, B.num, w//2)) actions.append((A.num, C.num, w//2)) actions.append((B.num, C.num, -w//2)) def traversal(CUR, edge, ROOT, graph_leafs, actions, prev_edge=None): NEXT = next(n for n in edge.ends if n is not CUR) if NEXT.is_leaf(): # find OTH_LEAF for OTH_LEAF, nedge in zip(CUR.neighbs, CUR.nedges): if nedge is not edge and nedge is not prev_edge: break while not OTH_LEAF.is_leaf(): nedge = next(e for e in OTH_LEAF.nedges if e is not nedge) OTH_LEAF = next(n for n in nedge.ends if n is not OTH_LEAF) solve_ABC(NEXT, ROOT, OTH_LEAF, edge, CUR, actions, edge.weight) edge.weight = 0 return NEXT, 0 else: leafs = [] cumul_w = 0 for neigh, nedge in zip(NEXT.neighbs, NEXT.nedges): if neigh is CUR: continue leaf, w = traversal(NEXT, nedge, ROOT, graph_leafs, actions, edge) leafs.append(leaf) cumul_w += w solve_ABC(ROOT, leafs[0], leafs[1], edge, NEXT, actions, edge.weight - cumul_w) return leafs[0], cumul_w + edge.weight def solve(g): from time import sleep if len(g.edges) == 1: e = g.edges[0] print('1\n1 2 {}'.format(e.weight)) return # first end & contig. edge graph_leafs = [n for n in g.nodes if len(n.neighbs) == 1] R = graph_leafs[0] edge = R.nedges[0] actions = [] traversal(R, edge, R, graph_leafs, actions) # Actions output print(len(actions)) for a in actions: print(' '.join(str(i) for i in a)) if __name__ == '__main__': N = int(sys.stdin.readline()) E = N - 1 g = Graph(N, E) g.read_edges() #print(g) #g.draw(True) ends = [node for node in g.nodes if len(node.neighbs) == 1] for n in g.nodes: if len(n.neighbs) == 2: print('NO') break else: print('YES') solve(g) ```
instruction
0
18,624
13
37,248
No
output
1
18,624
13
37,249
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any integer number x and add x to values written on all edges on the simple path between u and v. Note that in previous subtask x was allowed to be any real, here it has to be integer. For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -1 on the path from 4 to 5. <image> You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section. Leave is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice. Input The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of nodes in a tree. Each of the next n-1 lines contains three integers u, v, val (1 ≤ u, v ≤ n, u ≠ v, 0 ≤ val ≤ 10 000), meaning that there is an edge between nodes u and v with val written on it. It is guaranteed that these edges form a tree. It is guaranteed that all val numbers are pairwise different and even. Output If there aren't any sequences of operations which lead to the given configuration, output "NO". If it exists, output "YES" in the first line. In the second line output m — number of operations you are going to apply (0 ≤ m ≤ 10^5). Note that you don't have to minimize the number of the operations! In the next m lines output the operations in the following format: u, v, x (1 ≤ u, v ≤ n, u not = v, x — integer, -10^9 ≤ x ≤ 10^9), where u, v — leaves, x — number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above. Examples Input 5 1 2 2 2 3 4 3 4 10 3 5 18 Output NO Input 6 1 2 6 1 3 8 1 4 12 2 5 2 2 6 4 Output YES 4 3 6 1 4 6 3 3 4 7 4 5 2 Note The configuration from the first sample is drawn below, and it is impossible to achieve. <image> The sequence of operations from the second sample is illustrated below. <image> Submitted Solution: ``` #! /usr/bin/env python3 import sys try: # for methods Graph.gen_rand_tree() & Graph.draw() import networkx as nx from random import randint, random import matplotlib.pyplot as plt from matplotlib import MatplotlibDeprecationWarning from warnings import filterwarnings filterwarnings("ignore", category=MatplotlibDeprecationWarning) # for testing import os except: pass class Node: def __init__(self, num): self.num = num self.neighbs = [] self.nedges = [] self.marker = False self.val = None def add_neigh(self, oth, edge_weight=None): self.neighbs.append(oth) oth.neighbs.append(self) e = Edge(self, oth, edge_weight) self.nedges.append(e) oth.nedges.append(e) return e def is_leaf(self): return len(self.neighbs) == 1 def __repr__(self): return '({}: {}{}{})'.format( self.num, [i.num for i in self.neighbs], ', val: {}'.format(self.val) if self.val != None else '', ', Marked' if self.marker else '', ) class Edge: def __init__(self, n0, n1, weight=None): self.ends = [n0, n1] self.weight = weight self.marker = False def __repr__(self): return '<{} -- {}{}{}>'.format( self.ends[0].num, self.ends[1].num, ', weight: {}'.format(self.weight) if self.weight != None else '', ', Marked' if self.marker else '', ) class Graph: def __init__(self, N=None, E=None): self.N = N self.E = E self.nodes = [] self.edges = [] self.OFFSET = 1 def read_edges(self, file=sys.stdin): nodes = {} for _ in range(self.E): # read line vals_arr = file.readline().split() i, j = tuple(int(x) for x in vals_arr[:2]) if len(vals_arr) > 2: try: val = int(vals_arr[2]) except ValueError: val = float(vals_arr[2]) else: val = None # create nodes if i not in nodes: nodes[i] = Node(i) if j not in nodes: nodes[j] = Node(j) # connect nodes e = nodes[i].add_neigh(nodes[j], val) self.edges.append(e) self.nodes = [nodes[i] for i in range(self.OFFSET, len(nodes) + self.OFFSET)] if self.N == None: self.N = len(self.nodes) else: assert self.N == len(self.nodes), \ 'N = {}, len = {}'.format(self.N, len(self.nodes)) def read_nodes(self, file=sys.stdin): self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for i in range(self.OFFSET, self.N + self.OFFSET): ni = self.nodes[i-self.OFFSET] ints = tuple(int(x) for x in file.readline().split()) for j in ints: nj = self.nodes[j-self.OFFSET] if nj not in ni.neighbs: e = ni.add_neigh(nj) self.edges.append(e) if self.E == None: self.E = len(self.edges) else: assert self.E == len(self.edges), \ 'E = {}, len = {}'.format(self.E, len(self.edges)) def write_edges(self, file=sys.stdout): for e in self.edges: print('{} {}{}'.format( e.ends[0].num, e.ends[1].num, ' {}'.format(e.weight) if e.weight != None else ''), file=file) def write_nodes(self, file=sys.stdout): sorted_nodes = sorted(self.nodes, key = lambda x: x.num) for n in sorted_nodes: print(' '.join(str(x.num) for x in n.neighbs), file=file) def gen_rand_tree(self, weighted=False, is_weights_int=True): if self.E != None: print('Number of edges will be changed') # Make tree tries = max(1000, self.N ** 2) g = nx.random_powerlaw_tree(self.N, tries=tries) relabel_map = {i: i+1 for i in range(self.N)} nx.relabel_nodes(g, relabel_map) # Store data to self. fields self.E = len(g.edges()) self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for nx_e in g.edges(): i, j = nx_e[0], nx_e[1] ni, nj = self.nodes[i], self.nodes[j] e = ni.add_neigh(nj) self.edges.append(e) # Set random weights if weighted: for e in self.edges: w = randint(0, 10) if is_weights_int else round(random()*10, 1) e.weight = w def check(self): assert len(self.nodes) == self.N assert len(self.edges) == self.E self.drop_edge_markers() for node in self.nodes: assert len(node.neighbs) == len(node.nedges), \ ('Incorrect node {}'.format(node) + '\nlen(.neighbs): ' '{}'.format(len(node.neighbs)) + '\nlen(.nedges): ' '{}'.format(len(node.nedges))) for neith, nedge in zip(node.neighbs, node.nedges): assert len(nedge.ends) == 2, \ 'Too many ends of edge {}:\n{}'.format(nedge, nedge.ends) assert node in nedge.ends, \ ('Edge {}'.format(nedge) + ' exists in node ' '{}'.format(node) + ' neighbors list, ' 'but not vice versa') oth_end = \ nedge.ends[0] if node is nedge.ends[1] else nedge.ends[1] assert neith is oth_end, \ ('Node {}'.format(neith) + ' should be the end of edge ' '{}'.format(nedge) + ' instead of {}'.format(oth_end)) nedge.marker = True for e in self.edges: assert e.marker, 'Isolated edge {}'.format(e) e.marker = False #TODO: del_node, del_edge, change_end def drop_node_markers(self): for node in self.nodes: node.marker = False def init_node_vals(self, val): for node in self.nodes: node.val = val def drop_edge_markers(self): for edge in self.edges: edge.marker = False def init_edge_weights(self, val): for edge in self.edges: edge.val = val def draw(self, weighted=False, dot_output=False, interactive=True): # Make graph & fill data for .dot output g = nx.Graph() for n in self.nodes: g.add_node(n.num, color = 'red' if n.marker else 'black') for e in self.edges: if weighted: g.add_edge(e.ends[0].num, e.ends[1].num, label=e.weight, color = 'red' if e.marker else 'black') else: g.add_edge(e.ends[0].num, e.ends[1].num, color = 'red' if e.marker else 'black') # Fill data for NetworkX draw pos = nx.spring_layout(g) ecol_map = ['red' if e.marker else 'black' for e in self.edges] ncol_map = ['red' if n.marker else 'gray' for n in self.nodes] nx.draw_networkx(g, pos=pos, node_color=ncol_map, edge_color=ecol_map, with_labels=True) if weighted: elab_map = nx.get_edge_attributes(g,'label') nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=elab_map) # Save & show if dot_output: nx.drawing.nx_pydot.write_dot(g, 'fig.dot') plt.axis('off') plt.savefig('fig.png') if interactive: plt.show() plt.clf() def __repr__(self): return '\n'.join(str(node) for node in self.nodes) def __getitem__(self, i): return self.nodes[i - self.OFFSET] def solve_ABC(A, B, C, edge, NEXT, actions, w=0): actions.append((A.num, B.num, w//2)) actions.append((A.num, C.num, w//2)) actions.append((B.num, C.num, -w//2)) def traversal(CUR, edge, ROOT, graph_leafs, actions, prev_edge=None): NEXT = next(n for n in edge.ends if n is not CUR) if NEXT.is_leaf(): # find OTH_LEAF for OTH_LEAF, nedge in zip(CUR.neighbs, CUR.nedges): if nedge is not edge and nedge is not prev_edge: break while not OTH_LEAF.is_leaf(): nedge = next(e for e in OTH_LEAF.nedges if e is not nedge) OTH_LEAF = next(n for n in nedge.ends if n is not OTH_LEAF) solve_ABC(NEXT, ROOT, OTH_LEAF, edge, CUR, actions, edge.weight) edge.weight = 0 return NEXT, 0 else: leafs = [] cumul_w = 0 for neigh, nedge in zip(NEXT.neighbs, NEXT.nedges): if neigh is CUR: continue leaf, w = traversal(NEXT, nedge, ROOT, graph_leafs, actions, edge) leafs.append(leaf) cumul_w += w cumul_w = edge.weight - cumul_w solve_ABC(ROOT, leafs[0], leafs[1], edge, NEXT, actions, cumul_w) return leafs[0], cumul_w def solve(g): from time import sleep if len(g.edges) == 1: e = g.edges[0] print('1\n1 2 {}'.format(-e.weight)) return # first end & contig. edge graph_leafs = [n for n in g.nodes if len(n.neighbs) == 1] R = graph_leafs[0] edge = R.nedges[0] actions = [] traversal(R, edge, R, graph_leafs, actions) # Actions output print(len(actions)) for a in actions: print(' '.join(str(i) for i in a)) if __name__ == '__main__': N = int(sys.stdin.readline()) E = N - 1 g = Graph(N, E) g.read_edges() #print(g) #g.draw(True) ends = [node for node in g.nodes if len(node.neighbs) == 1] for n in g.nodes: if len(n.neighbs) == 2: print('NO') break else: print('YES') solve(g) ```
instruction
0
18,625
13
37,250
No
output
1
18,625
13
37,251
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Note that this is the second problem of the two similar problems. You can hack this problem if you solve it. But you can hack the previous problem only if you solve both problems. You are given a tree with n nodes. In the beginning, 0 is written on all edges. In one operation, you can choose any 2 distinct leaves u, v and any integer number x and add x to values written on all edges on the simple path between u and v. Note that in previous subtask x was allowed to be any real, here it has to be integer. For example, on the picture below you can see the result of applying two operations to the graph: adding 2 on the path from 7 to 6, and then adding -1 on the path from 4 to 5. <image> You are given some configuration of nonnegative integer pairwise different even numbers, written on the edges. For a given configuration determine if it is possible to achieve it with these operations, and, if it is possible, output the sequence of operations that leads to the given configuration. Constraints on the operations are listed in the output format section. Leave is a node of a tree of degree 1. Simple path is a path that doesn't contain any node twice. Input The first line contains a single integer n (2 ≤ n ≤ 1000) — the number of nodes in a tree. Each of the next n-1 lines contains three integers u, v, val (1 ≤ u, v ≤ n, u ≠ v, 0 ≤ val ≤ 10 000), meaning that there is an edge between nodes u and v with val written on it. It is guaranteed that these edges form a tree. It is guaranteed that all val numbers are pairwise different and even. Output If there aren't any sequences of operations which lead to the given configuration, output "NO". If it exists, output "YES" in the first line. In the second line output m — number of operations you are going to apply (0 ≤ m ≤ 10^5). Note that you don't have to minimize the number of the operations! In the next m lines output the operations in the following format: u, v, x (1 ≤ u, v ≤ n, u not = v, x — integer, -10^9 ≤ x ≤ 10^9), where u, v — leaves, x — number we are adding. It is guaranteed that if there exists a sequence of operations producing given configuration, then there exists a sequence of operations producing given configuration, satisfying all the conditions above. Examples Input 5 1 2 2 2 3 4 3 4 10 3 5 18 Output NO Input 6 1 2 6 1 3 8 1 4 12 2 5 2 2 6 4 Output YES 4 3 6 1 4 6 3 3 4 7 4 5 2 Note The configuration from the first sample is drawn below, and it is impossible to achieve. <image> The sequence of operations from the second sample is illustrated below. <image> Submitted Solution: ``` #! /usr/bin/env python3 import sys try: # for methods Graph.gen_rand_tree() & Graph.draw() import networkx as nx from random import randint, random import matplotlib.pyplot as plt from matplotlib import MatplotlibDeprecationWarning from warnings import filterwarnings filterwarnings("ignore", category=MatplotlibDeprecationWarning) # for testing import os except: pass class Node: def __init__(self, num): self.num = num self.neighbs = [] self.nedges = [] self.marker = False self.val = None def add_neigh(self, oth, edge_weight=None): self.neighbs.append(oth) oth.neighbs.append(self) e = Edge(self, oth, edge_weight) self.nedges.append(e) oth.nedges.append(e) return e def is_leaf(self): return len(self.neighbs) == 1 def __repr__(self): return '({}: {}{}{})'.format( self.num, [i.num for i in self.neighbs], ', val: {}'.format(self.val) if self.val != None else '', ', Marked' if self.marker else '', ) class Edge: def __init__(self, n0, n1, weight=None): self.ends = [n0, n1] self.weight = weight self.marker = False def __repr__(self): return '<{} -- {}{}{}>'.format( self.ends[0].num, self.ends[1].num, ', weight: {}'.format(self.weight) if self.weight != None else '', ', Marked' if self.marker else '', ) class Graph: def __init__(self, N=None, E=None): self.N = N self.E = E self.nodes = [] self.edges = [] self.OFFSET = 1 def read_edges(self, file=sys.stdin): nodes = {} for _ in range(self.E): # read line vals_arr = file.readline().split() i, j = tuple(int(x) for x in vals_arr[:2]) if len(vals_arr) > 2: try: val = int(vals_arr[2]) except ValueError: val = float(vals_arr[2]) else: val = None # create nodes if i not in nodes: nodes[i] = Node(i) if j not in nodes: nodes[j] = Node(j) # connect nodes e = nodes[i].add_neigh(nodes[j], val) self.edges.append(e) self.nodes = [nodes[i] for i in range(self.OFFSET, len(nodes) + self.OFFSET)] if self.N == None: self.N = len(self.nodes) else: assert self.N == len(self.nodes), \ 'N = {}, len = {}'.format(self.N, len(self.nodes)) def read_nodes(self, file=sys.stdin): self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for i in range(self.OFFSET, self.N + self.OFFSET): ni = self.nodes[i-self.OFFSET] ints = tuple(int(x) for x in file.readline().split()) for j in ints: nj = self.nodes[j-self.OFFSET] if nj not in ni.neighbs: e = ni.add_neigh(nj) self.edges.append(e) if self.E == None: self.E = len(self.edges) else: assert self.E == len(self.edges), \ 'E = {}, len = {}'.format(self.E, len(self.edges)) def write_edges(self, file=sys.stdout): for e in self.edges: print('{} {}{}'.format( e.ends[0].num, e.ends[1].num, ' {}'.format(e.weight) if e.weight != None else ''), file=file) def write_nodes(self, file=sys.stdout): sorted_nodes = sorted(self.nodes, key = lambda x: x.num) for n in sorted_nodes: print(' '.join(str(x.num) for x in n.neighbs), file=file) def gen_rand_tree(self, weighted=False, is_weights_int=True): if self.E != None: print('Number of edges will be changed') # Make tree tries = max(1000, self.N ** 2) g = nx.random_powerlaw_tree(self.N, tries=tries) relabel_map = {i: i+1 for i in range(self.N)} nx.relabel_nodes(g, relabel_map) # Store data to self. fields self.E = len(g.edges()) self.nodes = [Node(i) for i in range(self.OFFSET, self.N + self.OFFSET)] for nx_e in g.edges(): i, j = nx_e[0], nx_e[1] ni, nj = self.nodes[i], self.nodes[j] e = ni.add_neigh(nj) self.edges.append(e) # Set random weights if weighted: for e in self.edges: w = randint(0, 10) if is_weights_int else round(random()*10, 1) e.weight = w def check(self): assert len(self.nodes) == self.N assert len(self.edges) == self.E self.drop_edge_markers() for node in self.nodes: assert len(node.neighbs) == len(node.nedges), \ ('Incorrect node {}'.format(node) + '\nlen(.neighbs): ' '{}'.format(len(node.neighbs)) + '\nlen(.nedges): ' '{}'.format(len(node.nedges))) for neith, nedge in zip(node.neighbs, node.nedges): assert len(nedge.ends) == 2, \ 'Too many ends of edge {}:\n{}'.format(nedge, nedge.ends) assert node in nedge.ends, \ ('Edge {}'.format(nedge) + ' exists in node ' '{}'.format(node) + ' neighbors list, ' 'but not vice versa') oth_end = \ nedge.ends[0] if node is nedge.ends[1] else nedge.ends[1] assert neith is oth_end, \ ('Node {}'.format(neith) + ' should be the end of edge ' '{}'.format(nedge) + ' instead of {}'.format(oth_end)) nedge.marker = True for e in self.edges: assert e.marker, 'Isolated edge {}'.format(e) e.marker = False #TODO: del_node, del_edge, change_end def drop_node_markers(self): for node in self.nodes: node.marker = False def init_node_vals(self, val): for node in self.nodes: node.val = val def drop_edge_markers(self): for edge in self.edges: edge.marker = False def init_edge_weights(self, val): for edge in self.edges: edge.val = val def draw(self, weighted=False, dot_output=False, interactive=True): # Make graph & fill data for .dot output g = nx.Graph() for n in self.nodes: g.add_node(n.num, color = 'red' if n.marker else 'black') for e in self.edges: if weighted: g.add_edge(e.ends[0].num, e.ends[1].num, label=e.weight, color = 'red' if e.marker else 'black') else: g.add_edge(e.ends[0].num, e.ends[1].num, color = 'red' if e.marker else 'black') # Fill data for NetworkX draw pos = nx.spring_layout(g) ecol_map = ['red' if e.marker else 'black' for e in self.edges] ncol_map = ['red' if n.marker else 'gray' for n in self.nodes] nx.draw_networkx(g, pos=pos, node_color=ncol_map, edge_color=ecol_map, with_labels=True) if weighted: elab_map = nx.get_edge_attributes(g,'label') nx.draw_networkx_edge_labels(g, pos=pos, edge_labels=elab_map) # Save & show if dot_output: nx.drawing.nx_pydot.write_dot(g, 'fig.dot') plt.axis('off') plt.savefig('fig.png') if interactive: plt.show() plt.clf() def __repr__(self): return '\n'.join(str(node) for node in self.nodes) def __getitem__(self, i): return self.nodes[i - self.OFFSET] def solve_ABC(A, B, C, edge, NEXT, actions, w=0): actions.append((A.num, B.num, w//2)) actions.append((A.num, C.num, w//2)) actions.append((B.num, C.num, -w//2)) def traversal(CUR, edge, ROOT, graph_leafs, actions, prev_edge=None): NEXT = next(n for n in edge.ends if n is not CUR) if NEXT.is_leaf(): # find OTH_LEAF for OTH_LEAF, nedge in zip(CUR.neighbs, CUR.nedges): if nedge is not edge and nedge is not prev_edge: break while not OTH_LEAF.is_leaf(): nedge = next(e for e in OTH_LEAF.nedges if e is not nedge) OTH_LEAF = next(n for n in nedge.ends if n is not OTH_LEAF) solve_ABC(NEXT, ROOT, OTH_LEAF, edge, CUR, actions, edge.weight) edge.weight = 0 return NEXT, 0 else: leafs = [] cumul_w = 0 for neigh, nedge in zip(NEXT.neighbs, NEXT.nedges): if neigh is CUR: continue leaf, w = traversal(NEXT, nedge, ROOT, graph_leafs, actions, edge) leafs.append(leaf) cumul_w += w cumul_w = edge.weight - cumul_w solve_ABC(ROOT, leafs[0], leafs[1], edge, NEXT, actions, cumul_w) return leafs[0], cumul_w def solve(g): from time import sleep if len(g.edges) == 1: e = g.edges[0] print('1\n1 2 {}'.format(e.weight)) return # first end & contig. edge graph_leafs = [n for n in g.nodes if len(n.neighbs) == 1] R = graph_leafs[0] edge = R.nedges[0] actions = [] traversal(R, edge, R, graph_leafs, actions) # Actions output print(len(actions)) for a in actions: print(' '.join(str(i) for i in a)) if __name__ == '__main__': N = int(sys.stdin.readline()) E = N - 1 g = Graph(N, E) g.read_edges() #print(g) #g.draw(True) ends = [node for node in g.nodes if len(node.neighbs) == 1] for n in g.nodes: if len(n.neighbs) == 2: print('NO') break else: print('YES') solve(g) ```
instruction
0
18,626
13
37,252
No
output
1
18,626
13
37,253
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a positive integer D. Let's build the following graph from it: * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; * the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: <image> Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12]. There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime. Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0. So the shortest path between two vertices v and u is the path that has the minimal possible length. Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges. You are given q queries of the following form: * v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353. Input The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from. The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries. Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D). Output Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353. Examples Input 12 3 4 4 12 1 3 4 Output 1 3 1 Input 1 1 1 1 Output 1 Input 288807105787200 4 46 482955026400 12556830686400 897 414 12556830686400 4443186242880 325 Output 547558588 277147129 457421435 702277623 Note In the first example: * The first query is only the empty path — length 0; * The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5). * The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
instruction
0
18,667
13
37,334
Tags: combinatorics, graphs, greedy, math, number theory Correct Solution: ``` from sys import stdin mod=998244353 N=10**5+3 fac=[1]*(N+1) for i in range(1,N+1): fac[i]=fac[i-1]*i%mod inv_fac=[1]*(N+1) inv_fac[N]=pow(fac[N],mod-2,mod) for i in range(N-1,0,-1): inv_fac[i]=inv_fac[i+1]*(i+1)%mod D=int(stdin.readline()) A=[] for i in range(2,int(D**.5)+1): c=0 while D%i==0: D//=i c+=1 if c!=0: A.append(i) if D>=2: A.append(D) l=len(A) q=int(stdin.readline()) for _ in range(q): u,v=map(int,stdin.readline().split()) l1=[0]*l l2=[0]*l l3=[0]*l for i in range(l): while u%A[i]==0: l1[i]+=1 u//=A[i] while v%A[i]==0: l2[i]+=1 v//=A[i] l3[i]=l1[i]-l2[i] ans1=1 ans2=1 s1=0 s2=0 for i in range(l): if l3[i]>=0: ans1=ans1*inv_fac[l3[i]]%mod s1+=l3[i] else: ans2=ans2*inv_fac[-l3[i]]%mod s2-=l3[i] ans1=ans1*fac[s1]%mod ans2=ans2*fac[s2]%mod print(ans1*ans2%mod) ```
output
1
18,667
13
37,335
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a positive integer D. Let's build the following graph from it: * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; * the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: <image> Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12]. There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime. Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0. So the shortest path between two vertices v and u is the path that has the minimal possible length. Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges. You are given q queries of the following form: * v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353. Input The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from. The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries. Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D). Output Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353. Examples Input 12 3 4 4 12 1 3 4 Output 1 3 1 Input 1 1 1 1 Output 1 Input 288807105787200 4 46 482955026400 12556830686400 897 414 12556830686400 4443186242880 325 Output 547558588 277147129 457421435 702277623 Note In the first example: * The first query is only the empty path — length 0; * The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5). * The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
instruction
0
18,668
13
37,336
Tags: combinatorics, graphs, greedy, math, number theory Correct Solution: ``` # region fastio # from https://codeforces.com/contest/1333/submission/75948789 import sys, io, os BUFSIZE = 8192 class FastIO(io.IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = io.BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(io.IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") def print(*args, **kwargs): """Prints the values to a stream, or to sys.stdout by default.""" sep, file = kwargs.pop("sep", " "), kwargs.pop("file", sys.stdout) at_start = True for x in args: if not at_start: file.write(sep) file.write(str(x)) at_start = False file.write(kwargs.pop("end", "\n")) if kwargs.pop("flush", False): file.flush() sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") # endregion cache = {} def calc_paths(n): if n in cache: return cache[n] n_ = n i = 2 numer = denom = 1 nu = de = 0 while i*i<=n: while n%i==0: de += 1 nu += 1 denom = denom * de % mod numer = numer * nu % mod n //= i de = 0 i += 1 if n > 1: de += 1 nu += 1 denom = denom * de % mod numer = numer * nu % mod res = numer * pow(denom, mod-2, mod) % mod cache[n_] = res return res from math import gcd D = int(input()) Q = int(input()) VU = [list(map(int, input().split())) for _ in range(Q)] mod = 998244353 factorial = [1] * 100 for i in range(1, 100): factorial[i] = factorial[i-1] * i % mod for v, u in VU: g = gcd(v, u) print(calc_paths(v//g) * calc_paths(u//g) % mod) ```
output
1
18,668
13
37,337
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a positive integer D. Let's build the following graph from it: * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; * the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: <image> Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12]. There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime. Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0. So the shortest path between two vertices v and u is the path that has the minimal possible length. Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges. You are given q queries of the following form: * v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353. Input The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from. The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries. Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D). Output Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353. Examples Input 12 3 4 4 12 1 3 4 Output 1 3 1 Input 1 1 1 1 Output 1 Input 288807105787200 4 46 482955026400 12556830686400 897 414 12556830686400 4443186242880 325 Output 547558588 277147129 457421435 702277623 Note In the first example: * The first query is only the empty path — length 0; * The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5). * The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
instruction
0
18,669
13
37,338
Tags: combinatorics, graphs, greedy, math, number theory Correct Solution: ``` import io, os import sys input = io.BytesIO(os.read(0,os.fstat(0).st_size)).readline D=int(input()) q=int(input()) mod=998244353 Q=[tuple(map(int,input().split())) for i in range(q)] from math import gcd from math import sqrt L=[] Q2=[] for x,y in Q: GCD=gcd(x,y) x//=GCD y//=GCD Q2.append((x,y)) L.append(x) L.append(y) FACTOR=set() for l in L: for f in FACTOR: while l%f==0: l//=f if l==1: continue else: L=int(sqrt(l)) for i in range(2,L+2): while l%i==0: FACTOR.add(i) l//=i if l!=1: FACTOR.add(l) FACT=[1] for i in range(1,2*10**2+1): FACT.append(FACT[-1]*i%mod) FACT_INV=[pow(FACT[-1],mod-2,mod)] for i in range(2*10**2,0,-1): FACT_INV.append(FACT_INV[-1]*i%mod) FACT_INV.reverse() def Combi(a,b): if 0<=b<=a: return FACT[a]*FACT_INV[b]*FACT_INV[a-b]%mod else: return 0 def FACTORIZE(x): F=[] for f in FACTOR: #print(f,x) a=0 while x%f==0: a+=1 x//=f if a!=0: F.append(a) return F for x,y in Q2: ANS=1 F=FACTORIZE(x) S=sum(F) for f in F: ANS=ANS*Combi(S,f)%mod S-=f F=FACTORIZE(y) S=sum(F) for f in F: ANS=ANS*Combi(S,f)%mod S-=f sys.stdout.write(str(ANS%mod)+"\n") ```
output
1
18,669
13
37,339
Provide tags and a correct Python 3 solution for this coding contest problem. You are given a positive integer D. Let's build the following graph from it: * each vertex is a divisor of D (not necessarily prime, 1 and D itself are also included); * two vertices x and y (x > y) have an undirected edge between them if x is divisible by y and \frac x y is a prime; * the weight of an edge is the number of divisors of x that are not divisors of y. For example, here is the graph for D=12: <image> Edge (4,12) has weight 3 because 12 has divisors [1,2,3,4,6,12] and 4 has divisors [1,2,4]. Thus, there are 3 divisors of 12 that are not divisors of 4 — [3,6,12]. There is no edge between 3 and 2 because 3 is not divisible by 2. There is no edge between 12 and 3 because 12/3=4 is not a prime. Let the length of the path between some vertices v and u in the graph be the total weight of edges on it. For example, path [(1, 2), (2, 6), (6, 12), (12, 4), (4, 2), (2, 6)] has length 1+2+2+3+1+2=11. The empty path has length 0. So the shortest path between two vertices v and u is the path that has the minimal possible length. Two paths a and b are different if there is either a different number of edges in them or there is a position i such that a_i and b_i are different edges. You are given q queries of the following form: * v u — calculate the number of the shortest paths between vertices v and u. The answer for each query might be large so print it modulo 998244353. Input The first line contains a single integer D (1 ≤ D ≤ 10^{15}) — the number the graph is built from. The second line contains a single integer q (1 ≤ q ≤ 3 ⋅ 10^5) — the number of queries. Each of the next q lines contains two integers v and u (1 ≤ v, u ≤ D). It is guaranteed that D is divisible by both v and u (both v and u are divisors of D). Output Print q integers — for each query output the number of the shortest paths between the two given vertices modulo 998244353. Examples Input 12 3 4 4 12 1 3 4 Output 1 3 1 Input 1 1 1 1 Output 1 Input 288807105787200 4 46 482955026400 12556830686400 897 414 12556830686400 4443186242880 325 Output 547558588 277147129 457421435 702277623 Note In the first example: * The first query is only the empty path — length 0; * The second query are paths [(12, 4), (4, 2), (2, 1)] (length 3+1+1=5), [(12, 6), (6, 2), (2, 1)] (length 2+2+1=5) and [(12, 6), (6, 3), (3, 1)] (length 2+2+1=5). * The third query is only the path [(3, 1), (1, 2), (2, 4)] (length 1+1+1=3).
instruction
0
18,670
13
37,340
Tags: combinatorics, graphs, greedy, math, number theory Correct Solution: ``` mod = 998244353 eps = 10**-9 def main(): import sys input = sys.stdin.buffer.readline # comb init # mod = 1000000007 nmax = 100 # change here fac = [0] * nmax finv = [0] * nmax inv = [0] * nmax fac[0] = 1 fac[1] = 1 finv[0] = 1 finv[1] = 1 inv[1] = 1 for i in range(2, nmax): fac[i] = fac[i - 1] * i % mod inv[i] = mod - inv[mod % i] * (mod // i) % mod finv[i] = finv[i - 1] * inv[i] % mod def comb(n, r): if n < r: return 0 else: return (fac[n] * ((finv[r] * finv[n - r]) % mod)) % mod def PrimeDecomposition(N): ret = {} n = int(N ** 0.5) for d in range(2, n + 1): while N % d == 0: if d not in ret: ret[d] = 1 else: ret[d] += 1 N //= d if N == 1: break if N != 1: ret[N] = 1 return ret D = int(input()) PD = PrimeDecomposition(D) P = list(PD.keys()) np = len(P) ans_all = [] for _ in range(int(input())): u, v = map(int, input().split()) pos = [] neg = [] for p in P: up = 0 while u % p == 0: up += 1 u //= p vp = 0 while v % p == 0: vp += 1 v //= p if up > vp: pos.append(up - vp) elif up < vp: neg.append(vp - up) ans = 1 if pos: ans = (ans * fac[sum(pos)])%mod for x in pos: ans = (ans * finv[x])%mod if neg: ans = (ans * fac[sum(neg)]) % mod for x in neg: ans = (ans * finv[x]) % mod ans_all.append(ans) print(*ans_all, sep="\n") if __name__ == '__main__': main() ```
output
1
18,670
13
37,341