message
stringlengths
2
22.8k
message_type
stringclasses
2 values
message_id
int64
0
1
conversation_id
int64
16
109k
cluster
float64
1
1
__index_level_0__
int64
32
217k
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` from heapq import heappush, heappop N,Q,*L = map(int, open(0).read().split()) D = L[3*N:] ls = [] for i in range(N): s,t,x = L[3*i],L[3*i+1],L[3*i+2] ls.append((s-x,1,x)) ls.append((t-x,0,x)) for i,d in enumerate(D): ls.append((d,2,i)) ls.sort() ans = [0]*Q S = set() hq = [] for a,b,c in ls: if b==0: S.remove(c) elif b==1: S.add(c) heappush(hq,c) else: while hq and hq[0] not in S: heappop(hq) ans[c] = hq[0] if hq else -1 print('\n'.join(map(str,ans))) ```
instruction
0
51,115
1
102,230
Yes
output
1
51,115
1
102,231
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` import sys input = sys.stdin.readline from heapq import * N, Q = map(int, input().split()) X = [] for _ in range(N): s, t, x = map(int, input().split()) X.append((s-x,t-x,x)) X = sorted(X, key = lambda x: x[0]) D = [int(input()) for _ in range(Q)] i = 0 j = 0 A = [] B = [] C = [] for q in range(Q): while i < len(X) and D[q] >= X[i][0]: a, b, x = X[i] heappush(A, (x, b)) heappush(B, (b, x)) i += 1 while len(B) and B[0][0] <= D[q]: b, x = heappop(B) heappush(C, (x, b)) while len(C) and len(A) and C[0][0] == A[0][0]: heappop(A) heappop(C) print(A[0][0] if A else -1) ```
instruction
0
51,116
1
102,232
Yes
output
1
51,116
1
102,233
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` import sys input = sys.stdin.readline n,Q=map(int,input().split()) b_num = 2**(n-1).bit_length() mx = 10**9 segl=[mx]*2*b_num def update(k, x): k += b_num-1 segl[k] = x while k+1: k = (k-1)//2 segl[k] = min(segl[k*2+1],segl[k*2+2]) if __name__ == '__main__': xs = [] for i in range(n): s,t,x=map(int,input().split()) xs += [(s-x,True,x,i), (t-x,False,x,i)] qs = [] for _ in range(Q): qs.append(int(input())) xs.sort(key=lambda x:x[0]) j = 0 for x in xs: while Q-j and qs[j] < x[0]: print(segl[0] if segl[0]!= mx else -1) j += 1 update(x[3], x[2] if x[1] else mx) while Q-j: print(-1) j+=1 ```
instruction
0
51,117
1
102,234
Yes
output
1
51,117
1
102,235
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` import sys from bisect import bisect_left N,Q = map(int, input().split()) STX = [None] * N for i in range(N): s,t,x = map(int, input().split()) STX[i] = [x,s,t] STX.sort() Dn = [None] * (Q+1) for i in range(Q): Dn[i] = int(input()) Dn[Q] = 10**10 ans = [-1] * Q skip = [-1] * Q for x, s, t in STX: ss = bisect_left(Dn, s - x) tt = bisect_left(Dn, t - x) while ss < tt: sk = skip[ss] if sk == -1: ans[ss] = x skip[ss] = tt ss += 1 else: ss = sk print('\n'.join(map(str, ans))) ```
instruction
0
51,118
1
102,236
Yes
output
1
51,118
1
102,237
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` from collections import defaultdict N, Q = map(int, input().split()) STX = [] for i in range(N): S, T, X = map(int, input().split()) STX.append([S, T, X]) out = defaultdict(lambda: -1) for out_num, (S, T, X) in enumerate(STX): for i in range(max(S-X, 0), max(T-X, 1)): if out[i] != -1: if out[i] > X: out[i] = X else: out[i] = X for i in range(Q): print(out[int(input())]) ```
instruction
0
51,119
1
102,238
No
output
1
51,119
1
102,239
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` import sys from operator import itemgetter inputs = sys.stdin.readline N, Q= map(int,inputs().split()) def main(): E = [None]*2*N for n in range(N): a,b,c = map(int,inputs().split()) E[2*n] = (a - c, 1, c) E[2*n + 1] = (b - c, -1, c) E.sort(key=itemgetter(0)) tuple(tuple(E)) mini = 1000000001 kouho = {1000000001} my_add = kouho.add my_discard = kouho.discard q = 0 d = int(inputs()) flag = False cont = False for e in E: while(e[0] > d): if cont == True: if mini < 1000000001: print(mini) else: print(-1) else: mini = min(kouho) if mini < 1000000001: print(mini) else: print(-1) cont = True if q < Q-1: q = q + 1 d = int(inputs()) else: flag = True q = q + 1 break if flag == True: break if e[1] == 1: my_add(e[2]) if mini > e[2]: mini = e[2] elif e[1] == -1: my_discard(e[2]) cont = False for t in [None]*(Q-q): print(-1) def sub(): V = [list(map(int,inputs().split())) for p in [0]*N] M = [int(inputs()) for p in [0]*Q] V.sort(key = lambda x:(x[2],x[0],x[1])) for v in V: v[0] -= v[2] v[1] -= v[2] + 1 for m in M: for n in range(N): if V[n][0] <=m and m <= V[n][1]: print(V[n][2]) break else: print(-1) if N>500000: sub() else: main() ```
instruction
0
51,120
1
102,240
No
output
1
51,120
1
102,241
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` N, Q = list(map(int, input().split())) STX=[] D=[] for i in range(N): STX.append(list(map(int, input().split()))) STX.sort(key=lambda x: x[0]) kensaku = dict() for i in range(Q): D.append(int(input())) kensaku[D[-1]] = i dist = [10000000000000 for i in range(Q)] for i in range(N): s = STX[i][0] - STX[i][2] t = STX[i][1] - STX[i][2] - 1 a = bisect.bisect_left(D, s) b = bisect.bisect_right(D, t) #print(D) for j in range(a, b): dist[kensaku[D[j]]] = min(dist[kensaku[D[j]]], STX[i][2]) del D[a:b] for i in range(Q): if dist[i] > 100000000000: print(-1) else: print(dist[i]) ```
instruction
0
51,121
1
102,242
No
output
1
51,121
1
102,243
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There is an infinitely long street that runs west to east, which we consider as a number line. There are N roadworks scheduled on this street. The i-th roadwork blocks the point at coordinate X_i from time S_i - 0.5 to time T_i - 0.5. Q people are standing at coordinate 0. The i-th person will start the coordinate 0 at time D_i, continue to walk with speed 1 in the positive direction and stop walking when reaching a blocked point. Find the distance each of the Q people will walk. Constraints * All values in input are integers. * 1 \leq N, Q \leq 2 \times 10^5 * 0 \leq S_i < T_i \leq 10^9 * 1 \leq X_i \leq 10^9 * 0 \leq D_1 < D_2 < ... < D_Q \leq 10^9 * If i \neq j and X_i = X_j, the intervals [S_i, T_i) and [S_j, T_j) do not overlap. Input Input is given from Standard Input in the following format: N Q S_1 T_1 X_1 : S_N T_N X_N D_1 : D_Q Output Print Q lines. The i-th line should contain the distance the i-th person will walk or -1 if that person walks forever. Example Input 4 6 1 3 2 7 13 10 18 20 13 3 4 2 0 1 2 3 5 8 Output 2 2 10 -1 13 -1 Submitted Solution: ``` def update(l, r, v): L = l + N0; R = r + N0 while L < R: if R & 1: R -= 1 data[R-1] = v if L & 1: data[L-1] = v L += 1 L >>= 1; R >>= 1 # a_iの現在の値を取得 def _query(k): k += N0-1 s = INF while k >= 0: if data[k]: s = max(s, data[k]) k = (k - 1) // 2 return s # これを呼び出す def query(k): return _query(k)[1] from bisect import bisect_left if __name__ == '__main__': n, q = map(int, input().split()) stx = [list(map(int, input().split())) for _ in range(n)] l = [int(input()) for _ in range(q)] INF = (-1, 2**31-1) N = len(l) N0 = 2**(N-1).bit_length() data = [None]*(2*N0) stx.sort(key=lambda x:x[2], reverse=True) for i, (s, t, x) in enumerate(stx): i1 = bisect_left(l, s - 0.5 - x) i2 = bisect_left(l, t - 0.5 - x) update(i1, i2, (i, x)) for i in range(q): tmp = query(i) if tmp == INF[1]: print(-1) else: print(tmp) ```
instruction
0
51,122
1
102,244
No
output
1
51,122
1
102,245
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,655
1
103,310
Tags: dfs and similar, graphs Correct Solution: ``` n,r,r1 = map(int,input().split()) capt,ind= [0]*(n+1),1;ig= r1; capt[0] = r for u,v in enumerate(map(int,input().split())): ind += (u+1==r); capt[ind] = v; ind+=1 r0 = capt[r1] while 1: temp = capt[r0] if temp == r1: break capt[r0] = r1; r1 = r0; r0 = temp for x in range(1,n+1): if x!=ig: print(capt[x], end = " ") ```
output
1
51,655
1
103,311
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,656
1
103,312
Tags: dfs and similar, graphs Correct Solution: ``` def put(): return map(int, input().split()) def dfs(r1, r2): p = -1 curr = r2 while p!=r1: tmp = parent[curr] parent[curr]=p p = curr curr = tmp n,r1,r2 = put() parent = [0] parent.extend(list(put())) parent.insert(r1, -1) dfs(r1,r2) parent.remove(0) parent.remove(-1) print(*parent) ```
output
1
51,656
1
103,313
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,657
1
103,314
Tags: dfs and similar, graphs Correct Solution: ``` n, r1, r2 = map(int, input().split()) def dfs(u): x = None while x != r1: tmp = prev[u] prev[u] = x x = u u = tmp prev = [0] + list(map(int, input().split())) prev.insert(r1, None) dfs(r2) prev.remove(0) prev.remove(None) print(*prev) ```
output
1
51,657
1
103,315
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,658
1
103,316
Tags: dfs and similar, graphs Correct Solution: ``` import os import sys # from io import BytesIO, IOBase # 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") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 import threading threading.stack_size(10**8) from types import GeneratorType def bootstrap(func, stack=[]): def wrapped_function(*args, **kwargs): if stack: return func(*args, **kwargs) else: call = func(*args, **kwargs) while True: if type(call) is GeneratorType: stack.append(call) call = next(call) else: stack.pop() if not stack: break call = stack[-1].send(call) return call return wrapped_function Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def solve(): n,r1,r2 = Ri();r1-=1;r2-=1 g = [ [] for i in range(n)] temp = Ri() temp = [i-1 for i in temp] ans = 0 for i in range(n): if i == r1: ans+=1;continue g[i].append(temp[i-ans]);g[temp[i-ans]].append(i) ans = [0]*n @bootstrap def dfs(cur, par): for child in g[cur]: if child == par : continue ans[child] = cur+1 yield dfs(child, cur) yield dfs(r2, -1) for i in range(len(ans)): if ans[i] == 0: ans = ans[:i]+ans[i+1:] break for i in ans: print(i, end= " ") print() solve() ```
output
1
51,658
1
103,317
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,659
1
103,318
Tags: dfs and similar, graphs Correct Solution: ``` n,r1,r2=list(map(int,input().split())) p=list(map(int,input().split())) a=[0]*n for i in range(n-1): a[i+int(i>=r1-1)]=p[i] s=[r2] v=r2 while v!=r1: s.append(a[v-1]) v=a[v-1] for i in range(1,len(s)): a[s[i]-1]=s[i-1] print(*a[:r2-1]+a[r2:]) ```
output
1
51,659
1
103,319
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,660
1
103,320
Tags: dfs and similar, graphs Correct Solution: ``` def findPath(fr, to, parent): path = [to] current = to while current != fr: path.append(parent[current]) current = parent[current] return path n, r1, r2 = map(int, input().split()) idx = lambda i: i if i < r1 else i + 1 oldParents = dict((idx(i + 1), int(city)) for i, city in enumerate(input().split())) oldParents[r1] = r1 path = findPath(r1, r2, oldParents) newParents = oldParents for i in range(1, len(path)): newParents[path[i]] = path[i-1] for i in range(1, n + 1): if i != r2: print(newParents[i], end=' ') # Made By Mostafa_Khaled ```
output
1
51,660
1
103,321
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,661
1
103,322
Tags: dfs and similar, graphs Correct Solution: ``` import sys sys.setrecursionlimit(100000) n, r1, r2 = map(int, input().split()) a = list(map(int, input().split())) g = {} num = 0 for k, v in enumerate(a): num += 1 if num == r1: num += 1 # print(k, num, v) if num not in g: g[num] = [] g[num].append(v) if v not in g: g[v] = [] g[v].append(num) # print(g) b = [0] * (n + 1) visited = set() def visit(cur, parent): visited.add(cur) b[cur] = parent for child in g[cur]: if child not in visited: visit(child, cur) from collections import deque q = deque() q.append((r2, 0)) while q: cur, parent = q.popleft() if cur not in visited: visited.add(cur) b[cur] = parent for child in g[cur]: q.append((child, cur)) b2 = [b[k] for k in range(n + 1) if k > 0 and k != r2] # print(b) print(*b2) """ # """ # from random import randint # # a = [1, 3, 2, 4, 5, 100, 6, 8, 9, 13, 19, 34, 10, 23, 65, 40, 63, 45, 16, 97, 30, 17, 7, 67, 82, 11, 81, 22, 61, 57, 41, 66, 73, 52, 50, 15, 58, 72, 53, 88, 87, 93, 56, 98, 29, 76, 26, 99, 85, 42, 33, 18, 49, 83, 71, 14, 46, 20, 70, 86, 25, 74, 27, 94, 28, 0, 80, 92] # # for k in range(100): # # a.append(randint(0, 100)) # # d = {} # b = [] # for k, v in enumerate(a): # new = False # if v not in d: # d[v] = 0 # new = True # # last = 0 # for p in range(len(b) - 1, -1, -1): # val = b[p] # if last < val <= v: # if val > d[v]: # d[v] = val # last = val # if new: # b.append(v) # # print(len(b)) # # # b = [] # # ar = [] # # # # for k, v in enumerate(a): # # lb = len(b) # # last = 0 # # for k2 in range(lb): # # arr = b[k2] # # val = arr[-1] # # if last < val <= v: # # arr2 = arr[::] # # arr.append(v) # # b.append(arr2) # # last = val # # if len(arr) > len(ar): # # ar = arr # # # # if len(b) == lb: # # b.append([v]) # # # # print(len(b)) # # b.sort(key=lambda x: len(x)) # # for row in b: # # print(row) # # print('--') # # print(ar) # # # def var(s, c): # # if c == 0: # # for k in range(10): # # s1 = str(s) + str(k) # # print(s1) # # else: # # for k in range(10): # # s1 = str(s) + str(k) # # var(s1, c - 1) # # # # # # def var0(): # # for k in range(10): # # var(k, 3) # # # # # # var0() ```
output
1
51,661
1
103,323
Provide tags and a correct Python 3 solution for this coding contest problem. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2
instruction
0
51,662
1
103,324
Tags: dfs and similar, graphs Correct Solution: ``` import sys input=sys.stdin.readline n,r1,r2=map(int,input().split()) r1-=1;r2-=1 p=list(map(int,input().split())) g=[[] for i in range(n)] c=0 for i in range(n-1): if i==r1: c+=1 g[i+c].append(p[i]-1) g[p[i]-1].append(i+c) pre=[-1]*n q=[[-1,r2]] pre[r2]=r2 while q: par,ver=q.pop() for to in g[ver]: if par!=to: pre[to]=ver q.append([ver,to]) ans=[] for i in range(n): if pre[i]!=i: ans.append(pre[i]+1) print(*ans) ```
output
1
51,662
1
103,325
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` import sys from array import array # noqa: F401 def input(): return sys.stdin.buffer.readline().decode('utf-8') n, r1, r2 = map(int, input().split()) adj = [[] for _ in range(n + 1)] v = 1 for u in map(int, input().split()): if v == r1: v += 1 adj[v].append(u) adj[u].append(v) v += 1 ans = [0] * (n + 1) ans[r2] = -1 stack = [r2] while stack: v = stack.pop() for dest in adj[v]: if ans[dest] != 0: continue ans[dest] = v stack.append(dest) ans = [x for x in ans if x > 0] print(*ans) ```
instruction
0
51,663
1
103,326
Yes
output
1
51,663
1
103,327
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` import sys from math import gcd,sqrt from collections import defaultdict,Counter,deque import math # input=sys.stdin.readline # def print(x): # sys.stdout.write(str(x)+"\n") # sys.stdout=open("CP1/output.txt",'w') # sys.stdin=open("CP1/input.txt",'r') import os import sys from io import BytesIO, IOBase 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") def get_sum(bit,i): s = 0 i+=1 while i>0: s+=bit[i] i-=i&(-i) return s def update(bit,n,i,v): i+=1 while i<=n: bit[i]+=v i+=i&(-i) def modInverse(b,m): g = math.gcd(b, m) if (g != 1): return -1 else: return pow(b, m - 2, m) n,r1,r2 = map(int,input().split()) l = [0]+list(map(int,input().split())) hash = defaultdict(list) cur = 1 i = 1 ans = [0]*(n) def bfs(n,tot): boo = defaultdict(bool) queue = [n] par = [0]*(tot+1) boo[n] = True while queue: z = queue.pop(0) for i in hash[z]: if not boo[i]: queue.append(i) par[i] = z boo[i] = True # print(par[:(n)] + par[n+1:]) return par[:(n)] + par[n+1:] while i<len(l): # print(i) if cur == r1: cur+=1 else: hash[cur].append(l[i]) hash[l[i]].append(cur) i+=1 cur+=1 ans = bfs(r2,n) print(*ans[1:]) ```
instruction
0
51,664
1
103,328
Yes
output
1
51,664
1
103,329
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` import sys sys.setrecursionlimit(100000) n, r1, r2 = map(int, input().split()) a = list(map(int, input().split())) g = {} num = 0 for k, v in enumerate(a): num += 1 if num == r1: num += 1 # print(k, num, v) if num not in g: g[num] = [] g[num].append(v) if v not in g: g[v] = [] g[v].append(num) # print(g) b = [0] * (n + 1) visited = set() def visit(cur, parent): visited.add(cur) b[cur] = parent for child in g[cur]: if child not in visited: visit(child, cur) from collections import deque q = deque() q.append((r2, 0)) while q: cur, parent = q.popleft() if cur not in visited: visited.add(cur) b[cur] = parent for child in g[cur]: q.append((child, cur)) b2 = [b[k] for k in range(n + 1) if k > 0 and k != r2] # print(b) print(*b2) """ """ # from random import randint # # a = [1, 3, 2, 4, 5, 100, 6, 8, 9, 13, 19, 34, 10, 23, 65, 40, 63, 45, 16, 97, 30, 17, 7, 67, 82, 11, 81, 22, 61, 57, 41, 66, 73, 52, 50, 15, 58, 72, 53, 88, 87, 93, 56, 98, 29, 76, 26, 99, 85, 42, 33, 18, 49, 83, 71, 14, 46, 20, 70, 86, 25, 74, 27, 94, 28, 0, 80, 92] # # for k in range(100): # # a.append(randint(0, 100)) # # d = {} # b = [] # for k, v in enumerate(a): # new = False # if v not in d: # d[v] = 0 # new = True # # last = 0 # for p in range(len(b) - 1, -1, -1): # val = b[p] # if last < val <= v: # if val > d[v]: # d[v] = val # last = val # if new: # b.append(v) # # print(len(b)) # # # b = [] # # ar = [] # # # # for k, v in enumerate(a): # # lb = len(b) # # last = 0 # # for k2 in range(lb): # # arr = b[k2] # # val = arr[-1] # # if last < val <= v: # # arr2 = arr[::] # # arr.append(v) # # b.append(arr2) # # last = val # # if len(arr) > len(ar): # # ar = arr # # # # if len(b) == lb: # # b.append([v]) # # # # print(len(b)) # # b.sort(key=lambda x: len(x)) # # for row in b: # # print(row) # # print('--') # # print(ar) # # # def var(s, c): # # if c == 0: # # for k in range(10): # # s1 = str(s) + str(k) # # print(s1) # # else: # # for k in range(10): # # s1 = str(s) + str(k) # # var(s1, c - 1) # # # # # # def var0(): # # for k in range(10): # # var(k, 3) # # # # # # var0() ```
instruction
0
51,665
1
103,330
Yes
output
1
51,665
1
103,331
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` n, ro, rk = map(int, input().split()) t = [0] + list(map(int, input().split())) t.insert(ro, 0) r, p = [], rk while p: r.append(p) p = t[p] for i in range(1, len(r)): t[r[i]] = r[i - 1] t.pop(rk) print(' '.join(map(str, t[1: ]))) ```
instruction
0
51,666
1
103,332
Yes
output
1
51,666
1
103,333
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` import os import sys from io import BytesIO, IOBase 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") def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 import threading threading.stack_size(10**8) Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def solve(): n,r1,r2 = Ri();r1-=1;r2-=1 g = [ [] for i in range(n)] temp = Ri() temp = [i-1 for i in temp] ans = 0 for i in range(n): if i == r1: ans+=1;continue # print(i-ans) g[i].append(temp[i-ans]);g[temp[i-ans]].append(i) ans = [0]*n def dfs(cur, par): for child in g[cur]: if child == par : continue ans[child] = cur+1 dfs(child, cur) dfs(r2, -1) for i in range(len(ans)): if ans[i] == 0: ans = ans[:i]+ans[i+1:] break print(*ans) threading.Thread(target= solve).start() ```
instruction
0
51,667
1
103,334
No
output
1
51,667
1
103,335
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` def dfs(v1,visited,parent): global d,p2 if v1==p2: return parent visited[v1] = True for i in d[v1]: if visited[i]==False: dfshelper(i,visited,v1) from collections import defaultdict n,p1,p2 = [int(i) for i in input().split()] arr = [0]*(n+1) a = [int(i) for i in input().split()] d= defaultdict(list) visited = [False]*(n+1) visited[p2]=True out = [-1]*(n+1) c =1 i = 0 flag=0 for i in range(n): if i+1==p1: flag =1 pass else: j = i if flag==1: j-=1 out[i+1] = a[j] d[i+1].append(a[j]) d[a[j]].append(i+1) #print(out) for i in d[p2]: out[i]=p2 out[p1] = dfs(p2,visited,p2) out[p2]=-1 for i in range(1,n+1): if out[i]!=-1: print(out[i],end=' ') ```
instruction
0
51,668
1
103,336
No
output
1
51,668
1
103,337
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` n,old,new = tuple(map(int,input().split())) p = list(map(int,input().split())) route = {} for i in range(1,n+1): if i != old: nei = p.pop(0) if nei not in route: route[nei] = [i] else: route[nei].append(i) if i not in route: route[i] = [nei] else: route[i].append(nei) ans = {} def trackallroute(x,pre): if len(route[x]) == 1: return for e in route[x]: if e != pre: ans[e] = x trackallroute(e,x) trackallroute(new,-1) final = '' ans = sorted(ans.items()) for e in ans: final += str(e[1])+' ' print(final) ```
instruction
0
51,669
1
103,338
No
output
1
51,669
1
103,339
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. There are n cities in Berland. Each city has its index — an integer number from 1 to n. The capital has index r1. All the roads in Berland are two-way. The road system is such that there is exactly one path from the capital to each city, i.e. the road map looks like a tree. In Berland's chronicles the road map is kept in the following way: for each city i, different from the capital, there is kept number pi — index of the last city on the way from the capital to i. Once the king of Berland Berl XXXIV decided to move the capital from city r1 to city r2. Naturally, after this the old representation of the road map in Berland's chronicles became incorrect. Please, help the king find out a new representation of the road map in the way described above. Input The first line contains three space-separated integers n, r1, r2 (2 ≤ n ≤ 5·104, 1 ≤ r1 ≠ r2 ≤ n) — amount of cities in Berland, index of the old capital and index of the new one, correspondingly. The following line contains n - 1 space-separated integers — the old representation of the road map. For each city, apart from r1, there is given integer pi — index of the last city on the way from the capital to city i. All the cities are described in order of increasing indexes. Output Output n - 1 numbers — new representation of the road map in the same format. Examples Input 3 2 3 2 2 Output 2 3 Input 6 2 4 6 1 2 4 2 Output 6 4 1 4 2 Submitted Solution: ``` from sys import setrecursionlimit import threading setrecursionlimit(10 ** 9) threading.stack_size(67108864) def dfs(u, fr): global al, parent for i in al[u]: if i != fr: parent[i] = u dfs(i, u) def main(): n, r1, r2 = [int(i) for i in input().split()] r1 -= 1 r2 -= 1 p = [int(i) for i in input().split()] al = [[] for i in range(n)] for i in range(n - 1): if i >= r1: al[i + 1].append(p[i] - 1) al[p[i] - 1].append(i + 1) else: al[i].append(p[i] - 1) al[p[i] - 1].append(i) parent = [-1] * n dfs(r2, -1) print(" ".join([str(i + 1) for i in parent if i != -1])) thread = threading.Thread(target=main) thread.start() ```
instruction
0
51,670
1
103,340
No
output
1
51,670
1
103,341
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,708
1
103,416
Tags: constructive algorithms Correct Solution: ``` def main(): t = int(input()) l = 1 r = t while l < r: print(f'{l} {r}', end=' ') l += 1 r -= 1 else: if l == r: print(f'{l}') main() ```
output
1
51,708
1
103,417
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,709
1
103,418
Tags: constructive algorithms Correct Solution: ``` n = int(input()) for i in range(1, n + 1): if i < n - i + 1: print(i, n - i + 1) else: if n % 2 != 0: print(i) break ```
output
1
51,709
1
103,419
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,710
1
103,420
Tags: constructive algorithms Correct Solution: ``` n=int(input()) ans=[0]*n l=1 r=n i=0 while i<n: if i%2==0: ans[i]=l l=l+1 else: ans[i]=r r=r-1 i=i+1 for i in ans: print(i,end=" ") ```
output
1
51,710
1
103,421
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,711
1
103,422
Tags: constructive algorithms Correct Solution: ``` n=int(input()) arr=[None]*n low=1 top=n for i in range(n): if i%2==0: print(low,end=' ') low+=1 else: print(top,end=' ') top-=1 ```
output
1
51,711
1
103,423
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,712
1
103,424
Tags: constructive algorithms Correct Solution: ``` n=int(input()) l=1 r=n x=0 ans=[] while l<=r: if x%2!=0: ans.append(r) r-=1 else: ans.append(l) l+=1 x+=1 print(*ans) ```
output
1
51,712
1
103,425
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,713
1
103,426
Tags: constructive algorithms Correct Solution: ``` import sys from math import log2,floor,ceil,sqrt # import bisect # from collections import deque Ri = lambda : [int(x) for x in sys.stdin.readline().split()] ri = lambda : sys.stdin.readline().strip() def input(): return sys.stdin.readline().strip() def list2d(a, b, c): return [[c] * b for i in range(a)] def list3d(a, b, c, d): return [[[d] * c for j in range(b)] for i in range(a)] def list4d(a, b, c, d, e): return [[[[e] * d for j in range(c)] for j in range(b)] for i in range(a)] def ceil(x, y=1): return int(-(-x // y)) def INT(): return int(input()) def MAP(): return map(int, input().split()) def LIST(N=None): return list(MAP()) if N is None else [INT() for i in range(N)] def Yes(): print('Yes') def No(): print('No') def YES(): print('YES') def NO(): print('NO') INF = 10 ** 18 MOD = 10**9+7 n = int(ri()) l = 1 r= n if n == 1: print(1) else: arr = [l,r] turn = 0 l+=1 r-=1 while l <= r: if turn == 1: arr.append(r) r-=1 else: arr.append(l) l+=1 turn^=1 print(*arr) ```
output
1
51,713
1
103,427
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,714
1
103,428
Tags: constructive algorithms Correct Solution: ``` # import atexit # import io # import sys # # _INPUT_LINES = sys.stdin.read().splitlines() # input = iter(_INPUT_LINES).__next__ # _OUTPUT_BUFFER = io.StringIO() # sys.stdout = _OUTPUT_BUFFER # # # @atexit.register # def write(): # sys.__stdout__.write(_OUTPUT_BUFFER.getvalue()) n = int(input()) res = [] isLeft = True for _ in range(n): if isLeft: res.append(_ // 2 + 1) isLeft = False else: res.append(n - _ // 2) isLeft = True print(*res) ```
output
1
51,714
1
103,429
Provide tags and a correct Python 3 solution for this coding contest problem. Once upon a time a little frog whose name was Vasya decided to travel around his home swamp. Overall there are n mounds on the swamp, located on one line. The distance between the neighboring mounds is one meter. Vasya wants to visit all the mounds in one day; besides, he wants to visit each one exactly once. For that he makes a route plan, to decide the order in which to jump on the mounds. Vasya can pick any mound as the first one. He thinks it boring to jump two times at the same distance. That's why he wants any two jumps on his route to have different lengths. Help Vasya the Frog and make the plan for him. Input The single line contains a number n (1 ≤ n ≤ 104) which is the number of mounds. Output Print n integers pi (1 ≤ pi ≤ n) which are the frog's route plan. * All the pi's should be mutually different. * All the |pi–pi + 1|'s should be mutually different (1 ≤ i ≤ n - 1). If there are several solutions, output any. Examples Input 2 Output 1 2 Input 3 Output 1 3 2
instruction
0
51,715
1
103,430
Tags: constructive algorithms Correct Solution: ``` n = int(input()) x = 1 y = n while 1: if x > n // 2: if n % 2: print(x) break print(x, y, end = " ") x += 1 y -= 1 ```
output
1
51,715
1
103,431
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,724
1
103,448
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` from heapq import * import sys MOD1 = 1000000007 MOD2 = 1000000123 def addM(a,b): return ((a[0]+b[0])%MOD1,(a[1]+b[1])%MOD2) def mulM(a,b): return ((a[0]*b[0])%MOD1,(a[1]*b[1])%MOD2) def dijk(adj,n,s): dist = [10**18]*n ways = [(0,0)]*n frontier = [] dist[s] = 0 ways[s] = (1,1) heappush(frontier,(0,s)) while (len(frontier)>0): x = heappop(frontier) if x[0]!=dist[x[1]]: continue x = x[1] for (i,l) in adj[x]: if dist[x]+l<dist[i]: dist[i] = dist[x]+l ways[i] = ways[x] heappush(frontier,(dist[i],i)) elif dist[x]+l==dist[i]: ways[i] = addM(ways[i],ways[x]) return (dist,ways) n,m,s,t = map(int,sys.stdin.readline().split()) s-=1 t-=1 adj = [[] for i in range(n)] jda = [[] for i in range(n)] edges = [] for i in range(m): a,b,l = map(int,sys.stdin.readline().split()) a-=1 b-=1 adj[a].append((b,l)) jda[b].append((a,l)) edges.append((a,b,l)) one = dijk(adj,n,s) two = dijk(jda,n,t) for i in edges: if one[0][i[0]]+i[2]+two[0][i[1]]==one[0][t] and mulM(one[1][i[0]],two[1][i[1]])==one[1][t]: sys.stdout.write("YES\n") else: x = one[0][t]-1-one[0][i[0]]-two[0][i[1]] if x<=0: sys.stdout.write("NO\n") else: sys.stdout.write("CAN "+str(i[2]-x)+"\n") ```
output
1
51,724
1
103,449
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,725
1
103,450
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` from heapq import * from collections import defaultdict def D(v,g): h,p,o=[],defaultdict(lambda:1e99),[] heappush(h,(0,v)) while h: l,w=heappop(h) if w in p:continue p[w]=l o.append(w) for u,L in g[w]: heappush(h,(L+l,u)) return p,o n,m,s,t=map(int,input().split()) r=[] g={i+1:[] for i in range(n)} G={i+1:[] for i in range(n)} for _ in range(m): a,b,l=map(int,input().split()) r.append((a,b,l)) g[a].append((b,l)) G[b].append((a,l)) S,o=D(s,g) T,_=D(t,G) L=S[t] H={v:[w for w,l in e if S[v]+T[w]+l==L] for v,e in g.items()} B,A=set(),{s} for v in o: if not H[v]:continue if 1==len(A)==len(H[v]):B.add(v) A.update(H[v]) A.remove(v) print('\n'.join("YES" if a in B and S[a]+T[b]+l==L else "CAN "+str(S[a]+T[b]+l-L+1) if S[a]+T[b]+1<L else "NO" for a,b,l in r)) ```
output
1
51,725
1
103,451
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,726
1
103,452
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` from heapq import * import sys MOD = 1000000181 def addM(a,b): return (a+b)%MOD def mulM(a,b): return (a*b)%MOD def dijk(adj,n,s): dist = [10**18]*n ways = [0]*n frontier = [] dist[s] = 0 ways[s] = 1 heappush(frontier,(0,s)) while (len(frontier)>0): x = heappop(frontier) if x[0]!=dist[x[1]]: continue x = x[1] for (i,l) in adj[x]: if dist[x]+l<dist[i]: dist[i] = dist[x]+l ways[i] = ways[x] heappush(frontier,(dist[i],i)) elif dist[x]+l==dist[i]: ways[i] = addM(ways[i],ways[x]) return (dist,ways) n,m,s,t = map(int,sys.stdin.readline().split()) s-=1 t-=1 adj = [[] for i in range(n)] jda = [[] for i in range(n)] edges = [] for i in range(m): a,b,l = map(int,sys.stdin.readline().split()) a-=1 b-=1 adj[a].append((b,l)) jda[b].append((a,l)) edges.append((a,b,l)) one = dijk(adj,n,s) two = dijk(jda,n,t) for i in edges: if one[0][i[0]]+i[2]+two[0][i[1]]==one[0][t] and mulM(one[1][i[0]],two[1][i[1]])==one[1][t]: sys.stdout.write("YES\n") else: x = one[0][t]-1-one[0][i[0]]-two[0][i[1]] if x<=0: sys.stdout.write("NO\n") else: sys.stdout.write("CAN "+str(i[2]-x)+"\n") ```
output
1
51,726
1
103,453
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,727
1
103,454
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` #!/usr/bin/env python3 import heapq INF = int(1e18) MOD = (1 << 64) - 1 class MinHeap: def __init__(self): self.h = [] def push(self, x): heapq.heappush(self.h, x) def pop(self): return heapq.heappop(self.h) def isEmpty(self): return len(self.h) == 0 def add(x, y): return x + y - MOD if x + y >= MOD else x + y def mul(x, y): return x * y % MOD def go(adj, src): n = len(adj) frontier = MinHeap() ways = [0] * n cost = [INF] * n frontier.push((0, src)) ways[src] = 1 cost[src] = 0 while not frontier.isEmpty(): c, u = frontier.pop() if c > cost[u]: continue for v, w in adj[u]: if c + w < cost[v]: ways[v] = ways[u] cost[v] = c + w frontier.push((c + w, v)) elif c + w == cost[v]: ways[v] = add(ways[v], ways[u]) return cost, ways n, m, s, t = map(int, input().split()) s -= 1 t -= 1 adj = [[] for i in range(n)] adj_transpose = [[] for i in range(n)] edges = [] for i in range(m): u, v, w = map(int, input().split()) u -= 1 v -= 1 edges.append((u, v, w)) adj[u].append((v, w)) adj_transpose[v].append((u, w)) cost_s, ways_s = go(adj, s) cost_t, ways_t = go(adj_transpose, t) shortest_path = cost_s[t] for i in range(m): u, v, w = edges[i] cost = cost_s[u] + cost_t[v] + w if cost > shortest_path: fix_cost = cost - shortest_path + 1 w -= cost - shortest_path + 1 print(f"CAN {fix_cost}" if w >= 1 else "NO") else: if ways_s[t] == mul(ways_s[u], ways_t[v]): print("YES") else: print("CAN 1" if w > 1 else "NO") ```
output
1
51,727
1
103,455
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,728
1
103,456
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` import heapq def dijkstra(a, graph): shortestPaths = [None] * len(graph) priorityQueue = [] heapq.heappush(priorityQueue, (0, a)) while len(priorityQueue) != 0: length, endpoint = heapq.heappop(priorityQueue) if shortestPaths[endpoint] != None: continue shortestPaths[endpoint] = length for b, l, i in graph[endpoint]: if shortestPaths[b] != None: continue heapq.heappush(priorityQueue, (length + l, b)) return shortestPaths n, m, s, t = map(int, input().split()) s -= 1 t -= 1 roads = [] graph = [[] for _ in range(n)] backwardsGraph = [[] for _ in range(n)] for i in range(m): a, b, l = map(int, input().split()) a -= 1 b -= 1 roads.append((a, b, l, i)) graph[a].append((b, l, i)) backwardsGraph[b].append((a, l, i)) leftDijkstras = dijkstra(s, graph) rightDijkstras = dijkstra(t, backwardsGraph) answers = [None] * m events = [] for road in roads: a, b, l, i = road if leftDijkstras[a] == None or rightDijkstras[b] == None: continue pathTime = leftDijkstras[a] + rightDijkstras[b] + l if pathTime == leftDijkstras[t]: events.append((leftDijkstras[a], True, i)) events.append((leftDijkstras[b], False, i)) events.sort() edgeSet = set() niceEdges = [True] * m for event in events: if event[1] == True: edgeSet.add(event[2]) if len(edgeSet) > 1: niceEdges[event[2]] = False else: edgeSet.remove(event[2]) if len(edgeSet) != 0: niceEdges[event[2]] = False for road in roads: a, b, l, i = road if leftDijkstras[a] == None or rightDijkstras[b] == None: answers[i] = "NO" continue pathTime = leftDijkstras[a] + rightDijkstras[b] + l if pathTime == leftDijkstras[t] and niceEdges[i]: answers[i] = "YES" else: difference = pathTime - leftDijkstras[t] if l > difference + 1: answers[i] = "CAN " + str(difference + 1) else: answers[i] = "NO" for i in range(len(answers)): print(answers[i]) ```
output
1
51,728
1
103,457
Provide tags and a correct Python 3 solution for this coding contest problem. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6.
instruction
0
51,729
1
103,458
Tags: dfs and similar, graphs, hashing, shortest paths Correct Solution: ``` #!/usr/bin/env python3 import heapq INF = int(1e18) MOD = (1 << 32) - 1 class MinHeap: def __init__(self): self.h = [] def push(self, x): heapq.heappush(self.h, x) def pop(self): return heapq.heappop(self.h) def isEmpty(self): return len(self.h) == 0 def add(x, y): return x + y - MOD if x + y >= MOD else x + y def mul(x, y): return x * y % MOD def go(adj, src): n = len(adj) frontier = MinHeap() ways = [0] * n cost = [INF] * n frontier.push((0, src)) ways[src] = 1 cost[src] = 0 while not frontier.isEmpty(): c, u = frontier.pop() if c > cost[u]: continue for v, w in adj[u]: if c + w < cost[v]: ways[v] = ways[u] cost[v] = c + w frontier.push((c + w, v)) elif c + w == cost[v]: ways[v] = add(ways[v], ways[u]) return cost, ways n, m, s, t = map(int, input().split()) s -= 1 t -= 1 adj = [[] for i in range(n)] adj_transpose = [[] for i in range(n)] edges = [] for i in range(m): u, v, w = map(int, input().split()) u -= 1 v -= 1 edges.append((u, v, w)) adj[u].append((v, w)) adj_transpose[v].append((u, w)) cost_s, ways_s = go(adj, s) cost_t, ways_t = go(adj_transpose, t) shortest_path = cost_s[t] for i in range(m): u, v, w = edges[i] cost = cost_s[u] + cost_t[v] + w if cost > shortest_path: fix_cost = cost - shortest_path + 1 w -= cost - shortest_path + 1 print(f"CAN {fix_cost}" if w >= 1 else "NO") else: if ways_s[t] == mul(ways_s[u], ways_t[v]): print("YES") else: print("CAN 1" if w > 1 else "NO") ```
output
1
51,729
1
103,459
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6. Submitted Solution: ``` from heapq import * def D(v,g): h,p,o=[],{},[] heappush(h,(0,v)) while h: l,w=heappop(h) if w in p:continue p[w]=l o.append(w) for u,L in g[w]: heappush(h,(L+l,u)) return p,o n,m,s,t=map(int,input().split()) r=[] g={i+1:[] for i in range(n)} G=g.copy() for _ in range(m): a,b,l=map(int,input().split()) r.append((a,b,l)) g[a].append((b,l)) G[b].append((a,l)) S,o=D(s,g) T,_=D(t,G) L=S[t] H={v:[w for w,l in e if S[v]+T[w]+l==L] for v,e in g.items()} B,A=set(),{s} for v in o: if not H[v]:continue if len(A)==len(H[v])==1:B.add(v) A|=set(H[v]) A.remove(v) for a,b,l in r: c=S[a]+T[b]+l-L+1 if a in B and S[a]+T[b]+l==L:print("YES") elif c<l:print("CAN",c) else:print("NO") ```
instruction
0
51,730
1
103,460
No
output
1
51,730
1
103,461
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6. Submitted Solution: ``` from heapq import * MOD2 = 1000000123 def addM(a,b): return (0,(a[1]+b[1])%MOD2) def mulM(a,b): return (0,(a[1]*b[1])%MOD2) def dijk(adj,n,s): dist = [10**18]*n ways = [(0,0)]*n frontier = [] dist[s] = 0 ways[s] = (1,1) heappush(frontier,(0,s)) while (len(frontier)>0): x = heappop(frontier) if x[0]!=dist[x[1]]: continue x = x[1] for (i,l) in adj[x]: if dist[x]+l<dist[i]: dist[i] = dist[x]+l ways[i] = ways[x] heappush(frontier,(dist[i],i)) elif dist[x]+l==dist[i]: ways[i] = addM(ways[i],ways[x]) return (dist,ways) n,m,s,t = map(int,input().split()) s-=1 t-=1 adj = [[] for i in range(n)] jda = [[] for i in range(n)] edges = [] for i in range(m): a,b,l = map(int,input().split()) a-=1 b-=1 adj[a].append((b,l)) jda[b].append((a,l)) edges.append((a,b,l)) one = dijk(adj,n,s) two = dijk(jda,n,t) for i in edges: if one[0][i[0]]+i[2]+two[0][i[1]]==one[0][t] and mulM(one[1][i[0]],two[1][i[1]])==one[1][t]: print("YES") else: x = one[0][t]-1-one[0][i[0]]-two[0][i[1]] if x<=0: print("NO") else: print("CAN",i[2]-x) ```
instruction
0
51,731
1
103,462
No
output
1
51,731
1
103,463
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6. Submitted Solution: ``` from heapq import heappop, heappush class Node: def __init__(self, i): self.i = i self.e = [] self.f = [] self.v = None self.w = None self.r = False def __repr__(self): return f'Node({self.i})' def label(s, t, N, E): h = [(0, s)] while h: v, i = heappop(h) n = N[i] if n.v is None: n.v = v for p in n.e: _, j, u = E[p] heappush(h, (v + u, j)) h = [(0, t)] while h: w, j = heappop(h) n = N[j] if n.w is None: n.w = w for p in n.f: i, _, u = E[p] heappush(h, (w + u, i)) def rlabel(s, N, E, st): h = [(0, s)] S = {s} while h: v, i = heappop(h) n = N[i] S.remove(i) if not S: n.r = True for p in n.e: _, j, u = E[p] if j in S: continue v_ = v + u n_ = N[j] if (v_ == n_.v) and (n_.w is not None) and (n_.v + n_.w == st): S.add(j) heappush(h, (v_, j)) def query(N, E, st, p): i, j, u = E[p] n = N[i] m = N[j] # log('?', p, i, j, u, n.v, m.w, n.r, m.r) if n.v is None or n.w is None: return 'NO' e = st - n.v - m.w if e == u and n.r and m.r: return 'YES' if e > 1: return f'CAN {u-(e-1)}' return 'NO' def roads(n, m, s, t, N, E): label(s, t, N, E) # for i, n in enumerate(N): # log(i, n.v, n.w) st = N[t].v assert st rlabel(s, N, E, st) for p in range(m): yield query(N, E, st, p) def pe(N, p): i, j, u = readinti() N[i-1].e.append(p) N[j-1].f.append(p) return i-1, j-1, u def main(): n, m, s, t = readinti() N = [Node(i) for i in range(n)] E = [pe(N, p) for p in range(m)] print('\n'.join(roads(n, m, s-1, t-1, N, E))) ########## import sys import time import traceback from contextlib import contextmanager from io import StringIO def readint(): return int(input()) def readinti(): return map(int, input().split()) def readintl(): return list(readinti()) def readintll(k): return [readintl() for _ in range(k)] def log(*args, **kwargs): print(*args, **kwargs, file=sys.stderr) @contextmanager def patchio(i): try: sys.stdin = StringIO(i) sys.stdout = StringIO() yield sys.stdout finally: sys.stdin = sys.__stdin__ sys.stdout = sys.__stdout__ def do_test(k, test): try: log(f"TEST {k}") i, o = test with patchio(i) as r: t0 = time.time() main() t1 = time.time() if r.getvalue() == o: log(f"OK ({int((t1-t0)*1000000)/1000:0.3f} ms)\n") else: log(f"Expected:\n{o}" f"Got ({int((t1-t0)*1000000)/1000:0.3f} ms):\n{r.getvalue()}") except Exception: traceback.print_exc() log() def test(ts): for k in ts or range(len(tests)): do_test(k, tests[k]) tests = [("""\ 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 """, """\ YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES """), ("""\ 3 3 1 3 1 2 10 2 3 10 1 3 100 """, """\ YES YES CAN 81 """), ("""\ 2 2 1 2 1 2 1 1 2 2 """, """\ YES NO """)] if __name__ == '__main__': from argparse import ArgumentParser parser = ArgumentParser() parser.add_argument('--test', '-t', type=int, nargs='*') args = parser.parse_args() main() if args.test is None else test(args.test) ```
instruction
0
51,732
1
103,464
No
output
1
51,732
1
103,465
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Berland has n cities, the capital is located in city s, and the historic home town of the President is in city t (s ≠ t). The cities are connected by one-way roads, the travel time for each of the road is a positive integer. Once a year the President visited his historic home town t, for which his motorcade passes along some path from s to t (he always returns on a personal plane). Since the president is a very busy man, he always chooses the path from s to t, along which he will travel the fastest. The ministry of Roads and Railways wants to learn for each of the road: whether the President will definitely pass through it during his travels, and if not, whether it is possible to repair it so that it would definitely be included in the shortest path from the capital to the historic home town of the President. Obviously, the road can not be repaired so that the travel time on it was less than one. The ministry of Berland, like any other, is interested in maintaining the budget, so it wants to know the minimum cost of repairing the road. Also, it is very fond of accuracy, so it repairs the roads so that the travel time on them is always a positive integer. Input The first lines contain four integers n, m, s and t (2 ≤ n ≤ 105; 1 ≤ m ≤ 105; 1 ≤ s, t ≤ n) — the number of cities and roads in Berland, the numbers of the capital and of the Presidents' home town (s ≠ t). Next m lines contain the roads. Each road is given as a group of three integers ai, bi, li (1 ≤ ai, bi ≤ n; ai ≠ bi; 1 ≤ li ≤ 106) — the cities that are connected by the i-th road and the time needed to ride along it. The road is directed from city ai to city bi. The cities are numbered from 1 to n. Each pair of cities can have multiple roads between them. It is guaranteed that there is a path from s to t along the roads. Output Print m lines. The i-th line should contain information about the i-th road (the roads are numbered in the order of appearance in the input). If the president will definitely ride along it during his travels, the line must contain a single word "YES" (without the quotes). Otherwise, if the i-th road can be repaired so that the travel time on it remains positive and then president will definitely ride along it, print space-separated word "CAN" (without the quotes), and the minimum cost of repairing. If we can't make the road be such that president will definitely ride along it, print "NO" (without the quotes). Examples Input 6 7 1 6 1 2 2 1 3 10 2 3 7 2 4 8 3 5 3 4 5 2 5 6 1 Output YES CAN 2 CAN 1 CAN 1 CAN 1 CAN 1 YES Input 3 3 1 3 1 2 10 2 3 10 1 3 100 Output YES YES CAN 81 Input 2 2 1 2 1 2 1 1 2 2 Output YES NO Note The cost of repairing the road is the difference between the time needed to ride along it before and after the repairing. In the first sample president initially may choose one of the two following ways for a ride: 1 → 2 → 4 → 5 → 6 or 1 → 2 → 3 → 5 → 6. Submitted Solution: ``` from heapq import * MOD1 = 1000000007 MOD2 = 1000000123 def addM(a,b): return ((a[0]+b[0])%MOD1,(a[1]+b[1])%MOD2) def mulM(a,b): return ((a[0]*b[0])%MOD1,(a[1]*b[1])%MOD2) def equM(a,b): return a[0]==b[0] and a[1]==b[1] def dijk(adj,n,s): dist = [10**18]*n ways = [(0,0)]*n frontier = [] dist[s] = 0 ways[s] = (1,1) heappush(frontier,(0,s)) while (len(frontier)>0): x = heappop(frontier) if x[0]!=dist[x[1]]: continue for i in adj[x[1]]: if dist[i[0]]<dist[x[1]]+i[1]: dist[i[0]] = dist[x[1]]+i[1] ways[i[0]] = ways[x[1]] heappush(frontier,(dist[i[0]],i[0])) elif dist[i[0]]==dist[x[1]]+i[1]: ways[i[0]] = addM(ways[i[0]],ways[x[1]]) return (dist,ways) n,m,s,t = map(int,input().split()) s-=1 t-=1 adj = [[]]*n jda = [[]]*n edges = [] for i in range(m): a,b,l = map(int,input().split()) a-=1 b-=1 adj[a].append((b,l)) jda[b].append((a,l)) edges.append((a,b,l)) one = dijk(adj,n,s) two = dijk(jda,n,t) for i in edges: if mulM(one[1][i[0]],two[1][i[1]])==one[1][t] and one[0][i[0]]+i[2]+two[0][i[1]]==one[0][t]: print("YES") else: x = one[0][t]-1-one[0][i[0]]-two[0][i[1]] if x<=0: print("NO") else: print("CAN",i[2]-x) ```
instruction
0
51,733
1
103,466
No
output
1
51,733
1
103,467
Provide tags and a correct Python 3 solution for this coding contest problem. The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. Input The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation. Output In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6. Examples Input 1 30 200 Output -10.000000000000000 -20.000000000000000
instruction
0
51,738
1
103,476
Tags: math Correct Solution: ``` a, b, c = map(int, input().split()) b /= 2 * a d = (b * b - c / a) ** 0.5 print(d - b, - b - d) ```
output
1
51,738
1
103,477
Provide tags and a correct Python 3 solution for this coding contest problem. The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. Input The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation. Output In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6. Examples Input 1 30 200 Output -10.000000000000000 -20.000000000000000
instruction
0
51,739
1
103,478
Tags: math Correct Solution: ``` a, b, c = map(int, input().split()) d = (b * b - 4 * a * c)**0.5 x1, x2 = (-b - d) / (2 * a), (-b + d) / (2 * a) print(max(x1, x2)) print(min(x1, x2)) ```
output
1
51,739
1
103,479
Provide tags and a correct Python 3 solution for this coding contest problem. The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. Input The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation. Output In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6. Examples Input 1 30 200 Output -10.000000000000000 -20.000000000000000
instruction
0
51,741
1
103,482
Tags: math Correct Solution: ``` def main(): a, b, c = map(float, input().split()) b *= .5 d = (b * b - a * c) ** .5 res = ((d - b) / a, -(d + b) / a) print(max(res)) print(min(res)) if __name__ == '__main__': main() ```
output
1
51,741
1
103,483
Provide tags and a correct Python 3 solution for this coding contest problem. The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. Input The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation. Output In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6. Examples Input 1 30 200 Output -10.000000000000000 -20.000000000000000
instruction
0
51,743
1
103,486
Tags: math Correct Solution: ``` import math a,b,c = map(int,input().split()) d = b*b - 4*a*c x1 = (-b+math.sqrt(d))/(2*a) x2 = (-b-math.sqrt(d))/(2*a) print(max(x1,x2),min(x1,x2)) ```
output
1
51,743
1
103,487
Provide tags and a correct Python 3 solution for this coding contest problem. The Department of economic development of IT City created a model of city development till year 2100. To prepare report about growth perspectives it is required to get growth estimates from the model. To get the growth estimates it is required to solve a quadratic equation. Since the Department of economic development of IT City creates realistic models only, that quadratic equation has a solution, moreover there are exactly two different real roots. The greater of these roots corresponds to the optimistic scenario, the smaller one corresponds to the pessimistic one. Help to get these estimates, first the optimistic, then the pessimistic one. Input The only line of the input contains three integers a, b, c ( - 1000 ≤ a, b, c ≤ 1000) — the coefficients of ax2 + bx + c = 0 equation. Output In the first line output the greater of the equation roots, in the second line output the smaller one. Absolute or relative error should not be greater than 10 - 6. Examples Input 1 30 200 Output -10.000000000000000 -20.000000000000000
instruction
0
51,744
1
103,488
Tags: math Correct Solution: ``` import math a,b,c=map(int,input().split()) p=(-1*b + (b**2 - 4*a*c)**0.5)/(2*a) q=(-1*b - (b**2 - 4*a*c)**0.5)/(2*a) print(max(p,q)) print(min(p,q)) ```
output
1
51,744
1
103,489
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. The country Treeland consists of n cities connected with n - 1 bidirectional roads in such a way that it's possible to reach every city starting from any other city using these roads. There will be a soccer championship next year, and all participants are Santa Clauses. There are exactly 2k teams from 2k different cities. During the first stage all teams are divided into k pairs. Teams of each pair play two games against each other: one in the hometown of the first team, and the other in the hometown of the other team. Thus, each of the 2k cities holds exactly one soccer game. However, it's not decided yet how to divide teams into pairs. It's also necessary to choose several cities to settle players in. Organizers tend to use as few cities as possible to settle the teams. Nobody wants to travel too much during the championship, so if a team plays in cities u and v, it wants to live in one of the cities on the shortest path between u and v (maybe, in u or in v). There is another constraint also: the teams from one pair must live in the same city. Summarizing, the organizers want to divide 2k teams into pairs and settle them in the minimum possible number of cities m in such a way that teams from each pair live in the same city which lies between their hometowns. Input The first line of input contains two integers n and k (2 ≤ n ≤ 2·105, 2 ≤ 2k ≤ n) — the number of cities in Treeland and the number of pairs of teams, respectively. The following n - 1 lines describe roads in Treeland: each of these lines contains two integers a and b (1 ≤ a, b ≤ n, a ≠ b) which mean that there is a road between cities a and b. It's guaranteed that there is a path between any two cities. The last line contains 2k distinct integers c1, c2, ..., c2k (1 ≤ ci ≤ n), where ci is the hometown of the i-th team. All these numbers are distinct. Output The first line of output must contain the only positive integer m which should be equal to the minimum possible number of cities the teams can be settled in. The second line should contain m distinct numbers d1, d2, ..., dm (1 ≤ di ≤ n) denoting the indices of the cities where the teams should be settled. The k lines should follow, the j-th of them should contain 3 integers uj, vj and xj, where uj and vj are the hometowns of the j-th pair's teams, and xj is the city they should live in during the tournament. Each of the numbers c1, c2, ..., c2k should occur in all uj's and vj's exactly once. Each of the numbers xj should belong to {d1, d2, ..., dm}. If there are several possible answers, print any of them. Example Input 6 2 1 2 1 3 2 4 2 5 3 6 2 5 4 6 Output 1 2 5 4 2 6 2 2 Note In the first test the orginizers can settle all the teams in the city number 2. The way to divide all teams into pairs is not important, since all requirements are satisfied anyway, because the city 2 lies on the shortest path between every two cities from {2, 4, 5, 6}. Submitted Solution: ``` import time li = list(map(int, input().split())) n = li.pop(0) li.sort() for i in range(20000000): s = 0 print(" ".join(map(str, li))) ```
instruction
0
51,793
1
103,586
No
output
1
51,793
1
103,587
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths. Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially. At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium. Input The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 ≤ x, y ≤ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 ≤ ti, ci ≤ 109), which describe the taxi driver that waits at the i-th junction — the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character. Output If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Examples Input 4 4 1 3 1 2 3 1 4 1 2 4 1 2 3 5 2 7 7 2 1 2 7 7 Output 9 Note An optimal way — ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
instruction
0
51,892
1
103,784
Tags: shortest paths Correct Solution: ``` from heapq import * f = lambda: map(int, input().split()) inf = 1e13 n, m = f() x, y = f() p = [[] for i in range(n + 1)] for j in range(m): u, v, w = f() p[u].append((v, w)) p[v].append((u, w)) d = [(0, 0)] + [tuple(f()) for k in range(n)] C, T = {x: 0}, {x: 0} h = [(0, x, 0, 1)] while h: c, u, t, q = heappop(h) if u == y: exit(print(c)) dt, dc = d[u] if t < dt and q: heappush(h, (c + dc, u, dt, 0)) for v, w in p[u]: dt = t - w if dt >= 0: if c < C.get(v, inf) or dt > T.get(v, -1): C[v], T[v] = c, dt heappush(h, (c, v, dt, 1)) print(-1) ```
output
1
51,892
1
103,785
Provide tags and a correct Python 3 solution for this coding contest problem. Petya loves volleyball very much. One day he was running late for a volleyball match. Petya hasn't bought his own car yet, that's why he had to take a taxi. The city has n junctions, some of which are connected by two-way roads. The length of each road is defined by some positive integer number of meters; the roads can have different lengths. Initially each junction has exactly one taxi standing there. The taxi driver from the i-th junction agrees to drive Petya (perhaps through several intermediate junctions) to some other junction if the travel distance is not more than ti meters. Also, the cost of the ride doesn't depend on the distance and is equal to ci bourles. Taxis can't stop in the middle of a road. Each taxi can be used no more than once. Petya can catch taxi only in the junction, where it stands initially. At the moment Petya is located on the junction x and the volleyball stadium is on the junction y. Determine the minimum amount of money Petya will need to drive to the stadium. Input The first line contains two integers n and m (1 ≤ n ≤ 1000, 0 ≤ m ≤ 1000). They are the number of junctions and roads in the city correspondingly. The junctions are numbered from 1 to n, inclusive. The next line contains two integers x and y (1 ≤ x, y ≤ n). They are the numbers of the initial and final junctions correspondingly. Next m lines contain the roads' description. Each road is described by a group of three integers ui, vi, wi (1 ≤ ui, vi ≤ n, 1 ≤ wi ≤ 109) — they are the numbers of the junctions connected by the road and the length of the road, correspondingly. The next n lines contain n pairs of integers ti and ci (1 ≤ ti, ci ≤ 109), which describe the taxi driver that waits at the i-th junction — the maximum distance he can drive and the drive's cost. The road can't connect the junction with itself, but between a pair of junctions there can be more than one road. All consecutive numbers in each line are separated by exactly one space character. Output If taxis can't drive Petya to the destination point, print "-1" (without the quotes). Otherwise, print the drive's minimum cost. Please do not use the %lld specificator to read or write 64-bit integers in С++. It is preferred to use cin, cout streams or the %I64d specificator. Examples Input 4 4 1 3 1 2 3 1 4 1 2 4 1 2 3 5 2 7 7 2 1 2 7 7 Output 9 Note An optimal way — ride from the junction 1 to 2 (via junction 4), then from 2 to 3. It costs 7+2=9 bourles.
instruction
0
51,893
1
103,786
Tags: shortest paths Correct Solution: ``` import os import sys from io import BytesIO, IOBase # region fastio 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") # ------------------------------ from math import factorial from collections import Counter, defaultdict from heapq import heapify, heappop, heappush def RL(): return map(int, sys.stdin.readline().rstrip().split()) def RLL(): return list(map(int, sys.stdin.readline().rstrip().split())) def N(): return int(input()) def comb(n, m): return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0 def perm(n, m): return factorial(n) // (factorial(n - m)) if n >= m else 0 def mdis(x1, y1, x2, y2): return abs(x1 - x2) + abs(y1 - y2) def ctd(chr): return ord(chr)-ord("a") mod = 998244353 INF = float('inf') from heapq import heappush, heappop # ------------------------------ def main(): n, m = RL() x, y = RL() gp = defaultdict(dict) for _ in range(m): u, v, w = RL() gp[u][v] = min(gp[u].get(v, INF), w) gp[v][u] = min(gp[v].get(u, INF), w) cars = [[0, 0]] for _ in range(n): t, c = RL() cars.append([t, c]) disarr = [[INF]*(n+1) for _ in range(n+1)] for i in range(1, n+1): disarr[i][i] = 0 newg = [[INF]*(n+1) for _ in range(n+1)] dnex = defaultdict(list) def dij(s): q = [(0, s)] vis = [0]*(n+1) while q: d, nd = heappop(q) vis[nd] = 1 for nex in gp[nd]: if vis[nex]==1: continue dis = gp[nd][nex]+disarr[s][nd] if dis<disarr[s][nex]: disarr[s][nex] = dis heappush(q, (dis, nex)) for i in range(1, n+1): cd, cc = cars[s] d = disarr[s][i] if d<=cd: newg[s][i] = min(newg[s][i], cc) dnex[s].append(i) def dij1(s): q = [(0, s)] vis = [0]*(n+1) cst = [INF] * (n + 1) cst[s] = 0 while q: d, nd = heappop(q) vis[nd] = 1 for nex in dnex[nd]: if vis[nex]==1: continue cs = cst[nd]+newg[nd][nex] if cs<cst[nex]: cst[nex] = cs heappush(q, (cs, nex)) if cst[y]==INF: print(-1) else: print(cst[y]) for i in range(1, n+1): dij(i) dij1(x) # for i in newg:print(i) if __name__ == "__main__": main() ```
output
1
51,893
1
103,787