message
stringlengths
2
49.9k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
446
108k
cluster
float64
13
13
__index_level_0__
int64
892
217k
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,109
13
134,218
"Correct Solution: ``` from itertools import permutations n,m = map(int,input().split()) edge = [[0]*n for i in range(n)] for i in range(m): a,b = map(int,input().split()) a-=1; b-=1 edge[a][b] = edge[b][a] = 1 ret = 0 for i in permutations(range(n)): if i[0] != 0 : break for j in range(n-1): if edge[i[j]][i[j+1]] == 0: break else: ret += 1 print(ret) ```
output
1
67,109
13
134,219
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,110
13
134,220
"Correct Solution: ``` import itertools N, M, *AB = [int(_) for _ in open(0).read().split()] G = [set() for _ in range(N)] for a, b in zip(AB[::2], AB[1::2]): a -= 1 b -= 1 G[a].add(b) G[b].add(a) ans = 0 for root in itertools.permutations(range(1, N), N - 1): root = [0] + list(root) if all(a in G[b] for a, b in zip(root, root[1:])): ans += 1 print(ans) ```
output
1
67,110
13
134,221
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,111
13
134,222
"Correct Solution: ``` import itertools N,M=map(int,input().split()) edges=[] for i in range(M): edges.append(list(map(int,input().split()))) res=0 for i in itertools.permutations(range(2,N+1),N-1): path=[1]+list(i) check=[sorted(path[i:i+2]) in edges for i in range(len(path)-1)] if not False in check: res+=1 print(res) ```
output
1
67,111
13
134,223
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,112
13
134,224
"Correct Solution: ``` import itertools N, M = map(int, input().split()) E = [[] for i in range(N)] for i in range(M): a, b = map(int, input().split()) a -= 1 b -= 1 E[a].append(b) E[b].append(a) count = 0 for V in itertools.permutations(range(1, N)): if V[0] in E[0] and all(V[i] in E[V[i-1]] for i in range(1, N-1)): count += 1 print(count) ```
output
1
67,112
13
134,225
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,113
13
134,226
"Correct Solution: ``` N,M = map(int,input().split(" ")) G = [[] for x in range(N)] E = [0]*N for i in range(M): a,b = map(int,input().split(" ")) a -= 1 b -= 1 G[a].append(b) G[b].append(a) def search(x): a = 0 E[x] = 1 if 0 not in E: a += 1 for g in G[x]: if E[g] == 0: a += search(g) E[x] = 0 return a print(search(0)) ```
output
1
67,113
13
134,227
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,114
13
134,228
"Correct Solution: ``` n,m=map(int,input().split()) g=[[] for _ in range(n)] for _ in range(m): a,b=map(int,input().split()) a,b=a-1,b-1 g[a].append(b) g[b].append(a) ed=[0]*n ed[0]=1 ans=[0]*n def f(x): if 0 not in ed: ans[x]+=1 return for a in g[x]: if ed[a]==0: ed[a]=1 f(a) ed[a]=0 f(0) print(sum(ans)) ```
output
1
67,114
13
134,229
Provide a correct Python 3 solution for this coding contest problem. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1
instruction
0
67,115
13
134,230
"Correct Solution: ``` import itertools N,M=map(int,input().split()) route=[list(map(int,input().split())) for _ in range(M)] candidate=list(itertools.permutations(range(1,N+1))) ans=0 for c in candidate: if c[0]==1: for i in range(N-1): l=sorted([c[i], c[i+1]]) if l not in route: break else: ans+=1 print(ans) ```
output
1
67,115
13
134,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` import itertools n,m = map(int,input().split()) a = [] c = 0 for _ in [0]*m: a += [list(map(int,input().split()))] for x in list(itertools.permutations(range(2,n+1))): y = [1] + list(x) f = True for i in range(1,n): if (not [y[i-1],y[i]] in a) and (not [y[i],y[i-1]] in a): f = False break if f: c += 1 print(c) ```
instruction
0
67,116
13
134,232
Yes
output
1
67,116
13
134,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` N, M = map(int,input().split()) to = [[] for i in range(N)] for i in range(M): a,b = map(int,input().split()) a -= 1 b -= 1 to[a].append(b) to[b].append(a) cnt = 0 def search(i,visited): global cnt if len(visited) == N: cnt += 1 for v in to[i]: if v not in visited: search(v,visited+[v]) search(0,[0]) print(cnt) ```
instruction
0
67,117
13
134,234
Yes
output
1
67,117
13
134,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` from itertools import permutations as per ty,he=map(int,input().split()) l=[set(map(int,input().split())) for i in range(he)] ans=0 for g in per(range(2,ty+1)): co=[1]+list(g) for sd in zip(co,co[1:]): if set(sd) not in l:break else:ans+=1 print(ans) ```
instruction
0
67,118
13
134,236
Yes
output
1
67,118
13
134,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` from itertools import permutations n, m = map(int, input().split()) v = [set(map(int, input().split())) for _ in range(m)] ans = 0 x = [i for i in range(2, n+1)] cand = permutations(x) for i in cand: crnt = 1 for nxt in i: if set([crnt, nxt]) in v: crnt = nxt else: break else: ans += 1 print(ans) ```
instruction
0
67,119
13
134,238
Yes
output
1
67,119
13
134,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` from itertools import permutations n,m = map(int,input().split()) e = [tuple(map(int,input().split())) for _ in range(m)] ans = 1 for i in permutations(range(2, n+1), n-1): l = [1] + list(i) ans += sum(1 for j in zip(l, l[1:]) if tuple(j) in e) == n-1 print(ans) ```
instruction
0
67,120
13
134,240
No
output
1
67,120
13
134,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` from itertools import permutations n,m=map(int,input().split()) es=set() for _ in range(m): u,v=map(int,input().split()) u,v=u-1,v-1 es|={(u,v),(v,u)} ```
instruction
0
67,121
13
134,242
No
output
1
67,121
13
134,243
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` import sys sys.setrecursionlimit(10 ** 6) n,m=map(int,input().split()) g=[[]for i in range(n)]; ans=0 for i in range(m): a,b=map(int,input().split()) a-=1; b-=1 g[a].append(b) g[b].append(a) # print(g) def dfs(x,visited): global ans # print(x,visited) for p in g[x]: if visited[p]==0: visited[p]=1 if visited.count(1)==n: ans+=1 # print(ans) return dfs(p,visited) visited[p]=0 v=[0]*n v[0]=1 dfs(0,v) print(ans) ```
instruction
0
67,122
13
134,244
No
output
1
67,122
13
134,245
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. You are given an undirected unweighted graph with N vertices and M edges that contains neither self-loops nor double edges. Here, a self-loop is an edge where a_i = b_i (1≤i≤M), and double edges are two edges where (a_i,b_i)=(a_j,b_j) or (a_i,b_i)=(b_j,a_j) (1≤i<j≤M). How many different paths start from vertex 1 and visit all the vertices exactly once? Here, the endpoints of a path are considered visited. For example, let us assume that the following undirected graph shown in Figure 1 is given. <image> Figure 1: an example of an undirected graph The following path shown in Figure 2 satisfies the condition. <image> Figure 2: an example of a path that satisfies the condition However, the following path shown in Figure 3 does not satisfy the condition, because it does not visit all the vertices. <image> Figure 3: an example of a path that does not satisfy the condition Neither the following path shown in Figure 4, because it does not start from vertex 1. <image> Figure 4: another example of a path that does not satisfy the condition Constraints * 2≦N≦8 * 0≦M≦N(N-1)/2 * 1≦a_i<b_i≦N * The given graph contains neither self-loops nor double edges. Input The 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 Print the number of the different paths that start from vertex 1 and visit all the vertices exactly once. Examples Input 3 3 1 2 1 3 2 3 Output 2 Input 7 7 1 3 2 7 3 4 4 5 4 6 5 6 6 7 Output 1 Submitted Solution: ``` n,m = map(int,input().split()) H = [[0 for _ in range(n)] for _ in range(n) ] edge_list = [] for _ in range(m): a, b = map(int,input().split()) edge_list.append([a,b]) H[a-1][b-1] = 1 H[b-1][a-1] = 1 l = [0 for _ in range(n)] ans = 0 l[0] = 1 def dfs(node,x): visited = x global ans visited[node] = 1 if visited.count(0) == 0: ans += 1 return 0 else: for node_,edge_ in enumerate(H[node]): if edge_ == 1 and visited[node_] != 1: visited[node_] = 1 visited[node] = 1 dfs(node_,visited) dfs(0,l) print(ans) ```
instruction
0
67,123
13
134,246
No
output
1
67,123
13
134,247
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Given a tree with n (1 ≤ n ≤ 200,000) nodes and a list of q (1 ≤ q ≤ 100,000) queries, process the queries in order and output a value for each output query. The given tree is connected and each node on the tree has a weight wi (-10,000 ≤ wi ≤ 10,000). Each query consists of a number ti (ti = 1, 2), which indicates the type of the query , and three numbers ai, bi and ci (1 ≤ ai, bi ≤ n, -10,000 ≤ ci ≤ 10,000). Depending on the query type, process one of the followings: * (ti = 1: modification query) Change the weights of all nodes on the shortest path between ai and bi (both inclusive) to ci. * (ti = 2: output query) First, create a list of weights on the shortest path between ai and bi (both inclusive) in order. After that, output the maximum sum of a non-empty continuous subsequence of the weights on the list. ci is ignored for output queries. Input The first line contains two integers n and q. On the second line, there are n integers which indicate w1, w2, ... , wn. Each of the following n - 1 lines consists of two integers si and ei (1 ≤ si, ei ≤ n), which means that there is an edge between si and ei. Finally the following q lines give the list of queries, each of which contains four integers in the format described above. Queries must be processed one by one from top to bottom. Output For each output query, output the maximum sum in one line. Examples Input 3 4 1 2 3 1 2 2 3 2 1 3 0 1 2 2 -4 2 1 3 0 2 2 2 0 Output 6 3 -4 Input 7 5 -8 5 5 5 5 5 5 1 2 2 3 1 4 4 5 1 6 6 7 2 3 7 0 2 5 2 0 2 4 3 0 1 1 1 -1 2 3 7 0 Output 12 10 10 19 Input 21 30 10 0 -10 -8 5 -5 -4 -3 1 -2 8 -1 -7 2 7 6 -9 -6 3 4 9 10 3 3 2 3 12 12 4 4 13 4 9 10 21 21 1 1 11 11 14 1 15 10 6 6 17 6 16 6 5 5 18 5 19 10 7 10 8 8 20 1 1 21 -10 1 3 19 10 2 1 13 0 1 4 18 8 1 5 17 -5 2 16 7 0 1 6 16 5 1 7 15 4 2 4 20 0 1 8 14 3 1 9 13 -1 2 9 18 0 1 10 12 2 1 11 11 -8 2 21 15 0 1 12 10 1 1 13 9 7 2 6 14 0 1 14 8 -2 1 15 7 -7 2 10 2 0 1 16 6 -6 1 17 5 9 2 12 17 0 1 18 4 6 1 19 3 -3 2 11 8 0 1 20 2 -4 1 21 1 -9 2 5 19 0 Output 20 9 29 27 10 12 1 18 -2 -3 Submitted Solution: ``` #include <bits/stdc++.h> using namespace std; const int IINF = INT_MAX; const char EMPTY = 'X'; struct Node { long long value, left, right, maxi; char lazy; long long lazy_coef; Node(long long value = 0, long long left = -INT_MAX, long long right = -INT_MAX, long long maxi = -INT_MAX, char lazy = EMPTY, long long lazy_coef = 0) : value(value), left(left), right(right), maxi(maxi), lazy(lazy), lazy_coef(lazy_coef) {} }; class SegmentTree { public: vector<Node> RMQ; int limit, N; void init(int tmp) { N = tmp; int N_N = 1; while (N_N < N) N_N *= 2; limit = N_N; RMQ.resize(3 * limit); for (int i = 0; i < 3 * limit - 1; i++) RMQ[i] = Node(); } Node _build(int cur, int L, int R, const vector<int> &buf) { if (!(0 <= cur && cur < 2 * limit - 1)) return Node(); if (L == R - 1) { if (L >= N) return Node(); RMQ[cur].value = buf[L]; RMQ[cur].left = buf[L]; RMQ[cur].right = buf[L]; RMQ[cur].maxi = buf[L]; } else { Node vl = _build(cur * 2 + 1, L, (L + R) / 2, buf); Node vr = _build(cur * 2 + 2, (L + R) / 2, R, buf); RMQ[cur].value = vl.value + vr.value; RMQ[cur].left = max(vl.left, vl.value + vr.left); RMQ[cur].right = max(vr.right, vr.value + vl.right); RMQ[cur].maxi = max(vl.maxi, max(vr.maxi, vl.right + vr.left)); } return RMQ[cur]; } void build(const vector<int> &buf) { _build(0, 0, limit, buf); } inline void value_evaluate(int index, int L, int R) { if (RMQ[index].lazy == 'S') { RMQ[index].value = (R - L) * RMQ[index].lazy_coef; RMQ[index].left = max(RMQ[index].lazy_coef, (R - L) * RMQ[index].lazy_coef); RMQ[index].right = max(RMQ[index].lazy_coef, (R - L) * RMQ[index].lazy_coef); RMQ[index].maxi = max(RMQ[index].lazy_coef, (R - L) * RMQ[index].lazy_coef); } } inline void lazy_evaluate(int index, int L, int R) { value_evaluate(index, L, R); if (index < limit && RMQ[index].lazy != EMPTY) { if (RMQ[index].lazy == 'S') { RMQ[index * 2 + 1].lazy = RMQ[index * 2 + 2].lazy = 'S'; RMQ[index * 2 + 1].lazy_coef = RMQ[index].lazy_coef; RMQ[index * 2 + 2].lazy_coef = RMQ[index].lazy_coef; } } RMQ[index].lazy = EMPTY; RMQ[index].lazy_coef = 0; } inline void value_update(int index) { RMQ[index].value = RMQ[index * 2 + 1].value + RMQ[index * 2 + 2].value; RMQ[index].left = max(RMQ[index * 2 + 1].left, RMQ[index * 2 + 1].value + RMQ[index * 2 + 2].left); RMQ[index].right = max(RMQ[index * 2 + 2].right, RMQ[index * 2 + 2].value + RMQ[index * 2 + 1].right); RMQ[index].maxi = max(RMQ[index * 2 + 1].maxi, max(RMQ[index * 2 + 2].maxi, RMQ[index * 2 + 1].right + RMQ[index * 2 + 2].left)); } void _update(int a, int b, char opr, long long v, int index, int L, int R) { lazy_evaluate(index, L, R); if (b <= L || R <= a) return; if (a <= L && R <= b) { RMQ[index].lazy = opr; if (opr == 'S') RMQ[index].lazy_coef = v; lazy_evaluate(index, L, R); return; } _update(a, b, opr, v, index * 2 + 1, L, (L + R) / 2); _update(a, b, opr, v, index * 2 + 2, (L + R) / 2, R); value_update(index); } void update(int a, int b, char opr, long long v) { _update(a, b, opr, v, 0, 0, limit); } Node _query(int a, int b, int index, int L, int R) { lazy_evaluate(index, L, R); if (b <= L || R <= a) return Node(); if (a <= L && R <= b) return RMQ[index]; Node tmp1 = _query(a, b, index * 2 + 1, L, (L + R) / 2); Node tmp2 = _query(a, b, index * 2 + 2, (L + R) / 2, R); Node ret = Node(); ret.value = tmp1.value + tmp2.value; ret.left = max(tmp1.left, tmp1.value + tmp2.left); ret.right = max(tmp2.right, tmp2.value + tmp1.right); ret.maxi = max(tmp1.maxi, max(tmp2.maxi, tmp1.right + tmp2.left)); value_update(index); return ret; } Node query(int a, int b) { return _query(a, b, 0, 0, limit); } }; const int MAX_V = 201000; struct Edge { int to, weight; }; int V; vector<Edge> G[MAX_V]; vector<int> costs; class LCA_RMQ { private: int limit, N; vector<pair<int, int> > dat; public: void init(int n_) { N = n_; dat.clear(); limit = 1; while (limit < n_) limit *= 2; dat.resize(2 * limit); for (int i = 0; i < 2 * limit - 1; i++) dat[i] = pair<int, int>(IINF, IINF); } pair<int, int> _build(int cur, int L, int R, const vector<pair<int, int> > &buf) { if (!(0 <= cur && cur < 2 * limit)) return pair<int, int>(IINF, IINF); if (L == R - 1) { if (L >= N) return pair<int, int>(IINF, IINF); dat[cur] = buf[L]; } else { pair<int, int> vl = _build(cur * 2 + 1, L, (L + R) / 2, buf); pair<int, int> vr = _build(cur * 2 + 2, (L + R) / 2, R, buf); dat[cur] = min(vl, vr); } return dat[cur]; } void build(const vector<pair<int, int> > &buf) { _build(0, 0, limit, buf); }; void update(int k, pair<int, int> a) { k += limit - 1; dat[k] = a; while (k > 0) { k = (k - 1) / 2; dat[k] = (dat[k * 2 + 1].first > dat[k * 2 + 2].first ? dat[k * 2 + 2] : dat[k * 2 + 1]); } } pair<int, int> _query(int a, int b, int k, int l, int r) { if (r <= a || b <= l) return pair<int, int>(IINF, -1); else if (a <= l && r <= b) return dat[k]; pair<int, int> vl = _query(a, b, k * 2 + 1, l, (l + r) / 2); pair<int, int> vr = _query(a, b, k * 2 + 2, (l + r) / 2, r); return min(vl, vr); } pair<int, int> query(int a, int b) { return _query(a, b, 0, 0, limit); } }; int root; vector<int> id, vs, depth; void LCA_dfs(int v, int p, int d, int &k) { id[v] = k; vs[k] = v; depth[k++] = d; for (int i = 0; i < (int)G[v].size(); i++) { if (G[v][i].to != p) { LCA_dfs(G[v][i].to, v, d + 1, k); vs[k] = v; depth[k++] = d; } } } void LCA_init(int V, LCA_RMQ &rmq) { root = 0; vs.clear(); vs.resize(V * 2, 0); depth.clear(); depth.resize(V * 2, 0); id.clear(); id.resize(V); int k = 0; LCA_dfs(root, -1, 0, k); rmq.init(k + 1); vector<pair<int, int> > tmp; for (int i = 0; i < k; i++) tmp.push_back(pair<int, int>(depth[i], vs[i])); rmq.build(tmp); } int lca(int u, int v, LCA_RMQ &rmq) { return rmq.query(min(id[u], id[v]), max(id[u], id[v]) + 1).second; } int chainNumber; vector<int> subsize, chainID, headID, baseArray, posInBase, parent; void HLD_dfs(int cur, int prev) { parent[cur] = prev; for (int i = 0; i < (int)G[cur].size(); i++) { int to = G[cur][i].to; if (to == prev) continue; HLD_dfs(to, cur); subsize[cur] += subsize[to]; } } void HLD(int cur, int prev, int &ptr) { if (headID[chainNumber] == -1) headID[chainNumber] = cur; chainID[cur] = chainNumber; baseArray[ptr] = costs[cur]; posInBase[cur] = ptr++; int maxi = -1; for (int i = 0; i < (int)G[cur].size(); i++) { int to = G[cur][i].to; if (to == prev) continue; if (maxi == -1 || subsize[to] > subsize[maxi]) maxi = to; } if (maxi != -1) HLD(maxi, cur, ptr); for (int i = 0; i < (int)G[cur].size(); i++) { int to = G[cur][i].to; if (to == prev || to == maxi) continue; ++chainNumber; HLD(to, cur, ptr); } } void HLD_init() { chainNumber = 0; subsize.clear(); chainID.clear(); headID.clear(); baseArray.clear(); posInBase.clear(); parent.clear(); subsize.resize(V, 1); chainID.resize(V, -1); headID.resize(V, -1); baseArray.resize(V, -IINF); posInBase.resize(V, -1); parent.resize(V, -1); HLD_dfs(0, -1); int ptr = 0; HLD(0, -1, ptr); } long long LLINF = LLONG_MAX; bool DEBUG = false; void print(Node a) { puts("---"); cout << "sum = " << a.value << endl; cout << "left = " << a.left << endl; cout << "right = " << a.right << endl; cout << "maxi = " << a.maxi << endl; } long long special; Node _Query(int s, int t, SegmentTree &seg, int f) { if (!f && s == t) { int ps = posInBase[s], pt = posInBase[t]; if (ps > pt) swap(ps, pt); Node node = seg.query(ps, pt + 1); if (t == pt) special = node.right; else special = node.left; return node; } if (f && s == t) { special = 0; return Node(); } int chain_s, chain_t = chainID[t]; Node ret = Node(); while (1) { chain_s = chainID[s]; if (chain_s == chain_t) { int ps = posInBase[s], pt = posInBase[t]; int t_pos = pt; if (f && s == t) { return ret; } if (ps > pt) swap(ps, pt); if (f && t_pos == pt) --pt; if (f && t_pos == ps) ++ps; if (ps > pt) swap(ps, pt); Node temp = seg.query(ps, pt + 1); ret.maxi = max(ret.maxi, max(temp.maxi, ret.right + temp.left)); ret.left = max(ret.left, ret.value + temp.left); ret.right = max(temp.right, temp.value + ret.right); ret.value += temp.value; if (t_pos == pt) { special = ret.left; } else { special = ret.right; } return ret; } else { int head = headID[chain_s]; int ps = posInBase[s], ph = posInBase[head]; Node temp = seg.query(min(ps, ph), max(ps, ph) + 1); ret.maxi = max(ret.maxi, max(temp.maxi, ret.right + temp.left)); ret.left = max(ret.left, ret.value + temp.left); ret.right = max(temp.right, temp.value + ret.right); ret.value += temp.value; if (f && parent[head] == t) { if (ps < ph) special = ret.right; else special = ret.left; } s = parent[head]; } } return ret; } long long Query(int s, int t, SegmentTree &seg, LCA_RMQ &lca_rmq) { if (s == t) { int ps = posInBase[s], pt = posInBase[t]; if (ps > pt) swap(ps, pt); return seg.query(ps, pt + 1).maxi; } int ancestor = lca(s, t, lca_rmq); long long temp_maxi = 0; DEBUG = true; Node a = _Query(s, ancestor, seg, 0); DEBUG = false; temp_maxi += special; Node b = _Query(t, ancestor, seg, 1); temp_maxi += special; return max(a.maxi, max(b.maxi, temp_maxi)); } void _Update(int s, int t, SegmentTree &seg, int c) { if (s == t) return seg.update(posInBase[s], posInBase[s] + 1, 'S', c); int chain_s, chain_t = chainID[t]; while (1) { chain_s = chainID[s]; if (chain_s == chain_t) { int ps = posInBase[s], pt = posInBase[t]; if (ps > pt) swap(ps, pt); seg.update(ps, pt + 1, 'S', c); return; } else { int head = headID[chain_s]; int ps = posInBase[s], ph = posInBase[head]; seg.update(min(ps, ph), max(ps, ph) + 1, 'S', c); s = parent[head]; } } } void Update(int s, int t, int c, SegmentTree &seg, LCA_RMQ &lca_rmq) { if (s == t) { int ps = posInBase[s], pt = posInBase[t]; if (ps > pt) swap(ps, pt); seg.update(ps, pt + 1, 'S', c); return; } int ancestor = lca(s, t, lca_rmq); _Update(s, ancestor, seg, c); _Update(t, ancestor, seg, c); } int main() { int Q; scanf("%d %d", &V, &Q); costs.clear(); costs.resize(V); for (int i = 0; i < V; i++) scanf("%d", &costs[i]); for (int i = 0; i < V - 1; i++) { int s, t; scanf("%d %d", &s, &t); --s, --t; G[s].push_back((Edge){t, 0}); G[t].push_back((Edge){s, 0}); } HLD_init(); SegmentTree seg; seg.init(V); seg.build(baseArray); LCA_RMQ lca_rmq; LCA_init(V, lca_rmq); cout << "baseArray = " << endl; for (int i = 0; i < baseArray.size(); i++) cout << baseArray[i] << " "; cout << endl; cout << "chainID = " << endl; for (int i = 0; i < (int)chainID.size(); i++) cout << chainID[i] << " "; cout << endl; cout << "headID = " << endl; for (int i = 0; i < (int)headID.size(); i++) cout << headID[i] << " "; cout << endl; cout << "parent = " << endl; for (int i = 0; i < (int)parent.size(); i++) cout << parent[i] << " "; cout << endl; cout << "posInBase = " << endl; for (int i = 0; i < posInBase.size(); i++) cout << "[" << i << "," << posInBase[i] << "] "; cout << endl; while (1) { int L, R; cin >> L >> R; print(seg.query(L, R + 1)); } return 0; for (int i = 0; i < Q; i++) { int t, a, b, c; scanf("%d %d %d %d", &t, &a, &b, &c); --a, --b; if (t == 1) { Update(a, b, c, seg, lca_rmq); } else if (t == 2) { printf("%lld\n", Query(a, b, seg, lca_rmq)); } else assert(false); } return 0; } ```
instruction
0
67,214
13
134,428
No
output
1
67,214
13
134,429
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,219
13
134,438
"Correct Solution: ``` import random from collections import deque class TreapNode(): """節クラス: valは節の値, priorityは節の優先度を表す parent/left/rightはそれぞれ親/左側の子/右側の子へのポインタを表す """ def __init__(self, val, priority): self.val = val self.priority = priority # random.random() self.parent = None self.right = None self.left = None class Treap(): """SSet(Sorted Set)をサポートする""" def __init__(self): self.root = None def search(self, val: int) -> bool: """二分木に値valを持つ節が存在するかどうか判定する valと一致する節が存在する場合はTrue、存在しない場合はFalseを返す """ ptr = self.root while ptr is not None: if ptr.val == val: return True if val < ptr.val: ptr = ptr.left else: ptr = ptr.right return False def insert(self, val: int, priority): """二分木に値valを持つ節が存在しない場合、追加する""" if self.root is None: self.root = TreapNode(val, priority) return ptr = self.root while True: if val == ptr.val: return elif val < ptr.val: if ptr.left is None: # ポインタの示す先に節が存在しない場合はNode(val)を追加する ptr.left = TreapNode(val, priority) ptr.left.parent = ptr ptr = ptr.left break ptr = ptr.left else: if ptr.right is None: # ポインタの示す先に節が存在しない場合はNode(val)を追加する ptr.right = TreapNode(val, priority) ptr.right.parent = ptr ptr = ptr.right break ptr = ptr.right while (ptr.parent is not None) and (ptr.parent.priority < ptr.priority): if ptr.parent.right == ptr: self.rotate_left(ptr.parent) else: self.rotate_right(ptr.parent) if ptr.parent is None: self.root = ptr def delete(self, val: int): """二分木から値valを持つ節を削除する""" ptr = self.root while True: if ptr is None: return elif val == ptr.val: break elif val < ptr.val: ptr = ptr.left else: ptr = ptr.right while (ptr.left is not None) or (ptr.right is not None): if ptr.left is None: self.rotate_left(ptr) elif ptr.right is None: self.rotate_right(ptr) elif ptr.left.priority > ptr.right.priority: self.rotate_right(ptr) else: self.rotate_left(ptr) if self.root == ptr: self.root = ptr.parent if ptr.parent.left == ptr: ptr.parent.left = None else: ptr.parent.right = None def rotate_left(self, ptr): """木を左回転する""" w = ptr.right w.parent = ptr.parent if w.parent is not None: if w.parent.left == ptr: w.parent.left = w else: w.parent.right = w ptr.right = w.left if ptr.right is not None: ptr.right.parent = ptr ptr.parent = w w.left = ptr if ptr == self.root: self.root = w self.root.parent = None def rotate_right(self, ptr): """木を右回転する""" w = ptr.left w.parent = ptr.parent if w.parent is not None: if w.parent.right == ptr: w.parent.right = w else: w.parent.left = w ptr.left = w.right if ptr.left is not None: ptr.left.parent = ptr ptr.parent = w w.right = ptr if ptr == self.root: self.root = w self.root.parent = None def preorder_tree_walk(self): """先行順巡回(preorder tree walk)""" res = [] q = deque([]) ptr = self.root while True: if ptr is not None: q.append(ptr) res.append(ptr.val) ptr = ptr.left elif q: ptr = q.pop() ptr = ptr.right else: return res def inorder_tree_walk(self): """中間順巡回(inorder tree walk)""" res = [] q = deque([]) ptr = self.root while True: if ptr is not None: q.append(ptr) ptr = ptr.left elif q: ptr = q.pop() res.append(ptr.val) ptr = ptr.right else: return res def postorder_tree_walk(self): """後行順巡回(postorder tree walk)""" res = [] q = deque([self.root]) ptr = self.root while q: ptr = q.pop() res.append(ptr.val) if ptr.left is not None: q.append(ptr.left) if ptr.right is not None: q.append(ptr.right) return reversed(res) n = int(input()) info = [list(input().split()) for i in range(n)] tp = Treap() for i in range(n): if info[i][0] == "insert": tp.insert(int(info[i][1]), int(info[i][2])) elif info[i][0] == "find": if tp.search(int(info[i][1])): print("yes") else: print("no") elif info[i][0] == "delete": tp.delete(int(info[i][1])) else: print(" ", end="") print(*tp.inorder_tree_walk()) print(" ", end="") print(*tp.preorder_tree_walk()) ```
output
1
67,219
13
134,439
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,220
13
134,440
"Correct Solution: ``` class Node: def __init__(self, key, pri): self.key = key self.pri = pri self.left = None self.right = None def rRotate(t): s = t.left t.left = s.right s.right = t return s def lRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == None: return Node(key, pri) if key == t.key: return t if key < t.key: t.left = insert(t.left , key, pri) if t.pri < t.left.pri : t = rRotate(t) else: t.right = insert(t.right, key, pri) if t.pri < t.right.pri: t = lRotate(t) return t def delete(t, key): if t == None: return None if key < t.key: t.left = delete(t.left , key) elif key > t.key: t.right = delete(t.right, key) else: return _delete(t, key) return t def _delete(t, key): if t.left == None and t.right == None: return None elif t.left == None: t = lRotate(t) elif t.right == None: t = rRotate(t) else: if t.left.pri > t.right.pri: t = rRotate(t) else: t = lRotate(t) return delete(t, key) def find(t, key): if(t == None): return False if(t.key == key): return True if(t.key > key): return find(t.left , key) else : return find(t.right, key) def preorder(t): if(t == None): return print('', t.key, end='') preorder(t.left ) preorder(t.right) def inorder(t): if(t == None): return inorder(t.left ) print('', t.key, end='') inorder(t.right) if __name__ == '__main__': n = int(input()) top = None for _ in range(n): strs = input().split() op = strs[0] if op != 'print': key = int(strs[1]) if op == 'insert': pri = int(strs[2]) if op == 'insert': top = insert(top, key, pri) if op == 'delete': top = delete(top, key) if op == 'find' : if find(top, key): print('yes') else : print('no' ) if op == 'print' : inorder(top) print() preorder(top) print() ```
output
1
67,220
13
134,441
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,221
13
134,442
"Correct Solution: ``` class Node: def __init__(self, key, priority): self.right = None self.left = None self.parent = None self.key = key self.priority = priority def preorder(self): ret = [self.key] if self.left: ret += self.left.preorder() if self.right: ret += self.right.preorder() return ret def inorder(self): ret = [] if self.left: ret += self.left.inorder() ret += [self.key] if self.right: ret += self.right.inorder() return ret def find(self, k): if self.key == k: return self elif self.key < k: if self.right: return self.right.find(k) else: return None else: if self.left: return self.left.find(k) else: return None class Treap: def __init__(self): self.root = None def right_rotate(self, t): s = t.left t.left = s.right s.right = t return s def left_rotate(self, t): s = t.right t.right = s.left s.left = t return s def insert(self, k, p): self.root = self._insert(self.root, k, p) def _insert(self, t, k, p): if t is None: return Node(k, p) if k == t.key: return t if k < t.key: t.left = self._insert(t.left, k, p) if t.priority < t.left.priority: t = self.right_rotate(t) else: t.right = self._insert(t.right, k, p) if t.priority < t.right.priority: t = self.left_rotate(t) return t def print(self): if self.root is None: print() else: print('', ' '.join(map(str, self.root.inorder()))) print('', ' '.join(map(str, self.root.preorder()))) def find(self, k): if self.root is None: return None else: return self.root.find(k) def delete(self, k): self.root = self._delete(self.root, k) def _delete(self, t, k): if t is None: return None if k < t.key: t.left = self._delete(t.left, k) elif k > t.key: t.right = self._delete(t.right, k) else: return self._else_delete(t, k) return t def _else_delete(self, t, k): if t.left is None and t.right is None: return None elif t.left is None: t = self.left_rotate(t) elif t.right is None: t = self.right_rotate(t) else: if t.left.priority > t.right.priority: t = self.right_rotate(t) else: t = self.left_rotate(t) return self._delete(t, k) m = int(input()) treap = Treap() for _ in range(m): s = input().split() if s[0] == "insert": treap.insert(int(s[1]), int(s[2])) elif s[0] == "find": if treap.find(int(s[1])): print("yes") else: print("no") elif s[0] == "delete": treap.delete(int(s[1])) else: treap.print() ```
output
1
67,221
13
134,443
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,222
13
134,444
"Correct Solution: ``` import sys from collections import namedtuple Node = namedtuple('Node', ['key', 'priority', 'left', 'right']) class Treap: MAX_KEY = 2000000000 MAX_PRIORITY = 2000000000 def __init__(self): self.root = None def insert(self, key, priority): def _insert(node): if node is None: return Node(key, priority, None, None) k, p, left, right = node if key < k: node = Node(k, p, _insert(left), right) if p < node.left.priority: node = self._rotate_right(node) elif key > k: node = Node(k, p, left, _insert(right)) if p < node.right.priority: node = self._rotate_left(node) else: # node.key == key pass # assert(self._bst_invariant(node)) # assert(self._heap_invariant(node)) return node self.root = _insert(self.root) def delete(self, key): def _delete(node): if node is None: return None k, p, left, right = node if key < k: node = node._replace(left=_delete(left)) elif key > k: node = node._replace(right=_delete(right)) else: # key == k if left is None: node = right elif right is None: node = left else: if left.priority > right.priority: node = _delete(self._rotate_right(node)) else: node = _delete(self._rotate_left(node)) # assert(self._bst_invariant(node)) # assert(self._heap_invariant(node)) return node self.root = _delete(self.root) def find(self, key): def _find(node): if node is None: return False if key < node.key: return _find(node.left) elif key > node.key: return _find(node.right) else: return True return _find(self.root) def inorder(self): def _inorder(node): if node is not None: yield from _inorder(node.left) yield node yield from _inorder(node.right) return _inorder(self.root) def preorder(self): def _preorder(node): if node is not None: yield node yield from _preorder(node.left) yield from _preorder(node.right) return _preorder(self.root) def postorder(self): def _postorder(node): if node is not None: yield from _postorder(node.left) yield from _postorder(node.right) yield node return _postorder(self.root) def _rotate_left(self, node): # assert node.right is not None top = node.right node = node._replace(right=top.left) top = top._replace(left=node) return top def _rotate_right(self, node): # assert node.left is not None top = node.left node = node._replace(left=top.right) top = top._replace(right=node) return top def _heap_invariant(self, node): if node is None: return True key, priority, left, right = node return ((left is None or priority > left.priority) and (right is None or priority > right.priority)) def _bst_invariant(self, node): if node is None: return True key, priority, left, right = node return ((left is None or key > left.key) and (right is None or key < right.key)) def __str__(self): def _str(node): if node is None: return '' else: k, p, l, r = node return '({}[{}/{}]{})'.format(_str(l), k, p, _str(r)) return _str(self.root) def run(): input() tree = Treap() for line in sys.stdin: if line.startswith('insert'): key, priority = [int(i) for i in line[7:].split()] tree.insert(key, priority) elif line.startswith('find'): if tree.find(int(line[5:])): print("yes") else: print("no") elif line.startswith('delete'): tree.delete(int(line[7:])) elif line.startswith('print'): print('', ' '.join([str(n.key) for n in tree.inorder()])) print('', ' '.join([str(n.key) for n in tree.preorder()])) else: raise ValueError('invalid command') # print(tree) if __name__ == '__main__': run() ```
output
1
67,222
13
134,445
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,223
13
134,446
"Correct Solution: ``` # coding:utf-8 NIL = None class Node(): def __init__(self, key, pri): self.key = key self.pri = pri self.right = NIL self.left = NIL def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == NIL: return Node(key, pri) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, pri) if t.pri < t.left.pri: t = rightRotate(t) else : t.right = insert(t.right, key, pri) if t.pri < t.right.pri: t = leftRotate(t) return t def erase(t, key): if t == NIL: return NIL if key == t.key: if t.right == NIL and t.left == NIL: return NIL elif t.left == NIL: t = leftRotate(t) elif t.right == NIL: t = rightRotate(t) else : if t.left.pri > t.right.pri: t = rightRotate(t) else : t = leftRotate(t) return erase(t, key) if key < t.key: t.left = erase(t.left, key) else: t.right = erase(t.right, key) return t def find(t, key): if t == NIL: return False if key == t.key: return True if key < t.key: return find(t.left, key) else: return find(t.right, key) head = Node(-1, 2000000001) def print_priorder(t): if t == NIL: return if t != head: print(" " + str(t.key), end='') print_priorder(t.left) print_priorder(t.right) def print_inorder(t): if t == NIL: return print_inorder(t.left) if t != head: print(" " + str(t.key), end='') print_inorder(t.right) n = int(input()) # 命令の数 for i in range(n): inst = input().split() if inst[0] == "insert": insert(head, int(inst[1]), int(inst[2])) elif inst[0] == "find": if find(head, int(inst[1])): print("yes") else : print("no") elif inst[0] == "delete": erase(head, int(inst[1])) elif inst[0] == "print": print_inorder(head) print() print_priorder(head) print() ```
output
1
67,223
13
134,447
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,224
13
134,448
"Correct Solution: ``` class Node: def __init__(self, key, priority): self.key = key self.pri = priority self.parent = None self.left = None self.right = None def insert(self, z): if z.key < self.key: if self.left: self.left.insert(z) else: self.left = z z.parent = self if self.pri < self.left.pri: self.rightR() elif self.key < z.key: if self.right: self.right.insert(z) else: self.right = z z.parent = self if self.pri < self.right.pri: self.leftR() def find(self, key): if self.key == key: return True elif not self.left and not self.right: return False else: if key < self.key: return self.left.find(key) else: return self.right.find(key) def delete(self, key): if key < self.key: self.left.delete(key) elif key > self.key: self.right.delete(key) else: self._delete() def _delete(self): if not self.left and not self.right: if self.parent.left == self: self.parent.left = None else: self.parent.right = None del self return None elif self.left and self.right: if self.left.pri > self.right.pri: self.rightR() else: self.leftR() elif self.right: self.leftR() else: self.rightR() self._delete() def rightR(self): tmp = self.left if self.parent: if self.key < self.parent.key: self.parent.left = tmp else: self.parent.right = tmp self.left = tmp.right if self.left: self.left.parent = self tmp.right = self tmp.parent = self.parent self.parent = tmp def leftR(self): tmp = self.right if self.parent: if self.key < self.parent.key: self.parent.left = tmp else: self.parent.right = tmp self.right = tmp.left if self.right: self.right.parent = self tmp.left = self tmp.parent = self.parent self.parent = tmp def preo(self): tmp = "" tmp += " " + str(self.key) if self.left: tmp += self.left.preo() if self.right: tmp += self.right.preo() return tmp def ino(self): tmp = "" if self.left: tmp += self.left.ino() tmp += " " + str(self.key) if self.right: tmp += self.right.ino() return tmp m = int(input()) root = None for i in range(m): com = input().split() if com[0] == "insert": node = Node(int(com[1]), int(com[2])) try: root.insert(node) except AttributeError : root = node elif com[0] == "find": try: if root.find(int(com[1])): print("yes") else: print("no") except AttributeError: print("no") elif com[0] == "delete": try: root.delete(int(com[1])) except AttributeError: pass else: try: print(root.ino()) print(root.preo()) except AttributeError: print("None") c = 0 while(True): if root.parent: root = root.parent else: break ```
output
1
67,224
13
134,449
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,225
13
134,450
"Correct Solution: ``` # Treap class Node(): def __init__(self, k, p): self.k = k self.p = p self.left = None self.right = None def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == None: return Node(key, pri) if key == t.k: return t if key < t.k: t.left = insert(t.left, key, pri) if t.p < t.left.p: t = rightRotate(t) else: t.right = insert(t.right, key, pri) if t.p < t.right.p: t = leftRotate(t) return t def erase(t, key): if t == None: return None if key == t.k: if t.left == None and t.right == None: return None elif t.left == None: t = leftRotate(t) elif t.right == None: t = rightRotate(t) else: if t.left.p > t.right.p: t = rightRotate(t) else: t = leftRotate(t) return erase(t, key) if key < t.k: t.left = erase(t.left, key) else: t.right = erase(t.right, key) return t def inorder(t): if t == None: return inorder(t.left) print(" " + str(t.k), end="") inorder(t.right) def preorder(t): if t == None: return print(" " + str(t.k), end="") preorder(t.left) preorder(t.right) def output(t): inorder(t) print() preorder(t) print() t = None data = [] dict = {} m = int(input()) for i in range(m): data.append(list(input().split())) for i in range(m): if data[i][0] == "insert": if (data[i][1] in dict) == False: t = insert(t, int(data[i][1]), int(data[i][2])) dict[data[i][1]] = True elif data[i][0] == "print": output(t) elif data[i][0] == "find": if (data[i][1] in dict) == True: print("yes") else: print("no") else: t = erase(t, int(data[i][1])) if (data[i][1] in dict) == True: del dict[data[i][1]] ```
output
1
67,225
13
134,451
Provide a correct Python 3 solution for this coding contest problem. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86
instruction
0
67,226
13
134,452
"Correct Solution: ``` class Node: def __init__(self, key, priority): self.key = key self.priority = priority self.parent = None self.left = None self.right = None # 根 parent_node = None # カウンター counter = 0 def getRoot(u): while u.parent != None: u = u.parent return u def printPreorder(u): if u == None: return print(" ", u.key, sep="", end="") printPreorder(u.left) printPreorder(u.right) def printInorder(u): if u == None: return printInorder(u.left) print(" ", u.key, sep="", end="") printInorder(u.right) def find(u, num): while u != None and u.key != num: if num < u.key: u = u.left else: u = u.right if u != None: print("yes") else: print("no") def rightRotate(u): # print("right") s = u.left u.left = s.right # 親の更新 if u.left != None: u.left.parent = u s.right = u # 親の更新 s.parent = u.parent u.parent = s return s def leftRotate(u): # print("left") s = u.right u.right = s.left # 親の更新 if u.right != None: u.right.parent = u s.left = u # 親の更新 s.parent = u.parent u.parent = s return s def insert(u, key, priority): # print("insert 1") global parent_node global counter if u == None: s = Nodes[counter] # カウンターの増加 counter += 1 s.key = key s.priority = priority # 根のノードの更新 if parent_node == None: parent_node = s return s if key == u.key: return u if key < u.key: u.left = insert(u.left, key, priority) # 親の更新 u.left.parent = u if u.priority < u.left.priority: u = rightRotate(u) else: u.right = insert(u.right, key, priority) # 親の更新 u.right.parent = u if u.priority < u.right.priority: u = leftRotate(u) return u def delete(u, key): # print("delete") if u == None: return None if key < u.key: u.left = delete(u.left, key) elif key > u.key: u.right = delete(u.right, key) else: return _delete(u, key) return u def _delete(u, key): # print("_delete") if u.left == None and u.right == None: return None elif u.left == None: u = leftRotate(u) elif u.right == None: u = rightRotate(u) else: if u.left.priority > u.right.priority: u = rightRotate(u) else: u = leftRotate(u) return delete(u, key) n = int(input()) # メモリの確保 Nodes = [] for i in range(n): tmp_node = Node(0, 0) Nodes.append(tmp_node) for i in range(n): cmd = input().split() if cmd[0] == 'insert': key = int(cmd[1]) priority = int(cmd[2]) insert(parent_node, key, priority) # print("test in") # 根が変わる場合を考慮する。 parent_node = getRoot(parent_node) # print("test out") # プリント elif cmd[0] == 'print': printInorder(parent_node) print("") printPreorder(parent_node) print("") # サーチ elif cmd[0] == 'find': key = int(cmd[1]) find(parent_node, key) # 削除 else: key = int(cmd[1]) # 根が変わる場合を考慮する。 if parent_node.key != key: delete(parent_node, key) parent_node = getRoot(parent_node) elif parent_node.left != None: tmp_node = parent_node.left delete(parent_node, key) parent_node = getRoot(tmp_node) elif parent_node.right != None: tmp_node = parent_node.right delete(parent_node, key) parent_node = getRoot(tmp_node) else: delete(parent_node, key) parent_node = None ```
output
1
67,226
13
134,453
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` class Node: def __init__(self, key, priority): self.key = key self.priority = priority self.parent = None self.left = self.right = None def preorder(self): L = [self.key] if self.left: L += self.left.preorder() if self.right: L += self.right.preorder() return L def inorder(self): L = [] if self.left: L += self.left.inorder() L.append(self.key) if self.right: L += self.right.inorder() return L def rightRotate(t): s = t.left t.left = s.right s.right = t return s # root of the subtree def leftRotate(t): s = t.right t.right = s.left s.left = t return s # root of the subtree def insert(t, key, priority): if not t: return Node(key, priority) # 葉に到達したら新しい節点を生成して返す if key == t.key: return t # 重複したkeyは無視 if key < t.key: # 左の子に移動 t.left = insert(t.left, key, priority) # 左の子へのポインタを更新 if t.priority < t.left.priority: # 左の子の方が優先度が高い場合右回転 t = rightRotate(t) else: # 右の子へ移動 t.right = insert(t.right, key, priority) # 右の子へのポインタを更新 if t.priority < t.right.priority: # 右の子の方が優先度が高い場合左回転 t = leftRotate(t) return t def delete(t, key): if not t: return None if key < t.key: # 削除対象を検索 t.left = delete(t.left, key) elif key > t.key: t.right = delete(t.right, key) else: return _delete(t, key) return t def _delete(t, key): if not t.left and not t.right: # 葉の場合 return None if not t.left: # 右の子のみを持つ場合左回転 t = leftRotate(t) elif not t.right: # 左の子のみを持つ場合右回転 t = rightRotate(t) else: # 左の子と右の子を両方持つ場合、優先度が高い方を持ち上げる if t.left.priority > t.right.priority: t = rightRotate(t) else: t = leftRotate(t) return delete(t, key) def find(t, k): x = t while x: if x.key == k: return x x = x.left if k < x.key else x.right return None t = None m = int(input()) for _ in range(m): cmd = list(input().split()) if cmd[0] == 'insert': t = insert(t, int(cmd[1]), int(cmd[2])) if cmd[0] == 'find': print('yes' if find(t, int(cmd[1])) else 'no') if cmd[0] == 'delete': t = delete(t, int(cmd[1])) if cmd[0] == 'print': print('', *t.inorder()) print('', *t.preorder()) ```
instruction
0
67,227
13
134,454
Yes
output
1
67,227
13
134,455
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` # Treap class Node(): def __init__(self, k, p): self.k = k self.p = p self.left = None self.right = None def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == None: return Node(key, pri) if key == t.k: return t if key < t.k: t.left = insert(t.left, key, pri) if t.p < t.left.p: t = rightRotate(t) else: t.right = insert(t.right, key, pri) if t.p < t.right.p: t = leftRotate(t) return t def erase(t, key): if t == None: return None if key == t.k: if t.left == None and t.right == None: return None elif t.left == None: t = leftRotate(t) elif t.right == None: t = rightRotate(t) else: if t.left.p > t.right.p: t = rightRotate(t) else: t = leftRotate(t) return erase(t, key) if key < t.k: t.left = erase(t.left, key) else: t.right = erase(t.right, key) return t def find(t, k): if t == None: return -1 if t.k == k: return 1 if k < t.k: return find(t.left, k) else: return find(t.right, k) def inorder(t): if t == None: return inorder(t.left) print(" " + str(t.k), end="") inorder(t.right) def preorder(t): if t == None: return print(" " + str(t.k), end="") preorder(t.left) preorder(t.right) def output(t): inorder(t) print() preorder(t) print() t = None data = [] m = int(input()) for i in range(m): data.append(list(input().split())) for i in range(m): if data[i][0] == "insert": t = insert(t, int(data[i][1]), int(data[i][2])) elif data[i][0] == "print": output(t) elif data[i][0] == "find": result = find(t, int(data[i][1])) if result == 1: print("yes") else: print("no") else: t = erase(t, int(data[i][1])) ```
instruction
0
67,228
13
134,456
Yes
output
1
67,228
13
134,457
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` # -*- coding: utf-8 -*- class Node: def __init__(self, key, priority, left=None, right=None): self.key = key self.priority = priority self.left = left self.right = right def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, priority): if not t: return Node(key, priority) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, priority) if t.priority < t.left.priority: t = rightRotate(t) else: t.right = insert(t.right, key, priority) if t.priority < t.right.priority: t = leftRotate(t) return t def erase(t, key): if not t: return None if key == t.key: if (not t.left) and (not t.right): return None elif not t.left: t = leftRotate(t) elif not t.right: t = rightRotate(t) else: if t.left.priority > t.right.priority: t = rightRotate(t) else: t = leftRotate(t) return erase(t, key) elif key > t.key: t.right = erase(t.right, key) else: t.left = erase(t.left, key) return t def find(t, key): if t.key == key: print("yes") elif t.key < key and t.right != None: find(t.right, key) elif t.key > key and t.left != None: find(t.left, key) else: print("no") return 0 def in_print(t): if t.left != None: in_print(t.left) print(" " + str(t.key), end='') if t.right != None: in_print(t.right) def pre_print(t): print(" " + str(t.key), end='') if t.left != None: pre_print(t.left) if t.right != None: pre_print(t.right) Treap = None num = int(input()) for i in range(num): string = list(input().split()) if string[0] == "insert": key = int(string[1]) priority = int(string[2]) Treap = insert(Treap, key, priority) elif string[0] == "find": key = int(string[1]) find(Treap, key) elif string[0] == "delete": key = int(string[1]) Treap = erase(Treap, key) else: in_print(Treap) print() pre_print(Treap) print() ```
instruction
0
67,229
13
134,458
Yes
output
1
67,229
13
134,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` class Node: def __init__(self, key:int, priority:int): self.key = key self.priority = priority self.left = None self.right = None class Tree: def __init__(self): self.root = None def leftRotate(self, t:Node): s:Node = t.right t.right = s.left s.left = t if t.key == self.root.key: self.root = s return s def rightRotate(self, t:Node): s:Node = t.left t.left = s.right s.right = t if t.key == self.root.key: self.root = s return s def insert(self, t:Node, key:int, priority:int): if not self.root: self.root = Node(key, priority) return self.root if not t: return Node(key, priority) if key == t.key: return t if key < t.key: t.left = self.insert(t.left, key, priority) if t.priority < t.left.priority: t = self.rightRotate(t) else: t.right = self.insert(t.right, key, priority) if t.priority < t.right.priority: t = self.leftRotate(t) return t def delete(self, t:Node, key:int): if not t: return None if key < t.key: t.left = self.delete(t.left, key) elif key > t.key: t.right = self.delete(t.right, key) else: return self._delete(t, key) return t def _delete(self, t:Node, key:int): if not t.left and not t.right: return None elif not t.left: t = self.leftRotate(t) elif not t.right: t = self.rightRotate(t) else: if t.left.priority > t.right.priority: t = self.rightRotate(t) else: t = self.leftRotate(t) return self.delete(t, key) def Preorder(target:Node): yield target.key if target.left != None: yield from Preorder(target.left) if target.right != None: yield from Preorder(target.right) def Inorder(target:Node): if target.left != None: yield from Inorder(target.left) yield target.key if target.right != None: yield from Inorder(target.right) def find(target:Node,findkey:int): return node_of_key(target, findkey) != None def node_of_key(target:Node,findkey:int): if target.key == findkey: return target elif target.key > findkey: if target.left: return node_of_key(target.left, findkey) else: if target.right: return node_of_key(target.right, findkey) return None def min_value_node_of_tree(root:Node): if root.left == None: return root else: return min_value_node_of_tree(root.left) from sys import stdin tree = Tree() n = int(input()) lines = stdin.readlines() for line in lines: proc,*param = line.split() if proc == "insert": if not tree.root: tree.root = Node(int(param[0]), int(param[1])) else: tree.insert(tree.root, int(param[0]), int(param[1])) elif proc == "find": print("yes" if find(tree.root, int(param[0])) else "no") elif proc == "delete": tree.delete(tree.root, int(param[0])) else: print(" ",end="") print(*Inorder(tree.root)) print(" ",end="") print(*Preorder(tree.root)) ```
instruction
0
67,230
13
134,460
Yes
output
1
67,230
13
134,461
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` # -*- coding: utf-8 -*- class Node: def __init__(self, key, priority): self.key = key self.priority = priority self.left = None self.right = None def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, priority): if not t: return Node(key, priority) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, priority) if t.priority < t.left.priority: t = rightRotate(t) else: t.right = insert(t.right, key, priority) if t.priority < t.right.priority: t = leftRotate(t) return t def erase(t, key): if not t: return None if key == t.key: if (not t.left) and (not t.right): return None elif not t.left: t = leftRotate(t) elif not t.right: t = rightRotate(t) else: if t.left.priority > t.right.priority: t = rightRotate(t) else: t = leftRotate(t) return erase(t, key) if key < t.key: t.left = erase(t.left, key) else: t.right = erase(t.right, key) return t def find(t, key): if t.key == key: print("yes") return 0 elif t.key < key and (not t.right): find(t.right, key) elif t.key > key and (not t.left): find(t.left, key) else: print("no") return 0 def in_print(t): if not t.left: in_print(t.left) print(" " + str(t), end='') if not t.right: in_print(t.right) def pre_print(t): print(" " + str(t), end='') if not t.left: pre_print(t.left) if not t.right: pre_print(t.right) Treap = None num = int(input()) for i in range(num): string = list(input().split()) if string[0] == "insert": key = int(string[1]) priority = int(string[2]) insert(Treap, key, priority) elif string[0] == "find": key = int(string[1]) find(Treap, key) elif string[0] == "delete": key = int(string[1]) erase(Treap, key) else: in_print(Treap) print() pre_print(Treap) print() ```
instruction
0
67,231
13
134,462
No
output
1
67,231
13
134,463
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` # -*- coding: utf-8 -*- class Node: def __init__(self, key, priority, left=None, right=None): self.key = key self.priority = priority self.left = left self.right = right def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, priority): if not t: return Node(key, priority) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, priority) if t.priority < t.left.priority: t = rightRotate(t) else: t.right = insert(t.right, key, priority) if t.priority < t.right.priority: t = leftRotate(t) return t def erase(t, key): if not t: return None if key == t.key: if (not t.left) and (not t.right): return None elif not t.left: t = leftRotate(t) elif not t.right: t = rightRotate(t) else: if t.left.priority > t.right.priority: t = rightRotate(t) else: t = leftRotate(t) return erase(t, key) def find(t, key): if t.key == key: print("yes") elif t.key < key and t.right != None: find(t.right, key) elif t.key > key and t.left != None: find(t.left, key) else: print("no") return 0 def in_print(t): if t.left != None: in_print(t.left) print(" " + str(t), end='') if t.right != None: in_print(t.right) def pre_print(t): print(" " + str(t), end='') if t.left != None: pre_print(t.left) if t.right != None: pre_print(t.right) Treap = None num = int(input()) for i in range(num): string = list(input().split()) if string[0] == "insert": key = int(string[1]) priority = int(string[2]) Treap = insert(Treap, key, priority) elif string[0] == "find": key = int(string[1]) find(Treap, key) elif string[0] == "delete": key = int(string[1]) Treap = erase(Treap, key) else: in_print(Treap) print() pre_print(Treap) print() ```
instruction
0
67,232
13
134,464
No
output
1
67,232
13
134,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` class Node: def __init__(self, key, pri): self.key = key self.pri = pri self.left = None self.right = None def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == None: return Node(key, pri) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, pri) if t.pri < t.left.pri: t = rightRotate(t) else: t.right = insert(t.right, key, pri) if t.pri < t.right.pri: t = leftRotate(t) return t def delete(t, key): if t == None: return None if key == t.key: if t.right == None and t.left == None: return None elif t.left == None: t = leftRotate(t) elif t.right == None: t = rightRotate(t) else : if t.left.pri > t.right.pri: t = rightRotate(t) else : t = leftRotate(t) return delete(t, key) if key < t.key: t.left = delete(t.left, key) else: t.right = delete(t.right, key) return t def find(t, key): if t == None: return False if key == t.key: return True if key < t.key: return find(t.left, key) else: return find(t.right, key) def priorder(t): if t == None: return print(" " + str(t.key), end='') priorder(t.left) priorder(t.right) def inorder(t): if t == None: return inorder(t.left) print(" " + str(t.key), end='') inorder(t.right) m = int(input()) t = None for i in range(m): com = input().split() if com[0] == "insert": t = insert(t, int(com[1]), int(com[2])) elif com[0] == "find": if find(t, int(com[1])): print("yes") else : print("no") elif com[0] == "delete": delete(t, int(com[1])) elif com[0] == "print": inorder(t) print() priorder(t) print() ```
instruction
0
67,233
13
134,466
No
output
1
67,233
13
134,467
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. A binary search tree can be unbalanced depending on features of data. For example, if we insert $n$ elements into a binary search tree in ascending order, the tree become a list, leading to long search times. One of strategies is to randomly shuffle the elements to be inserted. However, we should consider to maintain the balanced binary tree where different operations can be performed one by one depending on requirement. We can maintain the balanced binary search tree by assigning a priority randomly selected to each node and by ordering nodes based on the following properties. Here, we assume that all priorities are distinct and also that all keys are distinct. * binary-search-tree property. If $v$ is a left child of $u$, then $v.key < u.key$ and if $v$ is a right child of $u$, then $u.key < v.key$ * heap property. If $v$ is a child of $u$, then $v.priority < u.priority$ This combination of properties is why the tree is called Treap (tree + heap). An example of Treap is shown in the following figure. <image> Insert To insert a new element into a Treap, first of all, insert a node which a randomly selected priority value is assigned in the same way for ordinal binary search tree. For example, the following figure shows the Treap after a node with key = 6 and priority = 90 is inserted. <image> It is clear that this Treap violates the heap property, so we need to modify the structure of the tree by rotate operations. The rotate operation is to change parent-child relation while maintaing the binary-search-tree property. <image> The rotate operations can be implemented as follows. rightRotate(Node t) Node s = t.left t.left = s.right s.right = t return s // the new root of subtree | leftRotate(Node t) Node s = t.right t.right = s.left s.left = t return s // the new root of subtree ---|--- The following figure shows processes of the rotate operations after the insert operation to maintain the properties. <image> The insert operation with rotate operations can be implemented as follows. insert(Node t, int key, int priority) // search the corresponding place recursively if t == NIL return Node(key, priority) // create a new node when you reach a leaf if key == t.key return t // ignore duplicated keys if key < t.key // move to the left child t.left = insert(t.left, key, priority) // update the pointer to the left child if t.priority < t.left.priority // rotate right if the left child has higher priority t = rightRotate(t) else // move to the right child t.right = insert(t.right, key, priority) // update the pointer to the right child if t.priority < t.right.priority // rotate left if the right child has higher priority t = leftRotate(t) return t Delete To delete a node from the Treap, first of all, the target node should be moved until it becomes a leaf by rotate operations. Then, you can remove the node (the leaf). These processes can be implemented as follows. delete(Node t, int key) // seach the target recursively if t == NIL return NIL if key < t.key // search the target recursively t.left = delete(t.left, key) else if key > t.key t.right = delete(t.right, key) else return _delete(t, key) return t _delete(Node t, int key) // if t is the target node if t.left == NIL && t.right == NIL // if t is a leaf return NIL else if t.left == NIL // if t has only the right child, then perform left rotate t = leftRotate(t) else if t.right == NIL // if t has only the left child, then perform right rotate t = rightRotate(t) else // if t has both the left and right child if t.left.priority > t.right.priority // pull up the child with higher priority t = rightRotate(t) else t = leftRotate(t) return delete(t, key) Write a program which performs the following operations to a Treap $T$ based on the above described algorithm. * insert ($k$, $p$): Insert a node containing $k$ as key and $p$ as priority to $T$. * find ($k$): Report whether $T$ has a node containing $k$. * delete ($k$): Delete 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 200,000$ * $0 \leq k, p \leq 2,000,000,000$ * The height of the binary tree does not exceed 50 if you employ the above algorithm * The keys in the binary search tree are all different. * The priorities in the binary search tree are all different. * The size of output $\leq 10$ MB Input In the first line, the number of operations $m$ is given. In the following $m$ lines, operations represented by insert $k \; p$, find $k$, delete $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 16 insert 35 99 insert 3 80 insert 1 53 insert 14 25 insert 80 76 insert 42 3 insert 86 47 insert 21 12 insert 7 10 insert 6 90 print find 21 find 22 delete 35 delete 99 print Output 1 3 6 7 14 21 35 42 80 86 35 6 3 1 14 7 21 80 42 86 yes no 1 3 6 7 14 21 42 80 86 6 3 1 80 14 7 21 42 86 Submitted Solution: ``` class Node: def __init__(self, key, pri): self.key = key self.pri = pri self.left = None self.right = None def rightRotate(t): s = t.left t.left = s.right s.right = t return s def leftRotate(t): s = t.right t.right = s.left s.left = t return s def insert(t, key, pri): if t == None: return Node(key, pri) if key == t.key: return t if key < t.key: t.left = insert(t.left, key, pri) if t.pri < t.left.pri: t = rightRotate(t) else: t.right = insert(t.right, key, pri) if t.pri < t.right.pri: t = leftRotate(t) return t def delete(t, key): if t == None: return None if key == t.key: if t.right == None and t.left == None: return None elif t.left == None: t = leftRotate(t) elif t.right == None: t = rightRotate(t) else : if t.left.pri > t.right.pri: t = rightRotate(t) else : t = leftRotate(t) return delete(t, key) if key < t.key: t.left = delete(t.left, key) else: t.right = delete(t.right, key) return t def find(t, key): if t == None: return False if key == t.key: return True if key < t.key: return find(t.left, key) else: return find(t.right, key) def priorder(t): if t == None: return print('' + str(t.key), end='') priorder(t.left) priorder(t.right) def inorder(t): if t == None: return inorder(t.left) print('' + str(t.key), end='') inorder(t.right) m = int(input()) t = None for _ in range(m): com = input().split() if com[0] == 'insert': t = insert(t, int(com[1]), int(com[2])) elif com[0] == 'find': if find(t, int(com[1])): print('yes') else : print('no') elif com[0] == 'delete': delete(t, int(com[1])) elif com[0] == 'print': inorder(t) print() priorder(t) print() ```
instruction
0
67,234
13
134,468
No
output
1
67,234
13
134,469
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,466
13
134,932
Tags: dfs and similar, dp, games, trees Correct Solution: ``` # -*- coding: utf-8 -*- # import bisect # import heapq # import math # import random # from collections import Counter, defaultdict, deque # from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal # from fractions import Fraction # from functools import lru_cache, reduce # from itertools import combinations, combinations_with_replacement, product, permutations, accumulate # from operator import add, mul, sub, itemgetter, attrgetter import sys # sys.setrecursionlimit(10**6) # readline = sys.stdin.buffer.readline readline = sys.stdin.readline INF = 2**62-1 def read_int(): return int(readline()) def read_int_n(): return list(map(int, readline().split())) def read_float(): return float(readline()) def read_float_n(): return list(map(float, readline().split())) def read_str(): return readline().strip() def read_str_n(): return readline().strip().split() def error_print(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.perf_counter() ret = f(*args, **kwargs) e = time.perf_counter() error_print(e - s, 'sec') return ret return wrap from collections import defaultdict from functools import reduce @mt def slv(N, A, B, DA, DB, UV): if 2*DA >= DB: return 'Alice' g = defaultdict(list) for u, v in UV: g[u].append(v) g[v].append(u) def dfs(u): d = {u: 0} s = [u] while s: u = s.pop() for v in g[u]: if v in d: continue d[v] = d[u] + 1 s.append(v) return d d = dfs(A) if d[B] <= DA: return 'Alice' mv = reduce(lambda m, i: max(m, (d[i], i)), range(1, N+1), (-INF, -1)) # print(mv) d = dfs(mv[1]) diam = max(d.values()) # print(diam) if 2*DA >= diam: return 'Alice' return 'Bob' def main(): for _ in range(read_int()): N, A, B, DA, DB = read_int_n() UV = [read_int_n() for _ in range(N-1)] print(slv(N, A, B, DA, DB, UV)) if __name__ == '__main__': main() ```
output
1
67,466
13
134,933
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,467
13
134,934
Tags: dfs and similar, dp, games, trees Correct Solution: ``` import io import os from collections import Counter, defaultdict, deque def bfs(source, getNbr): q = deque([source]) dist = {source: 0} while q: node = q.popleft() d = dist[node] for nbr in getNbr(node): if nbr not in dist: q.append(nbr) dist[nbr] = d + 1 return dist def longestPathFrom(root, getNbr): """Get longest path from source in an unweighted graph""" # BFS assert root queue = deque([root]) parent = {root: None} while queue: curr = queue.popleft() for child in getNbr(curr): if child not in parent: queue.append(child) parent[child] = curr # When loop exits, curr is the last element that was processed. Reconstruct the path ret = [curr] while curr in parent and parent[curr]: curr = parent[curr] ret.append(curr) return ret[::-1] def treeDiameter(graph): """Returns longest path in the tree""" # One end of the diameter has to be the farthest point from an arbitrary node # Then finding farthest node from that will give a diameter path of the graph initNode = 1 def getNbr(node): return graph[node] path1 = longestPathFrom(initNode, getNbr) assert path1[0] == initNode path2 = longestPathFrom(path1[-1], getNbr) return path2 def solve(N, A, B, DA, DB, edges): graph = [[] for i in range(N + 1)] for u, v in edges: graph[u].append(v) graph[v].append(u) # Alice wins in first move def getNbr(node): return graph[node] dist = bfs(A, getNbr) if dist[B] <= DA: return "Alice" # Alice can move to center then win diameter = treeDiameter(graph) if 2 * DA >= len(diameter) - 1: return "Alice" # Bob can escape even when cornered if DB > 2 * DA: return "Bob" return "Alice" if __name__ == "__main__": input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline TC = int(input()) for tc in range(1, TC + 1): N, A, B, DA, DB = [int(x) for x in input().split()] edges = [[int(x) for x in input().split()] for i in range(N - 1)] # 1 indexed ans = solve(N, A, B, DA, DB, edges) print(ans) ```
output
1
67,467
13
134,935
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,468
13
134,936
Tags: dfs and similar, dp, games, trees Correct Solution: ``` from sys import stdin def inp(): return stdin.buffer.readline().rstrip().decode('utf8') def itg(): return int(stdin.buffer.readline()) def mpint(): return map(int, stdin.buffer.readline().split()) # ############################## import from copy import deepcopy def to_tree(graph, root=0): """ graph: undirected graph (adjacency list) :return directed graph that parent -> children """ graph[:] = map(set, graph) stack = [[root]] while stack: if not stack[-1]: del stack[-1] continue vertex = stack[-1].pop() for e in graph[vertex]: graph[e].remove(vertex) stack.append(list(graph[vertex])) graph[:] = map(list, graph) def to_graph(tree, root=0): """ :return undirected graph (adjacency list) """ tree[:] = map(set, tree) for node1, node_set in enumerate(deepcopy(tree)): for node2 in node_set: tree[node2].add(node1) tree[:] = map(list, tree) def tree_distance(tree, u, v): # bfs if u == v: return 0 graph = deepcopy(tree) to_graph(graph) graph[:] = map(set, graph) curr = {u} step = 1 while True: nxt = set() for node in curr: if v in graph[node]: return step nxt |= graph[node] curr = nxt step += 1 def tree_bfs(tree, start=0, flat=False): stack = [start] result = [] while stack: new_stack = [] if flat: result.extend(stack) else: result.append(stack) for node in stack: new_stack.extend(tree[node]) stack = new_stack return result def tree_farthest(tree): """ :returns u, v, n that u, v is the both ends of one of the longest chain and the longest chain has n nodes """ # 2 times bfs node1 = tree_bfs(tree, flat=True)[-1] to_graph(tree) to_tree(tree, node1) bfs_data = tree_bfs(tree, node1) node2 = bfs_data[-1][-1] return node1, node2, len(bfs_data) # ############################## main def solve(): n, a, b, da, db = mpint() a -= 1 b -= 1 tree = [[] for _ in range(n)] for _ in range(n - 1): u, v = mpint() u -= 1 v -= 1 tree[u].append(v) tree[v].append(u) if db - da < 2: return True to_tree(tree) if tree_distance(tree, a, b) <= da: return True longest = tree_farthest(tree)[2] dis = longest >> 1 return dis <= da or db < da * 2 + 1 for __ in range(itg()): print("Alice" if solve() else "Bob") # Please check! ```
output
1
67,468
13
134,937
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,469
13
134,938
Tags: dfs and similar, dp, games, trees Correct Solution: ``` # -*- coding: utf-8 -*- # import bisect # import heapq # import math # import random # from collections import Counter, defaultdict, deque # from decimal import ROUND_CEILING, ROUND_HALF_UP, Decimal # from fractions import Fraction # from functools import lru_cache, reduce # from itertools import combinations, combinations_with_replacement, product, permutations, accumulate # from operator import add, mul, sub, itemgetter, attrgetter import sys # sys.setrecursionlimit(10**6) # readline = sys.stdin.buffer.readline readline = sys.stdin.readline INF = 2**62-1 def read_int(): return int(readline()) def read_int_n(): return list(map(int, readline().split())) def read_float(): return float(readline()) def read_float_n(): return list(map(float, readline().split())) def read_str(): return readline().strip() def read_str_n(): return readline().strip().split() def error_print(*args): print(*args, file=sys.stderr) def mt(f): import time def wrap(*args, **kwargs): s = time.perf_counter() ret = f(*args, **kwargs) e = time.perf_counter() error_print(e - s, 'sec') return ret return wrap from collections import defaultdict from functools import reduce @mt def slv(N, A, B, DA, DB, UV): if 2*DA >= DB: return 'Alice' g = defaultdict(list) for u, v in UV: g[u].append(v) g[v].append(u) def dfs(u): d = {u: 0} s = [u] while s: u = s.pop() for v in g[u]: if v in d: continue d[v] = d[u] + 1 s.append(v) return d d = dfs(A) if d[B] <= DA: return 'Alice' mv = reduce(lambda m, i: max(m, (d[i], i)), d.keys(), (-INF, -1)) d = dfs(mv[1]) diam = max(d.values()) if 2*DA >= diam: return 'Alice' return 'Bob' def main(): for _ in range(read_int()): N, A, B, DA, DB = read_int_n() UV = [read_int_n() for _ in range(N-1)] print(slv(N, A, B, DA, DB, UV)) if __name__ == '__main__': main() ```
output
1
67,469
13
134,939
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,470
13
134,940
Tags: dfs and similar, dp, games, trees Correct Solution: ``` from collections import deque T = int(input()) ans = ['Bob']*T for t in range(T): n,a,b,da,db = map(int, input().split()) a -= 1 b -= 1 edge = [[] for _ in range(n)] for i in range(n-1): u,v = map(int, input().split()) edge[u-1].append(v-1) edge[v-1].append(u-1) visited = [False]*n d = deque() visited[a]=True d.append((a,0)) while len(d)>0: v,cnt = d.popleft() for w in edge[v]: if visited[w]==False: visited[w]=True if w==b: dist = cnt+1 d.append((w,cnt+1)) if dist<=da: ans[t] = 'Alice' continue visited = [False]*n d = deque() visited[v]=True d.append((v,0)) while len(d)>0: v,cnt = d.popleft() for w in edge[v]: if visited[w]==False: visited[w]=True d.append((w,cnt+1)) if min(cnt,db)<=da*2: ans[t] = 'Alice' print(*ans, sep='\n') ```
output
1
67,470
13
134,941
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,471
13
134,942
Tags: dfs and similar, dp, games, trees Correct Solution: ``` import sys from collections import deque as dq input = sys.stdin.readline for _ in range(int(input())): N, a, b, da, db = map(int, input().split()) e = [[] for _ in range(N + 1)] for _ in range(N - 1): u, v = map(int, input().split()) e[u].append(v) e[v].append(u) if da * 2 + 1 > db: print("Alice") continue Q = dq([a]) inf = N + 1 dpa = [inf] * (N + 1) dpa[a] = 0 while len(Q): x = Q.popleft() for y in e[x]: if dpa[y] > dpa[x] + 1: dpa[y] = dpa[x] + 1 Q.append(y) if dpa[b] <= da: print("Alice") continue far = a for v in range(1, N + 1): if dpa[far] < dpa[v]: far = v dp = [inf] * (N + 1) dp[far] = 0 Q.append(far) while len(Q): x = Q.popleft() for y in e[x]: if dp[y] > dp[x] + 1: dp[y] = dp[x] + 1 Q.append(y) dia = -(-max(dp[1: ]) // 2) if dia <= da: print("Alice") continue print("Bob") ```
output
1
67,471
13
134,943
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,472
13
134,944
Tags: dfs and similar, dp, games, trees Correct Solution: ``` from sys import stdin input = stdin.readline q = int(input()) for _ in range(q): n,sa,sb,a,b = map(int,input().split()) sa -=1 sb -=1 nbr = [[] for i in range(n)] for i in range(n-1): x, y = map(int,input().split()) x -= 1 y-= 1 nbr[x].append(y) nbr[y].append(x) if 2 * a >= b: print("Alice") else: #jak najwieksza odleglosc > 2*a to bob, inaczej alice q = [sa] ind = 0 dist = [-1] * n dist[sa] = 0 while q: if ind >= len(q): break v = q[ind] ind += 1 for w in nbr[v]: if dist[w] == -1: q.append(w) dist[w] = dist[v] + 1 if dist[sb] <= a: print("Alice") else: q = [0] ind = 0 dist = [-1] * n dist[0] = 0 while q: if ind >= len(q): break v = q[ind] ind += 1 for w in nbr[v]: if dist[w] == -1: q.append(w) dist[w] = dist[v] + 1 maksik = 0 best = 0 for i in range(n): if dist[i] > maksik: best = i maksik = dist[i] q = [best] ind = 0 dist = [-1] * n dist[best] = 0 while q: if ind >= len(q): break v = q[ind] ind += 1 for w in nbr[v]: if dist[w] == -1: q.append(w) dist[w] = dist[v] + 1 if max(dist) > 2*a: print("Bob") else: print("Alice") ```
output
1
67,472
13
134,945
Provide tags and a correct Python 3 solution for this coding contest problem. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image>
instruction
0
67,473
13
134,946
Tags: dfs and similar, dp, games, trees Correct Solution: ``` import sys ii = lambda: sys.stdin.readline().strip() idata = lambda: [int(x) for x in ii().split()] def bfs(graph, start_ver): # ищет самую дальнюю вершину от данной вершины в данном графе, # выводит эту вершину и длину пути до неё visited = set() queue = [[start_ver, 0]] visited.add(start_ver) ans_way_length, ans_ver = 0, start_ver while queue: ver = queue.pop(0) for new_ver in graph[ver[0]]: if new_ver not in visited: visited.add(new_ver) queue += [[new_ver, ver[1] + 1]] if ans_way_length < ver[1] + 1: ans_ver, ans_way_length = new_ver, ver[1] + 1 return ans_ver, ans_way_length def solve(): n, a, b, da, db = idata() graph = {} for i in range(n - 1): v, u = idata() if not v in graph: graph[v] = [u] else: graph[v] += [u] if not u in graph: graph[u] = [v] else: graph[u] += [v] used = set() s1 = [a] d = [0] * (n + 1) l = 0 while s1: s2 = [] for i in s1: used.add(i) d[i] = l for j in graph[i]: if j not in used: s2 += [j] l += 1 s1 = s2[::] a = 0 q = d[b] k = max(d) for i in range(len(d)): if d[i] == k: a = i break used = set() s1 = [a] d = [0] * (n + 1) l = 0 while s1: s2 = [] for i in s1: used.add(i) d[i] = l for j in graph[i]: if j not in used: s2 += [j] l += 1 s1 = s2[::] if max(d) <= 2 * da or q <= da or 2 * da >= db: print('Alice') else: print('Bob') return for t in range(int(ii())): solve() ```
output
1
67,473
13
134,947
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` from collections import deque import sys input = sys.stdin.buffer.readline def main(): n, a, b, da, db = map(int, input().split()) edges = [[] for _ in range(n)] for _ in range(n - 1): u, v = map(int, input().split()) u -= 1 v -= 1 edges[u].append(v) edges[v].append(u) if da * 2 >= db: print("Alice") return a -= 1 b -= 1 queue = deque() queue.append(a) queue.append(0) check = [False for _ in range(n)] check[a] = True ab = -1 while queue: pos = queue.popleft() d = queue.popleft() + 1 for n_pos in edges[pos]: if check[n_pos]: continue check[n_pos] = True if n_pos == b: ab = d queue.append(n_pos) queue.append(d) if ab <= da: print("Alice") return queue = deque() queue.append(pos) queue.append(0) check = [False for _ in range(n)] check[pos] = True while queue: pos = queue.popleft() d = queue.popleft() + 1 for n_pos in edges[pos]: if check[n_pos]: continue check[n_pos] = True queue.append(n_pos) queue.append(d) d -= 1 if d <= da * 2: print("Alice") else: print("Bob") t = int(input()) for _ in range(t): main() ```
instruction
0
67,474
13
134,948
Yes
output
1
67,474
13
134,949
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` import sys input = sys.stdin.buffer.readline T = int(input()) def f(x,y): dg = 10**6 if x == 0: return y elif x < dg: if x > y: return y*dg + x else: return x*dg + y else: xs,xf = divmod(x,dg) if xs < y: xs = y else: return x if xf < xs: return xf*dg + xs else: return xs*dg + xf for testcase in range(T): n,a,b,da,db = map(int,input().split()) a -= 1 b -= 1 edge = [[] for i in range(n)] for i in range(n-1): u,v = map(int,input().split()) edge[u-1].append(v-1) edge[v-1].append(u-1) pa = [-1]*n pa[a] = 0 tank = [a] order = [] par = [-1]*n while tank: now = tank.pop() order.append(now) for e in edge[now]: if pa[e] == -1: pa[e] = pa[now] + 1 tank.append(e) par[e] = now pb = [-1]*n pb[b] = 0 tank = [b] while tank: now = tank.pop() for e in edge[now]: if pb[e] == -1: pb[e] = pb[now] + 1 tank.append(e) #first if (2*da + 1 > db or pa[b] <= da ): print("Alice") else: depth = [0]*n dg = 10**6 for e in order[::-1]: if par[e] == -1: continue depth[par[e]] = f(depth[par[e]],(depth[e]%dg)+1) flag = False for e in order: se,fi = divmod(depth[e],dg) if fi >= 2*da+1: flag = True break for nxt in edge[e]: if par[e] == nxt: continue nse,nfi = divmod(depth[nxt],dg) if nfi == fi-1: depth[nxt] = f(depth[nxt],se+1) else: depth[nxt] = f(depth[nxt],fi+1) if flag: print("Bob") else: print("Alice") ```
instruction
0
67,475
13
134,950
Yes
output
1
67,475
13
134,951
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` import sys from collections import deque # sys.stdin = open("input.txt") def dist(G, n, s): D = [None] * n Q = deque() Q.append(s) D[s] = 0 while Q: f = Q.popleft() for t in G[f]: if D[t] is None: D[t] = D[f] + 1 Q.append(t) return D def main(): tn = int(input()) for ti in range(tn): n, a, b, da, db = map(int, input().split()) a -= 1 b -= 1 G = [[] for _ in range(n)] for _ in range(n-1): u, v = map(int, input().split()) G[u-1].append(v-1) G[v-1].append(u-1) Da = dist(G, n, a) me = max(enumerate(Da), key=lambda x: x[1])[0] Dm = dist(G, n, me) if Da[b] <= da or db <= 2 * da or max(Dm) <= 2 * da: print("Alice") else: print("Bob") if __name__ == "__main__": main() ```
instruction
0
67,476
13
134,952
Yes
output
1
67,476
13
134,953
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` import sys def minp(): return sys.stdin.readline().strip() def mint(): return int(minp()) def mints(): return map(int, minp().split()) def solve(): n, a, b, da, db = mints() e = [[] for i in range(n+1)] for i in range(n-1): u, v = mints() e[u].append(v) e[v].append(u) if db < da*2+1: return False q = [0]*(n+2) ql = 0 qr = 1 d = [None]*(n+1) d[a] = 0 q[0] = a while ql < qr: x = q[ql] ql += 1 for v in e[x]: if d[v] is None: d[v] = d[x] + 1 q[qr] = v qr += 1 #print(d) if d[b] <= da: return False far = q[qr-1] #print(far, a, b, d[far]) if d[far] >= da*2+1: return True ql = 0 qr = 1 d = [None]*(n+1) d[far] = 0 q[0] = far while ql < qr: x = q[ql] ql += 1 for v in e[x]: if d[v] is None: d[v] = d[x] + 1 q[qr] = v qr += 1 far2 = q[qr-1] #print(far, far2, d[far2]) return d[far2] >= da*2+1 for i in range(mint()): print(["Alice","Bob"][solve()]) ```
instruction
0
67,477
13
134,954
Yes
output
1
67,477
13
134,955
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` import sys from collections import deque t = int(input()) for _ in range(t): n, av, bv, da, db = list(map(int, input().split())) def readTree(n): adj = [set() for _ in range(n)] for _ in range(n - 1): u, v = map(int, sys.stdin.readline().split()) adj[u - 1].add(v - 1) adj[v - 1].add(u - 1) return adj adj = readTree(n) dq = deque() dq.append(0) parent = [-2] + [-1] * (n - 1) depth = [0] * n while dq: nd = dq.popleft() for a in adj[nd]: if parent[a] < 0: parent[a] = nd depth[a] = depth[nd] + 1 dq.append(a) depth[0] = 0 av -= 1 bv -= 1 parent[0] = 0 # print(depth, depth[av], depth[bv]) if depth[av] == depth[bv]: d=2 while parent[bv] != parent[av]: d += 2 bv = parent[bv] av = parent[av] elif depth[av] < depth[bv]: count=0 d = depth[bv] - depth[av] d+=2 while depth[bv]!=depth[av]: bv=parent[bv] while parent[bv]!=parent[av]: d+=2 bv=parent[bv] av=parent[av] else: d = depth[av] - depth[bv] while depth[bv]!=depth[av]: av=parent[av] while parent[bv]!=parent[av]: d+=2 bv=parent[bv] av=parent[av] # print(d) if d <= da: print("Alice") elif db - da > da: print("Bob") else: print("Alice") ```
instruction
0
67,478
13
134,956
No
output
1
67,478
13
134,957
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` #list(map(int, input().rstrip().split())) def dist(m, n, A, B = -1): s = [[A, 0]] massimo, massimo_nodo = 0, 0 distanza = -1 v = [-1] * n while s: el, dis = s.pop() if dis > massimo: massimo = dis massimo_nodo = el if el == B: distanza = dis for child in m[el]: if v[child] == -1: v[child] = 1 s.append([child, dis+1]) return massimo, massimo_nodo, distanza t = int(input()) for test in range(t): [n,a,b,da,db] = list(map(int, input().rstrip().split())) m = [list() for i in range(n)] for i in range(n-1): [x,y] = list(map(int, input().rstrip().split())) m[x-1].append(y-1) m[y-1].append(x-1) _, foglia, _ = dist(m, n, 0) diam, _, _ = dist(m, n, foglia) _, _, dist_AB = dist(m, n, a-1, b-1) if db > 2*da and diam >= db and dist_AB > da: print("Bob") else: print("Alice") ```
instruction
0
67,479
13
134,958
No
output
1
67,479
13
134,959
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` from collections import deque t = int(input()) for _ in range(t): n,a,b,da,db = map(int, input().split(' ')) a -= 1 b -= 1 d = [0]*n vis = [0]*n g = [[] for i in range(n)] for i in range(n): g[i] = [] for i in range(n-1): u,v = map(int, input().split(' ')) u-=1 v-=1 g[u].append(v) g[v].append(u) q = deque() q.append(0) vis[0] = 1 while q: u = q.popleft() for v in g[u]: if not vis[v]: d[v] = d[u] + 1 vis[v] = 1 q.append(v) lp = max(d) if da > db: print("Alice") elif d[a] + d[b] <= da: print("Alice") else: if lp <= da+2: print("Alice") else: if db >= da + 2: print("Bob") else: print("Alice") ```
instruction
0
67,480
13
134,960
No
output
1
67,480
13
134,961
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Alice and Bob are playing a fun game of tree tag. The game is played on a tree of n vertices numbered from 1 to n. Recall that a tree on n vertices is an undirected, connected graph with n-1 edges. Initially, Alice is located at vertex a, and Bob at vertex b. They take turns alternately, and Alice makes the first move. In a move, Alice can jump to a vertex with distance at most da from the current vertex. And in a move, Bob can jump to a vertex with distance at most db from the current vertex. The distance between two vertices is defined as the number of edges on the unique simple path between them. In particular, either player is allowed to stay at the same vertex in a move. Note that when performing a move, a player only occupies the starting and ending vertices of their move, not the vertices between them. If after at most 10^{100} moves, Alice and Bob occupy the same vertex, then Alice is declared the winner. Otherwise, Bob wins. Determine the winner if both players play optimally. Input Each test contains multiple test cases. The first line contains the number of test cases t (1 ≤ t ≤ 10^4). Description of the test cases follows. The first line of each test case contains five integers n,a,b,da,db (2≤ n≤ 10^5, 1≤ a,b≤ n, a≠ b, 1≤ da,db≤ n-1) — the number of vertices, Alice's vertex, Bob's vertex, Alice's maximum jumping distance, and Bob's maximum jumping distance, respectively. The following n-1 lines describe the edges of the tree. The i-th of these lines contains two integers u, v (1≤ u, v≤ n, u≠ v), denoting an edge between vertices u and v. It is guaranteed that these edges form a tree structure. It is guaranteed that the sum of n across all test cases does not exceed 10^5. Output For each test case, output a single line containing the winner of the game: "Alice" or "Bob". Example Input 4 4 3 2 1 2 1 2 1 3 1 4 6 6 1 2 5 1 2 6 5 2 3 3 4 4 5 9 3 9 2 5 1 2 1 6 1 9 1 3 9 5 7 9 4 8 4 3 11 8 11 3 3 1 2 11 9 4 9 6 5 2 10 3 2 5 9 8 3 7 4 7 10 Output Alice Bob Alice Alice Note In the first test case, Alice can win by moving to vertex 1. Then wherever Bob moves next, Alice will be able to move to the same vertex on the next move. <image> In the second test case, Bob has the following strategy to win. Wherever Alice moves, Bob will always move to whichever of the two vertices 1 or 6 is farthest from Alice. <image> Submitted Solution: ``` # by the authority of GOD author: manhar singh sachdev # import os,sys from io import BytesIO, IOBase from collections import defaultdict,deque from copy import deepcopy def longest_path(path,n): st = [1] depth = [[0,0] for _ in range(n+1)] ans = 0 while len(st): if not len(path[st[-1]]): x = depth[st.pop()] ans = max(ans,sum(x)) if len(st): y = depth[st[-1]] if y[0] < x[0] + 1: y[1], y[0] = y[0], x[0] + 1 elif y[1] < x[0] + 1: y[1] = x[0] + 1 continue i = path[st[-1]].pop() path[i].remove(st[-1]) st.append(i) return ans def road(a,b,path,com): curr = deque([a]) visi = {a} cou,inc,tar = 0,0,1 while len(curr): x = curr.popleft() inc += 1 for i in path[x]: if i not in visi: visi.add(i) curr.append(i) if inc == tar: tar,inc = len(curr),0 cou += 1 if cou > com and b not in visi: return False if cou > com and b in visi: return True def main(): for _ in range(int(input())): n,a,b,da,db = map(int,input().split()) path = defaultdict(set) for _ in range(n-1): u,v = map(int,input().split()) path[u].add(v) path[v].add(u) path1 = deepcopy(path) d = longest_path(path,n) x = road(a,b,path1,da) if min(d,db) > 2*da and not x: print('Bob') else: print('Alice') #Fast IO Region BUFSIZE = 8192 class FastIO(IOBase): newlines = 0 def __init__(self, file): self._fd = file.fileno() self.buffer = BytesIO() self.writable = "x" in file.mode or "r" not in file.mode self.write = self.buffer.write if self.writable else None def read(self): while True: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) if not b: break ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines = 0 return self.buffer.read() def readline(self): while self.newlines == 0: b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE)) self.newlines = b.count(b"\n") + (not b) ptr = self.buffer.tell() self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr) self.newlines -= 1 return self.buffer.readline() def flush(self): if self.writable: os.write(self._fd, self.buffer.getvalue()) self.buffer.truncate(0), self.buffer.seek(0) class IOWrapper(IOBase): def __init__(self, file): self.buffer = FastIO(file) self.flush = self.buffer.flush self.writable = self.buffer.writable self.write = lambda s: self.buffer.write(s.encode("ascii")) self.read = lambda: self.buffer.read().decode("ascii") self.readline = lambda: self.buffer.readline().decode("ascii") sys.stdin, sys.stdout = IOWrapper(sys.stdin), IOWrapper(sys.stdout) input = lambda: sys.stdin.readline().rstrip("\r\n") if __name__ == '__main__': main() ```
instruction
0
67,481
13
134,962
No
output
1
67,481
13
134,963
Provide tags and a correct Python 3 solution for this coding contest problem. For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way: * Consider a graph on k nodes, with numbers from b_1 to b_k written on them. * For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j, where ⊕ denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph. * We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. You can find an example below (the picture corresponding to the first test case). Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5. However, sequence (0, 1, 5, 2) is good. <image> You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal? It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good. Input The first line contains a single integer n (2 ≤ n ≤ 200,000) — length of the sequence. The second line contains n distinct non-negative integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — the elements of the sequence. Output You should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good. Examples Input 5 0 1 5 2 6 Output 1 Input 7 6 9 8 7 3 5 2 Output 2 Note Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good. It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
instruction
0
67,498
13
134,996
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees Correct Solution: ``` import sys try:sys.stdin,sys.stdout=open('in.txt','r'),open('out.txt','w') except:pass ii1=lambda:int(sys.stdin.readline().strip()) # for interger is1=lambda:sys.stdin.readline().strip() # for str iia=lambda:list(map(int,sys.stdin.readline().strip().split())) # for List[int] isa=lambda:sys.stdin.readline().strip().split() # for List[str] mod=int(1e9 + 7);from collections import *;from math import * ###################### Start Here ###################### n = ii1() arr = iia() arr.sort() def dfs(arr): if len(arr) == 1: return 1 k = 1 << int(log2(arr[0] ^ arr[-1])) for i, a in enumerate(arr): if a & k: break return 1 + max(dfs(arr[:i]), dfs(arr[i:])) print(n - dfs(arr)) ```
output
1
67,498
13
134,997
Provide tags and a correct Python 3 solution for this coding contest problem. For a given sequence of distinct non-negative integers (b_1, b_2, ..., b_k) we determine if it is good in the following way: * Consider a graph on k nodes, with numbers from b_1 to b_k written on them. * For every i from 1 to k: find such j (1 ≤ j ≤ k, j≠ i), for which (b_i ⊕ b_j) is the smallest among all such j, where ⊕ denotes the operation of bitwise XOR (<https://en.wikipedia.org/wiki/Bitwise_operation#XOR>). Next, draw an undirected edge between vertices with numbers b_i and b_j in this graph. * We say that the sequence is good if and only if the resulting graph forms a tree (is connected and doesn't have any simple cycles). It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once. You can find an example below (the picture corresponding to the first test case). Sequence (0, 1, 5, 2, 6) is not good as we cannot reach 1 from 5. However, sequence (0, 1, 5, 2) is good. <image> You are given a sequence (a_1, a_2, ..., a_n) of distinct non-negative integers. You would like to remove some of the elements (possibly none) to make the remaining sequence good. What is the minimum possible number of removals required to achieve this goal? It can be shown that for any sequence, we can remove some number of elements, leaving at least 2, so that the remaining sequence is good. Input The first line contains a single integer n (2 ≤ n ≤ 200,000) — length of the sequence. The second line contains n distinct non-negative integers a_1, a_2, …, a_n (0 ≤ a_i ≤ 10^9) — the elements of the sequence. Output You should output exactly one integer — the minimum possible number of elements to remove in order to make the remaining sequence good. Examples Input 5 0 1 5 2 6 Output 1 Input 7 6 9 8 7 3 5 2 Output 2 Note Note that numbers which you remove don't impact the procedure of telling whether the resulting sequence is good. It is possible that for some numbers b_i and b_j, you will try to add the edge between them twice. Nevertheless, you will add this edge only once.
instruction
0
67,499
13
134,998
Tags: binary search, bitmasks, data structures, divide and conquer, dp, trees Correct Solution: ``` import math n = int(input()) A = list(map(int, input().split())) A.sort() def dfs(A): if len(A) == 1: return 1 k = 1 << int(math.log2(A[0] ^ A[-1])) for i, a in enumerate(A): if a & k: break return 1 + max(dfs(A[:i]), dfs(A[i:])) print(n - dfs(A)) ```
output
1
67,499
13
134,999