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
Provide tags and a correct Python 3 solution for this coding contest problem. Our brave travelers reached an island where pirates had buried treasure. However as the ship was about to moor, the captain found out that some rat ate a piece of the treasure map. The treasure map can be represented as a rectangle n × m in size. Each cell stands for an islands' square (the square's side length equals to a mile). Some cells stand for the sea and they are impenetrable. All other cells are penetrable (i.e. available) and some of them contain local sights. For example, the large tree on the hills or the cave in the rocks. Besides, the map also has a set of k instructions. Each instruction is in the following form: "Walk n miles in the y direction" The possible directions are: north, south, east, and west. If you follow these instructions carefully (you should fulfill all of them, one by one) then you should reach exactly the place where treasures are buried. Unfortunately the captain doesn't know the place where to start fulfilling the instructions — as that very piece of the map was lost. But the captain very well remembers that the place contained some local sight. Besides, the captain knows that the whole way goes through the island's penetrable squares. The captain wants to know which sights are worth checking. He asks you to help him with that. Input The first line contains two integers n and m (3 ≤ n, m ≤ 1000). Then follow n lines containing m integers each — the island map's description. "#" stands for the sea. It is guaranteed that all cells along the rectangle's perimeter are the sea. "." stands for a penetrable square without any sights and the sights are marked with uppercase Latin letters from "A" to "Z". Not all alphabet letters can be used. However, it is guaranteed that at least one of them is present on the map. All local sights are marked by different letters. The next line contains number k (1 ≤ k ≤ 105), after which k lines follow. Each line describes an instruction. Each instruction possesses the form "dir len", where dir stands for the direction and len stands for the length of the way to walk. dir can take values "N", "S", "W" and "E" for North, South, West and East correspondingly. At that, north is to the top, South is to the bottom, west is to the left and east is to the right. len is an integer from 1 to 1000. Output Print all local sights that satisfy to the instructions as a string without any separators in the alphabetical order. If no sight fits, print "no solution" without the quotes. Examples Input 6 10 ########## #K#..##### #.#..##.## #..L.#...# ###D###A.# ########## 4 N 2 S 1 E 1 W 2 Output AD Input 3 4 #### #.A# #### 2 W 1 N 2 Output no solution
instruction
0
98,622
1
197,244
Tags: brute force, implementation Correct Solution: ``` from sys import stdin n, m = map(int, stdin.readline().rstrip().split()) island = [] pos = {} for i in range(n): island.append(stdin.readline().rstrip()) for j, c in enumerate(island[i]): if c >= 'A' and c <= 'Z': pos[c] = [i, j] l_reach = [[-1 for j in range(m)] for i in range(n)] r_reach = [[-1 for j in range(m)] for i in range(n)] u_reach = [[-1 for j in range(m)] for i in range(n)] d_reach = [[-1 for j in range(m)] for i in range(n)] for i in range(1, n-1): for j in range(1, m-1): if island[i][j] != '#': l_reach[i][j] = 1 + l_reach[i][j-1] u_reach[i][j] = 1 + u_reach[i-1][j] for i in range(n-2, 0, -1): for j in range(m-2, 0, -1): if island[i][j] != '#': r_reach[i][j] = 1 + r_reach[i][j+1] d_reach[i][j] = 1 + d_reach[i+1][j] dir = [None] * 100 dir[ord('N')] = [-1, 0, u_reach] dir[ord('W')] = [0, -1, l_reach] dir[ord('S')] = [1, 0, d_reach] dir[ord('E')] = [0, 1, r_reach] for c in range(int(stdin.readline().rstrip())): x, y, d = dir[ord(stdin.read(1))] c = int(stdin.readline()[1:-1]) to_delete = [] for k, v in pos.items(): if c > d[v[0]][v[1]]: to_delete.append(k) else: v[0] += c * x v[1] += c * y for k in to_delete: del pos[k] ans = ''.join(sorted(pos.keys())) print(ans if ans else 'no solution') ```
output
1
98,622
1
197,245
Provide tags and a correct Python 3 solution for this coding contest problem. In addition to complaints about lighting, a lot of complaints about insufficient radio signal covering has been received by Bertown city hall recently. n complaints were sent to the mayor, all of which are suspiciosly similar to each other: in the i-th complaint, one of the radio fans has mentioned that the signals of two radio stations x_i and y_i are not covering some parts of the city, and demanded that the signal of at least one of these stations can be received in the whole city. Of cousre, the mayor of Bertown is currently working to satisfy these complaints. A new radio tower has been installed in Bertown, it can transmit a signal with any integer power from 1 to M (let's denote the signal power as f). The mayor has decided that he will choose a set of radio stations and establish a contract with every chosen station. To establish a contract with the i-th station, the following conditions should be met: * the signal power f should be not less than l_i, otherwise the signal of the i-th station won't cover the whole city; * the signal power f should be not greater than r_i, otherwise the signal will be received by the residents of other towns which haven't established a contract with the i-th station. All this information was already enough for the mayor to realise that choosing the stations is hard. But after consulting with specialists, he learned that some stations the signals of some stations may interfere with each other: there are m pairs of stations (u_i, v_i) that use the same signal frequencies, and for each such pair it is impossible to establish contracts with both stations. If stations x and y use the same frequencies, and y and z use the same frequencies, it does not imply that x and z use the same frequencies. The mayor finds it really hard to analyze this situation, so he hired you to help him. You have to choose signal power f and a set of stations to establish contracts with such that: * all complaints are satisfied (formally, for every i ∈ [1, n] the city establishes a contract either with station x_i, or with station y_i); * no two chosen stations interfere with each other (formally, for every i ∈ [1, m] the city does not establish a contract either with station u_i, or with station v_i); * for each chosen station, the conditions on signal power are met (formally, for each chosen station i the condition l_i ≤ f ≤ r_i is met). Input The first line contains 4 integers n, p, M and m (2 ≤ n, p, M, m ≤ 4 ⋅ 10^5) — the number of complaints, the number of radio stations, maximum signal power and the number of interfering pairs, respectively. Then n lines follow, which describe the complains. Each line contains two integers x_i and y_i (1 ≤ x_i < y_i ≤ p) — the indices of the radio stations mentioned in the i-th complaint). All complaints are distinct. Then p lines follow, which describe the radio stations. Each line contains two integers l_i and r_i (1 ≤ l_i ≤ r_i ≤ M) — the constrains on signal power that should be satisfied if the city establishes a contract with the i-th station. Then m lines follow, which describe the pairs of interfering radio stations. Each line contains two integers u_i and v_i (1 ≤ u_i < v_i ≤ p) — the indices of interfering radio stations. All these pairs are distinct. Output If it is impossible to choose signal power and a set of stations to meet all conditions, print -1. Otherwise print two integers k and f in the first line — the number of stations in the chosen set and the chosen signal power, respectively. In the second line print k distinct integers from 1 to p — the indices of stations to establish contracts with (in any order). If there are multiple answers, print any of them; you don't have to minimize/maximize the number of chosen stations, and the same applies to signal power. Examples Input 2 4 4 2 1 3 2 3 1 4 1 2 3 4 1 4 1 2 3 4 Output 2 3 1 3 Input 2 4 4 2 1 3 2 4 1 2 1 2 3 4 3 4 1 2 3 4 Output -1
instruction
0
98,709
1
197,418
Tags: 2-sat Correct Solution: ``` # ------------------- fast io -------------------- import os import sys input = lambda: sys.stdin.readline().rstrip("\r\n") # ------------------- fast io -------------------- def find_SCC(graph): SCC, S, P = [], [], [] depth = [0] * len(graph) stack = list(range(len(graph))) while stack: node = stack.pop() if node < 0: d = depth[~node] - 1 if P[-1] > d: SCC.append(S[d:]) del S[d:], P[-1] for node in SCC[-1]: depth[node] = -1 elif depth[node] > 0: while P[-1] > depth[node]: P.pop() elif depth[node] == 0: S.append(node) P.append(len(S)) depth[node] = len(S) stack.append(~node) stack += graph[node] SCC = SCC[::-1] cx = [-1] * (len(graph)) for i in range(len(SCC)): for j in SCC[i]: cx[j] = i return cx for _ in range(int(input()) if not True else 1): # n = int(input()) n, p, M, m = map(int, input().split()) # a, b = map(int, input().split()) # c, d = map(int, input().split()) # a = list(map(int, input().split())) # b = list(map(int, input().split())) # s = input() graph = [[] for __ in range(2 * p + 2 * M + 1)] for i in range(n): x, y = map(int, input().split()) x2 = (x + p) y2 = (y + p) graph[x2] += [y] graph[y2] += [x] for x in range(1, p + 1): l, r = map(int, input().split()) x2 = (x + p) l += 2 * p r += 2 * p + 1 graph[l+M] += [x2] graph[x] += [l] if r + M != 2 * p + 2 * M + 1: graph[r] += [x2] graph[x] += [r + M] for i in range(m): x, y = map(int, input().split()) x2 = (x + p) y2 = (y + p) graph[x] += [y2] graph[y] += [x2] for i in range(1, M): graph[2 * p + i + M] += [2 * p + i + M + 1] graph[2 * p + i + 1] += [2 * p + i] cx = find_SCC(graph) ans = [] for i in range(1, p + 1): if cx[i] > cx[i + p]: ans += [i] if not ans: print(-1) quit() for freq in range(M, 0, -1): if cx[2 * p + freq] > cx[2 * p + freq + M]: break print(len(ans), freq) print(*ans) ```
output
1
98,709
1
197,419
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths. Input The first line contains two integers n, m (1 ≤ n, m ≤ 106) — the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer — the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 → 1 → 3 → 1 → 4 → 1 → 5, * 2 → 1 → 3 → 1 → 5 → 1 → 4, * 2 → 1 → 4 → 1 → 5 → 1 → 3, * 3 → 1 → 2 → 1 → 4 → 1 → 5, * 3 → 1 → 2 → 1 → 5 → 1 → 4, * 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 → 1 → 4 → 1 → 3 → 1 → 5, * 2 → 1 → 5 → 1 → 3 → 1 → 4, * 2 → 1 → 5 → 1 → 4 → 1 → 3, * 3 → 1 → 4 → 1 → 2 → 1 → 5, * 3 → 1 → 5 → 1 → 2 → 1 → 4, * 4 → 1 → 3 → 1 → 2 → 1 → 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` n, m = map(int, input().split()) ranks = [0]*(n+1) rep = list(range(0, n+1)) for _ in range(0, m): a, b = map(int, input().split()) ranks[a] += 1 ranks[b] += 1 mab = min(a, b) rep[a] = mab rep[b] = mab #print(rep) if max(rep) > 1: print(0) else: odd = len([x for x in ranks if x % 2 != 0]) print(odd * (odd - 1) // 2) ```
instruction
0
99,152
1
198,304
No
output
1
99,152
1
198,305
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths. Input The first line contains two integers n, m (1 ≤ n, m ≤ 106) — the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer — the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 → 1 → 3 → 1 → 4 → 1 → 5, * 2 → 1 → 3 → 1 → 5 → 1 → 4, * 2 → 1 → 4 → 1 → 5 → 1 → 3, * 3 → 1 → 2 → 1 → 4 → 1 → 5, * 3 → 1 → 2 → 1 → 5 → 1 → 4, * 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 → 1 → 4 → 1 → 3 → 1 → 5, * 2 → 1 → 5 → 1 → 3 → 1 → 4, * 2 → 1 → 5 → 1 → 4 → 1 → 3, * 3 → 1 → 4 → 1 → 2 → 1 → 5, * 3 → 1 → 5 → 1 → 2 → 1 → 4, * 4 → 1 → 3 → 1 → 2 → 1 → 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) g = defaultdict(list) for i in range(m): a, b = map(int, input().split()) if a != b: g[a].append(b) g[b].append(a) else: g[a].append(b) color = [0]*(1 + n) stack = [] number_of_anj_comp = 0 for i in range(1, n + 1): if color[i] == 0: stack.append(i) edges = 0 while stack: v = stack.pop() if color[v] == 0: color[v] = 1 for u in g[v]: edges += 1 stack.append(u) color[v] = 2 if edges > 0: number_of_anj_comp += 1 if number_of_anj_comp > 1: print(0) else: ans = 0 for i in range(len(g)): k = len(g[i]) ans += k * (k - 1) // 2 print(ans) ```
instruction
0
99,153
1
198,306
No
output
1
99,153
1
198,307
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths. Input The first line contains two integers n, m (1 ≤ n, m ≤ 106) — the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer — the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 → 1 → 3 → 1 → 4 → 1 → 5, * 2 → 1 → 3 → 1 → 5 → 1 → 4, * 2 → 1 → 4 → 1 → 5 → 1 → 3, * 3 → 1 → 2 → 1 → 4 → 1 → 5, * 3 → 1 → 2 → 1 → 5 → 1 → 4, * 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 → 1 → 4 → 1 → 3 → 1 → 5, * 2 → 1 → 5 → 1 → 3 → 1 → 4, * 2 → 1 → 5 → 1 → 4 → 1 → 3, * 3 → 1 → 4 → 1 → 2 → 1 → 5, * 3 → 1 → 5 → 1 → 2 → 1 → 4, * 4 → 1 → 3 → 1 → 2 → 1 → 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` from collections import defaultdict n, m = map(int, input().split()) g = defaultdict(list) for i in range(m): a, b = map(int, input().split()) if a != b: g[a].append(b) g[b].append(a) else: g[a].append(b) color = [0]*(1 + n) stack = [] number_of_anj_comp = 0 for i in range(1, n + 1): if color[i] == 0: stack.append(i) edges = 0 while stack: v = stack.pop() if color[v] == 0: color[v] = 1 for u in g[v]: edges += 1 stack.append(u) color[v] = 2 if edges > 0: number_of_anj_comp += 1 if number_of_anj_comp > 1: print(0) else: ans = 0 for i in range(1, n): k = len(g[i]) ans += k * (k - 1) // 2 print(ans) ```
instruction
0
99,154
1
198,308
No
output
1
99,154
1
198,309
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Little boy Igor wants to become a traveller. At first, he decided to visit all the cities of his motherland — Uzhlyandia. It is widely known that Uzhlyandia has n cities connected with m bidirectional roads. Also, there are no two roads in the country that connect the same pair of cities, but roads starting and ending in the same city can exist. Igor wants to plan his journey beforehand. Boy thinks a path is good if the path goes over m - 2 roads twice, and over the other 2 exactly once. The good path can start and finish in any city of Uzhlyandia. Now he wants to know how many different good paths are in Uzhlyandia. Two paths are considered different if the sets of roads the paths goes over exactly once differ. Help Igor — calculate the number of good paths. Input The first line contains two integers n, m (1 ≤ n, m ≤ 106) — the number of cities and roads in Uzhlyandia, respectively. Each of the next m lines contains two integers u and v (1 ≤ u, v ≤ n) that mean that there is road between cities u and v. It is guaranteed that no road will be given in the input twice. That also means that for every city there is no more than one road that connects the city to itself. Output Print out the only integer — the number of good paths in Uzhlyandia. Examples Input 5 4 1 2 1 3 1 4 1 5 Output 6 Input 5 3 1 2 2 3 4 5 Output 0 Input 2 2 1 1 1 2 Output 1 Note In first sample test case the good paths are: * 2 → 1 → 3 → 1 → 4 → 1 → 5, * 2 → 1 → 3 → 1 → 5 → 1 → 4, * 2 → 1 → 4 → 1 → 5 → 1 → 3, * 3 → 1 → 2 → 1 → 4 → 1 → 5, * 3 → 1 → 2 → 1 → 5 → 1 → 4, * 4 → 1 → 2 → 1 → 3 → 1 → 5. There are good paths that are same with displayed above, because the sets of roads they pass over once are same: * 2 → 1 → 4 → 1 → 3 → 1 → 5, * 2 → 1 → 5 → 1 → 3 → 1 → 4, * 2 → 1 → 5 → 1 → 4 → 1 → 3, * 3 → 1 → 4 → 1 → 2 → 1 → 5, * 3 → 1 → 5 → 1 → 2 → 1 → 4, * 4 → 1 → 3 → 1 → 2 → 1 → 5, * and all the paths in the other direction. Thus, the answer is 6. In the second test case, Igor simply can not walk by all the roads. In the third case, Igor walks once over every road. Submitted Solution: ``` n, m = map(int, input().split()) ranks = [0]*(n+1) rep = list(range(0, n+1)) for _ in range(0, m): a, b = map(int, input().split()) ranks[a] += 1 ranks[b] += 1 mab = min(a, b) rep[a] = mab rep[b] = mab print(rep) if max(rep) > 1: print(0) else: odd = len([x for x in ranks if x % 2 != 0]) print(odd * (odd - 1) // 2) ```
instruction
0
99,155
1
198,310
No
output
1
99,155
1
198,311
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≤ n ≤ 3·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≤ li ≤ ri ≤ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve(): global dyn global towns for i in range(0, n)[::-1]: dyn[i] = [1, towns[i][1]] for j in range(i + 1, n): if towns[j][1] > towns[i][0] and dyn[i][0] < dyn[j][0] + 1: dyn[i][0] = dyn[j][0] + 1 return dyn[0][0] - 1 n = int(input())+1 towns = [[-500, 10e9]] for i in range(1, n): l, r = [int(x) for x in input().split()] towns.append([l, r]) # Memoization dyn = [[0, 10e9] for _ in range(len(towns))] print(solve()) print() ```
instruction
0
99,156
1
198,312
No
output
1
99,156
1
198,313
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≤ n ≤ 3·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≤ li ≤ ri ≤ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > towns[i][0]: dyn[i] = max(dyn[i], solve_rec(j, n) + 1) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): max_t = max(max_t, solve_rec(t, n)) print(max_t) ```
instruction
0
99,157
1
198,314
No
output
1
99,157
1
198,315
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≤ n ≤ 3·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≤ li ≤ ri ≤ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, day, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > day: for next_day in range(day + 1, towns[j][1] + 1): dyn[i] = max(dyn[i], solve_rec(j, next_day, n) + 1) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): for day in range(towns[t][0], towns[t][1] + 1): max_t = max(max_t, solve_rec(t, day, n)) print(max_t) ```
instruction
0
99,158
1
198,316
No
output
1
99,158
1
198,317
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Leha and Noora decided to go on a trip in the Baltic States. As you know from the previous problem, Leha has lost his car on the parking of the restaurant. Unfortunately, requests to the watchman didn't helped hacker find the car, so friends decided to go hitchhiking. In total, they intended to visit n towns. However it turned out that sights in i-th town are open for visitors only on days from li to ri. What to do? Leha proposed to choose for each town i a day, when they will visit this town, i.e any integer xi in interval [li, ri]. After that Noora choses some subsequence of towns id1, id2, ..., idk, which friends are going to visit, that at first they are strictly increasing, i.e idi < idi + 1 is for all integers i from 1 to k - 1, but also the dates of the friends visits are strictly increasing, i.e xidi < xidi + 1 is true for all integers i from 1 to k - 1. Please help Leha and Noora in choosing such xi for each town i, and such subsequence of towns id1, id2, ..., idk, so that friends can visit maximal number of towns. You may assume, that Leha and Noora can start the trip any day. Input The first line contains a single integer n (1 ≤ n ≤ 3·105) denoting the number of towns Leha and Noora intended to visit. Each line i of the n subsequent lines contains two integers li, ri (1 ≤ li ≤ ri ≤ 109), denoting that sights in i-th town are open for visitors on any day <image>. Output Print a single integer denoting the maximal number of towns, that Leha and Noora can visit. Example Input 5 6 6 1 2 3 4 2 2 1 4 Output 3 Note Consider the first example. Let's take this plan: let's visit the sight in the second town on the first day, in the third town on the third day and in the fifth town on the fourth. That's would be the optimal answer. Submitted Solution: ``` # Find largest increasing subsequence def solve_rec(i, day, n): global dyn global towns if dyn[i] != 0: return dyn[i] dyn[i] = 1 for j in range(i + 1, n): if towns[j][1] > day: max_day = dyn[i] for next_day in range(max(day + 1, towns[j][0]), towns[j][1] + 1): max_day = max(max_day, solve_rec(j, next_day, n) + 1) dyn[i] = max(dyn[i], max_day) return dyn[i] n = int(input()) towns = [(0, 0)] * n for i in range(n): l, r = [int(x) for x in input().split()] towns[i] = (l, r) # Memoization dyn = [0] * len(towns) max_t = 0 for t in range(len(towns)): for day in range(towns[t][0], towns[t][1] + 1): max_t = max(max_t, solve_rec(t, day, n)) print(max_t) ```
instruction
0
99,159
1
198,318
No
output
1
99,159
1
198,319
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,383
1
198,766
"Correct Solution: ``` import sys import heapq if sys.version[0] == '2': range, input = xrange, raw_input MAX_SPEED = 30 dvs = (-1, 0, 1) while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [[] for _ in range(N)] for _ in range(M): x, y, d, c = map(int, input().split()) edge[x - 1].append((y - 1, d, c)) edge[y - 1].append((x - 1, d, c)) INF = 1e9 dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] que = [(0.0, S, 0, S)] while que: cost, now, v, prev = heapq.heappop(que) if cost > dist[now][v][prev]: continue if now == G and v == 1: print("{:.20f}".format(cost)) break dist[now][v][prev] = cost for x, d, c in edge[now]: if x == prev: continue for dv in dvs: nv = v + dv if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv: dist[x][nv][now] = dist[now][v][prev] + d / nv heapq.heappush(que, (dist[x][nv][now], x, nv, now)) else: print("unreachable") ```
output
1
99,383
1
198,767
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,384
1
198,768
"Correct Solution: ``` from collections import defaultdict from heapq import heappop, heappush while True: n, m = map(int, input().split()) if n==0 and m==0: break s, g = map(int, input().split()) graph = defaultdict(list) for _ in range(m): x, y, d, c = map(int, input().split()) graph[x].append((y, d, c)) graph[y].append((x, d, c)) def dijkstra(s): d = defaultdict(lambda:float("INF")) d[(s, 0, -1)] = 0 used = defaultdict(bool) q = [] heappush(q, (0, (s, 0, -1))) while len(q): elapsed, v = heappop(q) cur, vel1, prev1 = v[0], v[1], v[2] if cur==g and vel1 == 1: return elapsed if used[v]: continue used[v] = True for to, dist, ct in graph[cur]: if to==prev1: continue for vel2 in range(vel1-1, vel1+2): if vel2<1 or ct<vel2: continue nxt = (to, vel2, cur) if used[nxt]: continue elapsed2 = elapsed+dist/vel2 if d[nxt] > elapsed2: d[nxt] = elapsed2 heappush(q, (elapsed2, nxt)) return "unreachable" print(dijkstra(s)) ```
output
1
99,384
1
198,769
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,385
1
198,770
"Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] while True: n,m = LI() if n == 0: break s,g = LI() a = [LI() for _ in range(m)] e = collections.defaultdict(list) for x,y,d,c in a: e[x].append((y,d,c)) e[y].append((x,d,c)) def search(s): d = collections.defaultdict(lambda: inf) d[(s,0,-1)] = 0 q = [] heapq.heappush(q, (0, (s, 0, -1))) v = collections.defaultdict(bool) while len(q): k, u = heapq.heappop(q) if v[u]: continue v[u] = True if u[0] == g and u[1] == 1: return '{:0.9f}'.format(k) c = u[1] b = u[2] for uv, ud, uc in e[u[0]]: if uv == b: continue for tc in range(max(c-1,1),min(uc+1,c+2)): nuv = (uv, tc, u[0]) if v[nuv]: continue vd = k + ud / tc if d[nuv] > vd: d[nuv] = vd heapq.heappush(q, (vd, nuv)) return 'unreachable' rr.append(search(s)) return '\n'.join(map(str, rr)) print(main()) ```
output
1
99,385
1
198,771
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,386
1
198,772
"Correct Solution: ``` def solve(): import sys from heapq import heappush, heappop file_input = sys.stdin inf = float('inf') while True: n, m = map(int, file_input.readline().split()) if n == 0: break s, g = map(int, file_input.readline().split()) adj_list = [[] for i in range(n)] for i in range(m): x, y, d, c = map(int, file_input.readline().split()) x -= 1 y -= 1 adj_list[x].append((y, d, c)) adj_list[y].append((x, d, c)) # Dijkstra's algorithm s -= 1 g -= 1 time_rec = [[[inf] * 31 for j in range(n)] for i in range(n)] time_rec[s][s][1] = 0 # pq element: (time, current city, previous city, speed) pq = [(0, s, s, 0)] while pq: t, c, p, s = heappop(pq) if time_rec[p][c][s] < t: continue if c == g and s == 1: print(t) break for next_city, d, s_limit in adj_list[c]: if next_city == p: continue if s <= 1: lower_limit = 1 else: lower_limit = s - 1 for shifted_s in range(lower_limit, s + 2): if shifted_s > s_limit: continue next_t = t + d / shifted_s if time_rec[c][next_city][shifted_s] <= next_t: continue else: heappush(pq, (next_t, next_city, c, shifted_s)) time_rec[c][next_city][shifted_s] = next_t else: print('unreachable') solve() ```
output
1
99,386
1
198,773
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,387
1
198,774
"Correct Solution: ``` import sys import heapq if sys.version[0] == '2': range, input = xrange, raw_input MAX_SPEED = 30 while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [[] for _ in range(N)] for _ in range(M): x, y, d, c = map(int, input().split()) edge[x - 1].append((y - 1, d, c)) edge[y - 1].append((x - 1, d, c)) INF = float('inf') dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] que = [(0.0, S, 0, S)] while que: cost, now, v, prev = heapq.heappop(que) if cost > dist[now][v][prev]: continue if now == G and v == 1: print("{:.20f}".format(cost)) break dist[now][v][prev] = cost for x, d, c in edge[now]: if x == prev: continue for dv in (-1, 0, 1): nv = v + dv if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv: dist[x][nv][now] = dist[now][v][prev] + d / nv heapq.heappush(que, (dist[x][nv][now], x, nv, now)) else: print("unreachable") ```
output
1
99,387
1
198,775
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,388
1
198,776
"Correct Solution: ``` from heapq import heappush, heappop def main(): while True: n, m = map(int, input().split()) if n == 0: break s, g = map(int, input().split()) s -= 1 g -= 1 edges = [[] for _ in range(n)] for _ in range(m): x, y, d, c = map(int, input().split()) x -= 1 y -= 1 edges[x].append((y, d, c)) edges[y].append((x, d, c)) que = [] heappush(que, (0, 1, s, None)) dic = {} dic[(1, None, s, None)] = 0 INF = 10 ** 20 ans = INF while que: score, speed, node, pre_node= heappop(que) if score >= ans:break for to, dist, limit in edges[node]: if to == pre_node or speed > limit:continue new_score = score + dist / speed if speed == 1 and to == g and ans > new_score:ans = new_score for new_speed in (speed - 1, speed, speed + 1): if new_speed <= 0:continue if (new_speed, to, node) not in dic or dic[(new_speed, to, node)] > new_score: dic[(new_speed, to, node)] = new_score heappush(que, (new_score, new_speed, to, node)) if ans == INF: print("unreachable") else: print(ans) main() ```
output
1
99,388
1
198,777
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,389
1
198,778
"Correct Solution: ``` #2006_D """ import sys from collections import defaultdict def dfs(d,y,x,f): global ans if d >= 10: return f_ = defaultdict(int) for i in f.keys(): f_[i] = f[i] for t,s in vr[(y,x)]: if a[t][s] == 3: ans = min(ans,d+1) break elif f[(t,s)]: if s == x+1: break f_[(t,s)] = 0 dfs(d+1,t,s-1,f_) f_[(t,s)] = 1 break for t,s in vl[(y,x)]: if a[t][s] == 3: ans = min(ans,d+1) break elif f[(t,s)]: if s == x-1: break f_[(t,s)] = 0 dfs(d+1,t,s+1,f_) f_[(t,s)] = 1 break for t,s in vd[(y,x)]: if a[t][s] == 3: ans = min(ans,d+1) break elif f[(t,s)]: if t == y+1: break f_[(t,s)] = 0 dfs(d+1,t-1,s,f_) f_[(t,s)] = 1 break for t,s in vu[(y,x)]: if a[t][s] == 3: ans = min(ans,d+1) break elif f[(t,s)]: if t == y-1: break f_[(t,s)] = 0 dfs(d+1,t+1,s,f_) f_[(t,s)] = 1 break return while 1: w,h = map(int, sys.stdin.readline()[:-1].split()) if w == h == 0: break a = [list(map(int, sys.stdin.readline()[:-1].split())) for i in range(h)] vr = defaultdict(list) vl = defaultdict(list) vd = defaultdict(list) vu = defaultdict(list) f = defaultdict(int) for y in range(h): for x in range(w): if a[y][x] == 1: f[(y,x)] = 1 if a[y][x] in [1,3]: for x_ in range(x): vr[(y,x_)].append((y,x)) elif a[y][x] == 2: sy,sx = y,x for y in range(h): for x in range(w)[::-1]: if a[y][x] in (1,3): for x_ in range(x+1,w): vl[(y,x_)].append((y,x)) for x in range(w): for y in range(h): if a[y][x] in (1,3): for y_ in range(y): vd[(y_,x)].append((y,x)) for x in range(w): for y in range(h)[::-1]: if a[y][x] in (1,3): for y_ in range(y+1,h): vu[(y_,x)].append((y,x)) ind = [[[0]*4 for i in range(w)] for j in range(h)] ans = 11 dfs(0,sy,sx,f) ans = ans if ans < 11 else -1 print(ans) """ #2018_D """ import sys from collections import defaultdict sys.setrecursionlimit(1000000) def dfs(d,s,l,v,dic): s_ = tuple(s) if dic[(d,s_)] != None: return dic[(d,s_)] if d == l: dic[(d,s_)] = 1 for x in s: if x > (n>>1): dic[(d,s_)] = 0 return 0 return 1 else: res = 0 i,j = v[d] if s[i] < (n>>1): s[i] += 1 res += dfs(d+1,s,l,v,dic) s[i] -= 1 if s[j] < (n>>1): s[j] += 1 res += dfs(d+1,s,l,v,dic) s[j] -= 1 dic[(d,s_)] = res return res def solve(n): dic = defaultdict(lambda : None) m = int(sys.stdin.readline()) s = [0]*n f = [[1]*n for i in range(n)] for i in range(n): f[i][i] = 0 for i in range(m): x,y = [int(x) for x in sys.stdin.readline().split()] x -= 1 y -= 1 s[x] += 1 f[x][y] = 0 f[y][x] = 0 v = [] for i in range(n): for j in range(i+1,n): if f[i][j]: v.append((i,j)) l = len(v) print(dfs(0,s,l,v,dic)) while 1: n = int(sys.stdin.readline()) if n == 0: break solve(n) """ #2011_D """ import sys def dfs(s,d,f,v): global ans if ans == n-n%2: return if d > ans: ans = d for i in range(n): if s[i] == 0: for j in range(i+1,n): if s[j] == 0: if f[i] == f[j]: s[i] = -1 s[j] = -1 for k in v[i]: s[k] -= 1 for k in v[j]: s[k] -= 1 dfs(s,d+2,f,v) s[i] = 0 s[j] = 0 for k in v[i]: s[k] += 1 for k in v[j]: s[k] += 1 def solve(n): p = [[int(x) for x in sys.stdin.readline().split()] for i in range(n)] v = [[] for i in range(n)] f = [0]*n s = [0]*n for i in range(n): x,y,r,f[i] = p[i] for j in range(i+1,n): xj,yj,rj,c = p[j] if (x-xj)**2+(y-yj)**2 < (r+rj)**2: v[i].append(j) s[j] += 1 dfs(s,0,f,v) print(ans) while 1: n = int(sys.stdin.readline()) ans = 0 if n == 0: break solve(n) """ #2003_D """ import sys def root(x,par): if par[x] == x: return x par[x] = root(par[x],par) return par[x] def unite(x,y,par,rank): x = root(x,par) y = root(y,par) if rank[x] < rank[y]: par[x] = y else: par[y] = x if rank[x] == rank[y]: rank[x] += 1 def solve(n): p = [[float(x) for x in sys.stdin.readline().split()] for i in range(n)] v = [] for i in range(n): for j in range(i): xi,yi,zi,ri = p[i] xj,yj,zj,rj = p[j] d = max(0,((xi-xj)**2+(yi-yj)**2+(zi-zj)**2)**0.5-(ri+rj)) v.append((i,j,d)) par = [i for i in range(n)] rank = [0]*n v.sort(key = lambda x:x[2]) ans = 0 for x,y,d in v: if root(x,par) != root(y,par): unite(x,y,par,rank) ans += d print("{:.3f}".format(round(ans,3))) while 1: n = int(sys.stdin.readline()) if n == 0: break solve(n) """ #2009_D import sys from heapq import heappop,heappush from collections import defaultdict def solve(n,m): s,g = [int(x) for x in sys.stdin.readline().split()] s -= 1 g -= 1 e = [[] for i in range(n)] for i in range(m): a,b,d,c = [int(x) for x in sys.stdin.readline().split()] a -= 1 b -= 1 e[a].append((b,d,c)) e[b].append((a,d,c)) dist = defaultdict(lambda : float("inf")) dist[(s,0,-1)] = 0 q = [(0,s,0,-1)] while q: dx,x,v,p = heappop(q) if x == g and v == 1: print(dx) return for i in range(-1,2): v_ = v+i if v_ < 1 :continue for y,d,c in e[x]: if p == y: continue if v_ > c: continue z = d/v_ if dx+z < dist[(y,v_,x)]: dist[(y,v_,x)] = dx+z heappush(q,(dist[(y,v_,x)],y,v_,x)) print("unreachable") return while 1: n,m = [int(x) for x in sys.stdin.readline().split()] if n == 0: break solve(n,m) ```
output
1
99,389
1
198,779
Provide a correct Python 3 solution for this coding contest problem. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664
instruction
0
99,390
1
198,780
"Correct Solution: ``` # AOJ 1162: Discrete Speed # Python3 2018.7.15 bal4u INF = 10e8 import heapq def dijkstra(V, to, start, goal): node = [[[INF for k in range(31)] for j in range(V)] for i in range(V)] Q = [] node[start][0][0] = 0 heapq.heappush(Q, (0, start, -1, 0)) while Q: t, s, p, v = heapq.heappop(Q) if s == goal and v == 1: return t for e, d, c in to[s]: if e == p: continue # Uターン禁止 for i in range(-1, 2): nv = v+i if nv > c or nv <= 0: continue nt = t + d/nv if nt < node[e][s][nv]: node[e][s][nv] = nt heapq.heappush(Q, (nt, e, s, nv)) return -1 while True: n, m = map(int, input().split()) if n == 0: break s, g = map(int, input().split()) s -= 1; g -= 1 to = [[] for i in range(n)] for i in range(m): x, y, d, c = map(int, input().split()) x -= 1; y -= 1 to[x].append((y, d, c)) to[y].append((x, d, c)) ans = dijkstra(n, to, s, g) print(ans if ans >= 0 else "unreachable") ```
output
1
99,390
1
198,781
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` import sys import heapq if sys.version[0] == '2': range, input = xrange, raw_input MAX_SPEED = 30 while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [[] for _ in range(N)] for _ in range(M): x, y, d, c = map(int, input().split()) edge[x - 1].append((y - 1, d, c)) edge[y - 1].append((x - 1, d, c)) INF = float('inf') dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] que = [(0.0, S, 0, S)] while que: cost, now, v, prev = heapq.heappop(que) if cost > dist[now][v][prev]: continue if now == G and v == 1: print("{:.20f}".format(cost)) break dist[now][v][prev] = cost for x, d, c in edge[now]: if x == prev: continue if 0 < v <= c and dist[x][v][now] > dist[now][v][prev] + d / v: dist[x][v][now] = dist[now][v][prev] + d / v heapq.heappush(que, (dist[x][v][now], x, v, now)) if v < c and dist[x][v + 1][now] > dist[now][v][prev] + d / (v + 1): dist[x][v + 1][now] = dist[now][v][prev] + d / (v + 1) heapq.heappush(que, (dist[x][v + 1][now], x, v + 1, now)) if 1 < v <= c + 1 and dist[x][v - 1][now] > dist[now][v][prev] + d / (v - 1): dist[x][v - 1][now] = dist[now][v][prev] + d / (v - 1) heapq.heappush(que, (dist[x][v - 1][now], x, v - 1, now)) else: print("unreachable") ```
instruction
0
99,391
1
198,782
Yes
output
1
99,391
1
198,783
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` from collections import deque from heapq import heappop, heappush def inpl(): return list(map(int, input().split())) INF = 50000 N, M = inpl() while N: s, g = inpl() G = [[] for _ in range(N+1)] for _ in range(M): a, b, d, c = inpl() G[a].append([b, c, d]) G[b].append([a, c, d]) DP = [[[INF]*(N+1) for _ in range(31)] for _ in range(N+1)] DP[s][0][0] = 0 Q = [[0, 0, s, 0]] # time, speed, where, pre while Q: t, v, p, bp = heappop(Q) if DP[p][v][bp] < t: continue for q, c, d in G[p]: if q == bp: continue for dv in range(-1, 2): nv = v+dv if not (0 < nv <= c): continue nt = t + d/(nv) if DP[q][nv][p] > nt: DP[q][nv][p] = nt heappush(Q, [nt, nv, q, p]) ans = min(DP[g][1]) if ans == INF: print("unreachable") else: print(ans) N, M = inpl() ```
instruction
0
99,392
1
198,784
Yes
output
1
99,392
1
198,785
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` import sys import heapq if sys.version[0] == '2': range, input = xrange, raw_input MAX_SPEED = 30 while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [[] for _ in range(N)] for _ in range(M): x, y, d, c = map(int, input().split()) edge[x - 1].append((y - 1, d, c)) edge[y - 1].append((x - 1, d, c)) INF = 1e18 dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] que = [(0.0, S, 0, S)] while que: cost, now, v, prev = heapq.heappop(que) if cost > dist[now][v][prev]: continue if now == G and v == 1: print("{:.20f}".format(cost)) break dist[now][v][prev] = cost for x, d, c in edge[now]: if x == prev: continue for dv in (-1, 0, 1): nv = v + dv if 0 < nv <= c and dist[x][nv][now] > dist[now][v][prev] + d / nv: dist[x][nv][now] = dist[now][v][prev] + d / nv heapq.heappush(que, (dist[x][nv][now], x, nv, now)) else: print("unreachable") ```
instruction
0
99,393
1
198,786
Yes
output
1
99,393
1
198,787
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` from collections import deque from heapq import heappop, heappush def inpl(): return list(map(int, input().split())) INF = 50000 N, M = inpl() while N: s, g = inpl() G = [[] for _ in range(N+1)] for _ in range(M): a, b, d, c = inpl() G[a].append([b, c, d]) G[b].append([a, c, d]) DP = [[INF]*(31) for _ in range(N+1)] DP[s][1] = 0 Q = [[0, 0, s]] # time, speed, where while Q: t, v, p = heappop(Q) if DP[p][v] < t: continue for q, c, d in G[p]: for dv in range(-1, 2): nv = v+dv if not (0 < nv <= min(30, c)): continue nt = t + d/(nv) if DP[q][nv] > nt: DP[q][nv] = nt heappush(Q, [nt, nv, q]) if DP[g][1] == INF: print("unreachable") else: print(DP[g][1]) N, M = inpl() ```
instruction
0
99,394
1
198,788
No
output
1
99,394
1
198,789
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` # AOJ 1162: Discrete Speed # Python3 2018.7.15 bal4u INF = 0x7fffffff import heapq def dijkstra(V, to, start, goal): node = [[[INF for k in range(32)] for j in range(V)] for i in range(V)] Q = [] node[start][0][0] = 0 heapq.heappush(Q, (0, start, 0, 0)) while Q: t, s, v, p = heapq.heappop(Q) if s == goal and v == 1: return node[goal][p][v] for e, d, c in to[s]: if e == p: continue for i in range(-1, 2): nv = v+i if nv > c or nv <= 0: continue nt = node[s][p][v]+d/nv if nt < node[e][s][nv]: node[e][s][nv] = nt heapq.heappush(Q, (nt, e, nv, s)) return -1 while True: n, m = map(int, input().split()) if n == 0: break s, g = map(int, input().split()) s -= 1; g -= 1 to = [[] for i in range(n)] for i in range(m): x, y, d, c = map(int, input().split()) x -= 1; y -= 1 to[x].append((y, d, c)) to[y].append((x, d, c)) ans = dijkstra(n, to, s, g) print(ans if ans >= 0 else "unreachable") ```
instruction
0
99,395
1
198,790
No
output
1
99,395
1
198,791
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` MAX_SPEED = 30 while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [] for _ in range(M): x, y, d, c = map(int, input().split()) edge.append((x - 1, y - 1, d, c)) edge.append((y - 1, x - 1, d, c)) INF = float('inf') dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] dist[S][0][S] = 0.0 while True: flag = False for x, y, d, c in edge: for j in range(min(MAX_SPEED + 1, c + 2)): for k in range(N): if k == y or (j <= c and dist[x][j][k] == INF): continue # print(x, y, d, c, j, k, dist[x][j][k]) if j > 1 and dist[y][j - 1][x] > dist[x][j][k] + d / (j - 1): dist[y][j - 1][x] = dist[x][j][k] + d / (j - 1) flag = True if 0 < j <= c and dist[y][j][x] > dist[x][j][k] + d / j: dist[y][j][x] = dist[x][j][k] + d / j flag = True if j < c and dist[y][j + 1][x] > dist[x][j][k] + d / (j + 1): dist[y][j + 1][x] = dist[x][j][k] + d / (j + 1) flag = True if not flag: break """ for i in range(N): print(*dist[i], sep='\n') print() """ ans = min(dist[G][1][j] for j in range(N)) print("unreachable" if ans == INF else "{:.20f}".format(ans)) ```
instruction
0
99,396
1
198,792
No
output
1
99,396
1
198,793
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Consider car trips in a country where there is no friction. Cars in this country do not have engines. Once a car started to move at a speed, it keeps moving at the same speed. There are acceleration devices on some points on the road, where a car can increase or decrease its speed by 1. It can also keep its speed there. Your job in this problem is to write a program which determines the route with the shortest time to travel from a starting city to a goal city. There are several cities in the country, and a road network connecting them. Each city has an acceleration device. As mentioned above, if a car arrives at a city at a speed v , it leaves the city at one of v - 1, v , or v + 1. The first road leaving the starting city must be run at the speed 1. Similarly, the last road arriving at the goal city must be run at the speed 1. The starting city and the goal city are given. The problem is to find the best route which leads to the goal city going through several cities on the road network. When the car arrives at a city, it cannot immediately go back the road it used to reach the city. No U-turns are allowed. Except this constraint, one can choose any route on the road network. It is allowed to visit the same city or use the same road multiple times. The starting city and the goal city may be visited during the trip. For each road on the network, its distance and speed limit are given. A car must run a road at a speed less than or equal to its speed limit. The time needed to run a road is the distance divided by the speed. The time needed within cities including that for acceleration or deceleration should be ignored. Input The input consists of multiple datasets, each in the following format. > n m > s g > x 1 y 1 d 1 c 1 > ... > xm ym dm cm > Every input item in a dataset is a non-negative integer. Input items in the same line are separated by a space. The first line gives the size of the road network. n is the number of cities in the network. You can assume that the number of cities is between 2 and 30, inclusive. m is the number of roads between cities, which may be zero. The second line gives the trip. s is the city index of the starting city. g is the city index of the goal city. s is not equal to g . You can assume that all city indices in a dataset (including the above two) are between 1 and n , inclusive. The following m lines give the details of roads between cities. The i -th road connects two cities with city indices xi and yi , and has a distance di (1 ≤ i ≤ m ). You can assume that the distance is between 1 and 100, inclusive. The speed limit of the road is specified by ci . You can assume that the speed limit is between 1 and 30, inclusive. No two roads connect the same pair of cities. A road never connects a city with itself. Each road can be traveled in both directions. The last dataset is followed by a line containing two zeros (separated by a space). Output For each dataset in the input, one line should be output as specified below. An output line should not contain extra characters such as spaces. If one can travel from the starting city to the goal city, the time needed for the best route (a route with the shortest time) should be printed. The answer should not have an error greater than 0.001. You may output any number of digits after the decimal point, provided that the above accuracy condition is satisfied. If it is impossible to reach the goal city, the string "`unreachable`" should be printed. Note that all the letters of "`unreachable`" are in lowercase. Sample Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output for the Sample Input unreachable 4.00000 5.50000 11.25664 Example Input 2 0 1 2 5 4 1 5 1 2 1 1 2 3 2 2 3 4 2 2 4 5 1 1 6 6 1 6 1 2 2 1 2 3 2 1 3 6 2 1 1 4 2 30 4 5 3 30 5 6 2 30 6 7 1 6 1 2 1 30 2 3 1 30 3 1 1 30 3 4 100 30 4 5 1 30 5 6 1 30 6 4 1 30 0 0 Output unreachable 4.00000 5.50000 11.25664 Submitted Solution: ``` from fractions import Fraction MAX_SPEED = 30 while True: N, M = map(int, input().split()) if not (N | M): break S, G = map(lambda x: int(x) - 1, input().split()) edge = [] for _ in range(M): x, y, d, c = map(int, input().split()) edge.append((x - 1, y - 1, d, c)) edge.append((y - 1, x - 1, d, c)) INF = float('inf') dist = [[[INF for _ in range(N)] for _ in range(MAX_SPEED + 1)] for _ in range(N)] dist[S][0][S] = Fraction() while True: flag = False for x, y, d, c in edge: for j in range(min(MAX_SPEED + 1, c + 2)): for k in range(N): if k == y or (j <= c and dist[x][j][k] == INF): continue # print(x, y, d, c, j, k, dist[x][j][k]) if j > 1 and dist[y][j - 1][x] > dist[x][j][k] + Fraction(d, j - 1): dist[y][j - 1][x] = dist[x][j][k] + Fraction(d, j - 1) flag = True if 0 < j <= c and dist[y][j][x] > dist[x][j][k] + Fraction(d, j): dist[y][j][x] = dist[x][j][k] + Fraction(d, j) flag = True if j < c and dist[y][j + 1][x] > dist[x][j][k] + Fraction(d, j + 1): dist[y][j + 1][x] = dist[x][j][k] + Fraction(d, j + 1) flag = True if not flag: break """ for i in range(N): print(*dist[i], sep='\n') print() """ ans = min(dist[G][1][j] for j in range(N)) print("unreachable" if ans == INF else "{:.20f}".format(float(ans))) ```
instruction
0
99,397
1
198,794
No
output
1
99,397
1
198,795
Provide a correct Python 3 solution for this coding contest problem. Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country. This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed. Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute. At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes. As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time. Input The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y. The input ends when N = M = L = K = A = H = 0, which is not included in the dataset. Output For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!". Sample Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output for the Sample Input Help! 3 2 Ten Five 12 Example Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output Help! 3 2 10 5 12
instruction
0
99,398
1
198,796
"Correct Solution: ``` from heapq import heappop, heappush def dijkstra(links, n, m, freezables, s, t): queue = [(0, 0, s, m)] visited = [0] * n while queue: link_cost, cost, node, remain = heappop(queue) if node == t: # Congratulations! if link_cost <= m: return link_cost return cost - remain if visited[node] >= remain: continue visited[node] = remain for cost2, node2 in links[node]: if remain < cost2: continue if node2 in freezables: heappush(queue, (link_cost + cost2, cost + cost2 * 2 + m - remain, node2, m)) else: heappush(queue, (link_cost + cost2, cost + cost2, node2, remain - cost2)) return 'Help!' while True: n, m, l, k, a, h = map(int, input().split()) if n == 0: break freezables = set(map(int, input().split())) if l > 0 else set() links = [set() for _ in range(n)] for _ in range(k): x, y, t = map(int, input().split()) links[x].add((t, y)) links[y].add((t, x)) print(dijkstra(links, n, m, freezables, a, h)) ```
output
1
99,398
1
198,797
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country. This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed. Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute. At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes. As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time. Input The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y. The input ends when N = M = L = K = A = H = 0, which is not included in the dataset. Output For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!". Sample Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output for the Sample Input Help! 3 2 Ten Five 12 Example Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output Help! 3 2 10 5 12 Submitted Solution: ``` from heapq import heappush, heappop INF = 10 ** 20 def main(): while True: n, m, l, k, a, h = map(int, input().split()) if n == 0: break if l != 0: sisetu = list(map(int, input().split())) + [a, h] else: input() sisetu = [a, h] costs = [[INF] * n for _ in range(n)] for _ in range(k): x, y, t = map(int, input().split()) costs[x][y] = t costs[y][x] = t for k in range(n): costsk = costs[k] for i in range(n): costsi = costs[i] costsik = costsi[k] for j in range(i + 1, n): costsij = costsi[j] costsikj = costsik + costsk[j] if costsij > costsikj: costsi[j] = costsikj costs[j][i] = costsikj edges = [[] for _ in range(n)] for i in range(n): for j in range(i + 1, n): if i in sisetu and j in sisetu and costs[i][j] <= m: edges[i].append((costs[i][j], j)) edges[j].append((costs[i][j], i)) que = [] heappush(que, (0, a)) cost = [INF] * n cost[a] = 0 while que: total, node = heappop(que) for dist, to in edges[node]: if total + dist < cost[to]: cost[to] = total + dist heappush(que, (total + dist, to)) if cost[h] == INF: print("Help!") else: print(cost[h] + max(0, (cost[h] - m))) main() ```
instruction
0
99,399
1
198,798
No
output
1
99,399
1
198,799
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country. This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed. Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute. At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes. As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time. Input The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y. The input ends when N = M = L = K = A = H = 0, which is not included in the dataset. Output For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!". Sample Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output for the Sample Input Help! 3 2 Ten Five 12 Example Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output Help! 3 2 10 5 12 Submitted Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**10 mod = 998244353 dd = [(0,-1),(1,0),(0,1),(-1,0)] ddn = [(0,-1),(1,-1),(1,0),(1,1),(0,1),(-1,-1),(-1,0),(-1,1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] while True: N,M,L,K,A,H = LI() if N == 0: break S = set() if L > 0: S = set(LI()) else: input() e = collections.defaultdict(list) for _ in range(K): a,b,d = LI() e[a].append((b,d)) e[b].append((a,d)) def search(s): d = collections.defaultdict(lambda: inf) d[(-M,s)] = 0 q = [] heapq.heappush(q, (0, -M, s)) v = collections.defaultdict(bool) while len(q): k, m, u = heapq.heappop(q) if v[(m,u)]: continue for mm in range(m,1): v[(mm,u)] = True for uv, ud in e[u]: if ud > -m or v[(m+ud,uv)]: continue vd = k + ud vm = m+ud if uv in S: vm = -M if d[(vm,uv)] > vd: for mm in range(vm,1): d[(mm,uv)] = vd heapq.heappush(q, (vd, vm, uv)) return d d = search(A) r = inf for k in list(d.keys()): if k[1] == H and r > d[k]: r = d[k] if r == inf: rr.append('Help!') elif r <= M: rr.append(r) else: rr.append(r*2-M) return '\n'.join(map(str,rr)) print(main()) ```
instruction
0
99,400
1
198,800
No
output
1
99,400
1
198,801
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country. This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed. Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute. At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes. As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time. Input The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y. The input ends when N = M = L = K = A = H = 0, which is not included in the dataset. Output For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!". Sample Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output for the Sample Input Help! 3 2 Ten Five 12 Example Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output Help! 3 2 10 5 12 Submitted Solution: ``` # AOJ2021 N = M = L = K = A = H = 0 def nexttown(): for r in range(0, N): dic[r] = [t[1:3] for t in town if t[0] == r] + [ [t[0], t[2]] for t in town if t[1] == r] def solve(): solve2(A, M, 0) if mint == 100000000: return "Help!" return mint def solve2(r, t, lv): global mint ntown = dic[r] for nt in ntown: town, time = nt tt = t - time #if t - time > 0 else 0 if tt >= 0: if not(town in freezer): if dp[tt][town] == 0 or min(dp[tt][town], mint) > dp[t][r] + time: dp[tt][town] = dp[t][r] + time if town != H: solve2(town, tt, lv + 1) elif mint > dp[tt][town]: mint = dp[tt][town] else: for j in range(M - tt, -1, -1): if dp[tt + j][town] == 0 or min(dp[tt + j][town], mint) > dp[t][r] + j + time: dp[tt + j][town] = dp[t][r] + j + time if town != H: solve2(town, tt + j, lv + 1) elif mint > dp[tt + j][town]: mint = dp[tt + j][town] while True: town = [] freezer = [] dp = [] dic = {} mint = 100000000 line = input() N, M, L, K, A, H = map(int, line.split()) if N == 0 and M == 0 and L == 0: break if L > 0: freezer = list(map(int, list(input().split()))) for _ in range(0, K): t = list(map(int, list(input().split()))) town.append(t) dp = [ [0] * N for _ in range(0, M + 1) ] nexttown() print(solve()) ```
instruction
0
99,401
1
198,802
No
output
1
99,401
1
198,803
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. Princess in Danger Princess crisis English text is not available in this practice contest. A brave princess in a poor country's tomboy is married to another country for a political marriage. However, a villain who was trying to kill the princess attacked him on the way to his wife, and the princess was seriously injured and was taken to a nearby hospital. However, the villain used a special poison to make sure the princess was dead. Therefore, in order to help the princess, she had to hurry to bring special medicine and frozen relatives' blood from her home country. This blood is transported frozen, but must be re-frozen in a blood freezing facility within up to M minutes of the previous freezing to keep it fresh. However, there are only a few places where refrigeration facilities are installed. Blood is safe for M minutes from a fully frozen state without refreezing. If the remaining time without refrigeration is S minutes and the product is transported without freezing for T minutes, the remaining time without refrigeration is S-T minutes. The remaining time that does not require refreezing can be restored up to M minutes by refreezing. The time it takes to refreeze blood depends on how much it is frozen. Every minute the blood is frozen in a freezing facility, the remaining time that does not need to be re-frozen recovers by 1 minute. At the time of departure from the capital of the home country, the remaining time without refrigerating the blood is M minutes. As a princess's servant, you must calculate the route to keep the blood fresh from the capital of your home country to the hospital where the princess was transported, in order to save the life of your precious lord. Yes, your mission is to figure out the shortest route from your home capital to the hospital and find the shortest time. Input The input consists of multiple datasets. The first row of each dataset contains six non-negative integers N (2 ≤ N ≤ 100), M (1 ≤ M ≤ 100), L (0 ≤ L ≤ N-2), K, A (0 ≤). A <N) and H (0 ≤ H <N) are given. These are the number of towns, the time limit for refrigeration, the number of towns with freezing facilities, the number of roads connecting towns directly, the number representing the capital of the home country, and the hospital where the princess was transported. Represents the town number. The capital of the home country and the hospital where the princess was transported are different towns. It is assumed that the towns are assigned numbers from 0 to N-1. The following lines are given L non-negative integers separated by a single space. These represent the numbers of the towns where the freezing facilities are located. The capital of the home country and the hospital where the princess was transported are not included in this list, but it can be considered that there is a freezing facility. The following line K gives information on the roads connecting the towns. In the i-th line, three non-negative integers X, Y, and T are given separated by one space, which means that there is a direct connection between town X and town Y, and it takes time T to move. Represents that. This road is bidirectional. Also, there is at most one road that directly connects town X and town Y. The input ends when N = M = L = K = A = H = 0, which is not included in the dataset. Output For each dataset, output the shortest time that blood can be delivered while maintaining its freshness. If it cannot be delivered, output "Help!". Sample Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output for the Sample Input Help! 3 2 Ten Five 12 Example Input 2 1 0 1 0 1 0 1 2 3 1 1 2 0 1 2 0 2 1 1 2 1 3 2 1 2 0 1 2 0 2 1 1 2 1 4 4 1 4 1 3 2 0 1 2 1 2 4 0 2 1 3 0 3 5 3 2 6 0 3 1 2 2 1 2 1 0 1 3 4 1 2 4 1 4 1 2 2 0 2 5 4 2 6 0 3 1 2 4 2 4 2 1 2 4 3 1 0 1 5 1 4 2 2 0 3 0 0 0 0 0 0 Output Help! 3 2 10 5 12 Submitted Solution: ``` town = [] freezer = [] dp = [] dic = {} mint = 100000000 N = M = L = K = A = H = 0 def nexttown(): for r in range(0, N): dic[r] = [t[1:3] for t in town if t[0] == r] + [ [t[0], t[2]] for t in town if t[1] == r] def solve(): solve2(A, M, 0) if mint == 100000000: return "Help!" return mint def solve2(r, t, lv): global mint ntown = dic[r] for nt in ntown: town, ti = nt tt = t - ti if tt >= 0: if not(town in freezer): if dp[tt][town] == 0 or min(dp[tt][town], mint) > dp[t][r] + ti: dp[tt][town] = dp[t][r] + ti if town != H: solve2(town, tt, lv + 1) elif mint > dp[tt][town]: mint = dp[tt][town] else: for j in range(M - tt, -1, -1): if dp[tt + j][town] == 0 or min(dp[tt + j][town], mint) > dp[t][r] + j + ti: dp[tt + j][town] = dp[t][r] + j + ti if town != H: solve2(town, tt + j, lv + 1) elif mint > dp[tt + j][town]: mint = dp[tt + j][town] while True: town = [] freezer = [] dp = [] dic = {} mint = 100000000 line = input() N, M, L, K, A, H = map(int, line.split()) if N == 0 and M == 0 and L == 0: break freezer = list(map(int, list(input().split()))) for _ in range(0, K): t = list(map(int, list(input().split()))) town.append(t) dp = [ [0] * N for _ in range(0, M + 1) ] nexttown() print(solve()) ```
instruction
0
99,402
1
198,804
No
output
1
99,402
1
198,805
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,909
1
199,818
Tags: binary search, math Correct Solution: ``` raw = input().split() import decimal n = int(raw[0]) k = int(raw[4]) def get(n,k): if(n%k==0): return n//k else: return n//k + 1 n = decimal.Decimal(str(get(n,k))) l = decimal.Decimal(str(raw[1])) v1 = decimal.Decimal(str(raw[2])) v2 = decimal.Decimal(str(raw[3])) print(l/v2*(decimal.Decimal('1')+(decimal.Decimal('2')*(n-decimal.Decimal(1))*(v2-v1))/(decimal.Decimal(2)*v1*n+v2-v1))) ```
output
1
99,909
1
199,819
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,910
1
199,820
Tags: binary search, math Correct Solution: ``` import math n,L,v1,v2,k = [int(x) for x in input().split()] n = int(math.ceil(n/k)) a = v2/v1 x = (2*L)/(a+2*n-1) y = L-(n-1)*x print((y*n+(n-1)*(y-x))/v2) ```
output
1
99,910
1
199,821
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,911
1
199,822
Tags: binary search, math Correct Solution: ``` n, L, v1, v2, k = map(int, input().split()) dif = v2 - v1 n = (n + k - 1) // k * 2 p1 = (n * v2 - dif) * L p2 = (n * v1 + dif) * v2 print(p1 / p2) ```
output
1
99,911
1
199,823
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,912
1
199,824
Tags: binary search, math Correct Solution: ``` import math n, l, v1, v2, k = map(int, input().split(' ')) p = math.ceil(n/k) def calc(d): cyc = ((d-d/v2*v1)/(v1+v2)) t = cyc + d/v2 #t is the time per cycle ans = -1 for i in range(p): tb4 = t * i; db4 = tb4 * v1 ans = max(ans, (d/v2+tb4+max(0, l-d-db4)/v1)) return ans lo = 0 hi = 1000000000 for i in range(200): a1 = (2*lo+hi)/3 a2 = (lo+2*hi)/3 if calc(a1)<calc(a2): hi=a2 else: lo=a1 print(calc(lo)) ```
output
1
99,912
1
199,825
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,913
1
199,826
Tags: binary search, math Correct Solution: ``` #!/usr/local/bin/python3 # -*- coding:utf-8 -*- import math inputParams = input().split() n = int(inputParams[0]) l = int(inputParams[1]) v1 = int(inputParams[2]) v2 = int(inputParams[3]) k = int(inputParams[4]) # 运送次数 times = math.ceil(n / k) t1 = l / (v2 + (2 * v2 / (v2 + v1)) * v1 * (times - 1)) totalTime = t1 + (2 * v2 / (v1 + v2)) * t1 * (times - 1) print(str(totalTime)) ```
output
1
99,913
1
199,827
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,914
1
199,828
Tags: binary search, math Correct Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,l,v1,v2,k=map(int,input().split()) n=int(math.ceil(n/k)) r=v2/v1 x=l*(r+1) x/=(2*n+r-1) ans=((n-1)*2*x)/(r+1) ans+=x/r print(ans/v1) ```
output
1
99,914
1
199,829
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,915
1
199,830
Tags: binary search, math Correct Solution: ``` n,l,v1,v2,k=map(int,input().split()) m=(n-1)//k+1 v=v1+v2 x=l/(1+(m-1)*(v1*(1-v1/v2)/(v2+v1)+v1/v2)) print(x/v2+(l-x)/v1) ```
output
1
99,915
1
199,831
Provide tags and a correct Python 3 solution for this coding contest problem. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5.
instruction
0
99,916
1
199,832
Tags: binary search, math Correct Solution: ``` n,l,v1,v2,k=map(int,input().split()) n=(n+k-1)//k a=(v2-v1)/(v1+v2) t=l/v2/(n-(n-1)*a) print(n*t+(n-1)*a*t) # Made By Mostafa_Khaled ```
output
1
99,916
1
199,833
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n,l,v,o,k=map(int,input().split()) T=(n+k-1)//k e=1-v/o L=l/v/(T/o+T*e/(v+o)-e/(v+o)-1/o+1/v) print((l-L)/v+L/o) ```
instruction
0
99,917
1
199,834
Yes
output
1
99,917
1
199,835
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n,l,v1,v2,k=map(int,input().split()) n=(n+k-1)//k a=(v2-v1)/(v1+v2) t=l/v2/(n-(n-1)*a) print(n*t+(n-1)*a*t) ```
instruction
0
99,918
1
199,836
Yes
output
1
99,918
1
199,837
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n, l, v1, v2, k = map(int, input().split()) diff = v2 - v1 n = (n + k - 1) // k * 2 p1 = (n * v2 - diff) * l p2 = (n * v1 + diff) * v2 print(p1 / p2) ```
instruction
0
99,919
1
199,838
Yes
output
1
99,919
1
199,839
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` import sys import math data = sys.stdin.read() data = data.split(' ') n = int(data[0]) l = int(data[1]) w = int(data[2]) v = int(data[3]) k = int(data[4]) z = math.ceil(n/k) top = l/w - l/(2*w*z) + l/(2*v*z) bot = 1 + v/(2*w*z) - 1/(2*z) print(top/bot) ```
instruction
0
99,920
1
199,840
Yes
output
1
99,920
1
199,841
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` # ---------------------------iye ha aam zindegi--------------------------------------------- import math import random import heapq, bisect import sys from collections import deque, defaultdict from fractions import Fraction import sys import threading from collections import defaultdict threading.stack_size(10**8) mod = 10 ** 9 + 7 mod1 = 998244353 # ------------------------------warmup---------------------------- import os import sys from io import BytesIO, IOBase sys.setrecursionlimit(300000) 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") # -------------------game starts now----------------------------------------------------import math class TreeNode: def __init__(self, k, v): self.key = k self.value = v self.left = None self.right = None self.parent = None self.height = 1 self.num_left = 1 self.num_total = 1 class AvlTree: def __init__(self): self._tree = None def add(self, k, v): if not self._tree: self._tree = TreeNode(k, v) return node = self._add(k, v) if node: self._rebalance(node) def _add(self, k, v): node = self._tree while node: if k < node.key: if node.left: node = node.left else: node.left = TreeNode(k, v) node.left.parent = node return node.left elif node.key < k: if node.right: node = node.right else: node.right = TreeNode(k, v) node.right.parent = node return node.right else: node.value = v return @staticmethod def get_height(x): return x.height if x else 0 @staticmethod def get_num_total(x): return x.num_total if x else 0 def _rebalance(self, node): n = node while n: lh = self.get_height(n.left) rh = self.get_height(n.right) n.height = max(lh, rh) + 1 balance_factor = lh - rh n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right) n.num_left = 1 + self.get_num_total(n.left) if balance_factor > 1: if self.get_height(n.left.left) < self.get_height(n.left.right): self._rotate_left(n.left) self._rotate_right(n) elif balance_factor < -1: if self.get_height(n.right.right) < self.get_height(n.right.left): self._rotate_right(n.right) self._rotate_left(n) else: n = n.parent def _remove_one(self, node): """ Side effect!!! Changes node. Node should have exactly one child """ replacement = node.left or node.right if node.parent: if AvlTree._is_left(node): node.parent.left = replacement else: node.parent.right = replacement replacement.parent = node.parent node.parent = None else: self._tree = replacement replacement.parent = None node.left = None node.right = None node.parent = None self._rebalance(replacement) def _remove_leaf(self, node): if node.parent: if AvlTree._is_left(node): node.parent.left = None else: node.parent.right = None self._rebalance(node.parent) else: self._tree = None node.parent = None node.left = None node.right = None def remove(self, k): node = self._get_node(k) if not node: return if AvlTree._is_leaf(node): self._remove_leaf(node) return if node.left and node.right: nxt = AvlTree._get_next(node) node.key = nxt.key node.value = nxt.value if self._is_leaf(nxt): self._remove_leaf(nxt) else: self._remove_one(nxt) self._rebalance(node) else: self._remove_one(node) def get(self, k): node = self._get_node(k) return node.value if node else -1 def _get_node(self, k): if not self._tree: return None node = self._tree while node: if k < node.key: node = node.left elif node.key < k: node = node.right else: return node return None def get_at(self, pos): x = pos + 1 node = self._tree while node: if x < node.num_left: node = node.left elif node.num_left < x: x -= node.num_left node = node.right else: return (node.key, node.value) raise IndexError("Out of ranges") @staticmethod def _is_left(node): return node.parent.left and node.parent.left == node @staticmethod def _is_leaf(node): return node.left is None and node.right is None def _rotate_right(self, node): if not node.parent: self._tree = node.left node.left.parent = None elif AvlTree._is_left(node): node.parent.left = node.left node.left.parent = node.parent else: node.parent.right = node.left node.left.parent = node.parent bk = node.left.right node.left.right = node node.parent = node.left node.left = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) def _rotate_left(self, node): if not node.parent: self._tree = node.right node.right.parent = None elif AvlTree._is_left(node): node.parent.left = node.right node.right.parent = node.parent else: node.parent.right = node.right node.right.parent = node.parent bk = node.right.left node.right.left = node node.parent = node.right node.right = bk if bk: bk.parent = node node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1 node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right) node.num_left = 1 + self.get_num_total(node.left) @staticmethod def _get_next(node): if not node.right: return node.parent n = node.right while n.left: n = n.left return n # -----------------------------------------------binary seacrh tree--------------------------------------- class SegmentTree1: def __init__(self, data, default=2**51, func=lambda a, b: a & b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------game starts now----------------------------------------------------import math class SegmentTree: def __init__(self, data, default=0, func=lambda a, b: a + b): """initialize the segment tree with data""" self._default = default self._func = func self._len = len(data) self._size = _size = 1 << (self._len - 1).bit_length() self.data = [default] * (2 * _size) self.data[_size:_size + self._len] = data for i in reversed(range(_size)): self.data[i] = func(self.data[i + i], self.data[i + i + 1]) def __delitem__(self, idx): self[idx] = self._default def __getitem__(self, idx): return self.data[idx + self._size] def __setitem__(self, idx, value): idx += self._size self.data[idx] = value idx >>= 1 while idx: self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1]) idx >>= 1 def __len__(self): return self._len def query(self, start, stop): if start == stop: return self.__getitem__(start) stop += 1 start += self._size stop += self._size res = self._default while start < stop: if start & 1: res = self._func(res, self.data[start]) start += 1 if stop & 1: stop -= 1 res = self._func(res, self.data[stop]) start >>= 1 stop >>= 1 return res def __repr__(self): return "SegmentTree({0})".format(self.data) # -------------------------------iye ha chutiya zindegi------------------------------------- class Factorial: def __init__(self, MOD): self.MOD = MOD self.factorials = [1, 1] self.invModulos = [0, 1] self.invFactorial_ = [1, 1] def calc(self, n): if n <= -1: print("Invalid argument to calculate n!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.factorials): return self.factorials[n] nextArr = [0] * (n + 1 - len(self.factorials)) initialI = len(self.factorials) prev = self.factorials[-1] m = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = prev * i % m self.factorials += nextArr return self.factorials[n] def inv(self, n): if n <= -1: print("Invalid argument to calculate n^(-1)") print("n must be non-negative value. But the argument was " + str(n)) exit() p = self.MOD pi = n % p if pi < len(self.invModulos): return self.invModulos[pi] nextArr = [0] * (n + 1 - len(self.invModulos)) initialI = len(self.invModulos) for i in range(initialI, min(p, n + 1)): next = -self.invModulos[p % i] * (p // i) % p self.invModulos.append(next) return self.invModulos[pi] def invFactorial(self, n): if n <= -1: print("Invalid argument to calculate (n^(-1))!") print("n must be non-negative value. But the argument was " + str(n)) exit() if n < len(self.invFactorial_): return self.invFactorial_[n] self.inv(n) # To make sure already calculated n^-1 nextArr = [0] * (n + 1 - len(self.invFactorial_)) initialI = len(self.invFactorial_) prev = self.invFactorial_[-1] p = self.MOD for i in range(initialI, n + 1): prev = nextArr[i - initialI] = (prev * self.invModulos[i % p]) % p self.invFactorial_ += nextArr return self.invFactorial_[n] class Combination: def __init__(self, MOD): self.MOD = MOD self.factorial = Factorial(MOD) def ncr(self, n, k): if k < 0 or n < k: return 0 k = min(k, n - k) f = self.factorial return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD # --------------------------------------iye ha combinations ka zindegi--------------------------------- def powm(a, n, m): if a == 1 or n == 0: return 1 if n % 2 == 0: s = powm(a, n // 2, m) return s * s % m else: return a * powm(a, n - 1, m) % m # --------------------------------------iye ha power ka zindegi--------------------------------- def sort_list(list1, list2): zipped_pairs = zip(list2, list1) z = [x for _, x in sorted(zipped_pairs)] return z # --------------------------------------------------product---------------------------------------- def product(l): por = 1 for i in range(len(l)): por *= l[i] return por # --------------------------------------------------binary---------------------------------------- def binarySearchCount(arr, n, key): left = 0 right = n - 1 count = 0 while (left <= right): mid = int((right + left) / 2) # Check if middle element is # less than or equal to key if (arr[mid] < key): count = mid + 1 left = mid + 1 # If key is smaller, ignore right half else: right = mid - 1 return count # --------------------------------------------------binary---------------------------------------- def countdig(n): c = 0 while (n > 0): n //= 10 c += 1 return c def binary(x, length): y = bin(x)[2:] return y if len(y) >= length else "0" * (length - len(y)) + y def countGreater(arr, n, k): l = 0 r = n - 1 # Stores the index of the left most element # from the array which is greater than k leftGreater = n # Finds number of elements greater than k while (l <= r): m = int(l + (r - l) / 2) if (arr[m] >= k): leftGreater = m r = m - 1 # If mid element is less than # or equal to k update l else: l = m + 1 # Return the count of elements # greater than k return (n - leftGreater) # --------------------------------------------------binary------------------------------------ n,l,v1,v2,k=map(int,input().split()) n=int(math.ceil(n/k)) r=v2/v1 x=l*(r+1) x/=(2*n+r-1) ans=((n-1)*2*x)/(r+1) ans+=x/r print(ans*v1) ```
instruction
0
99,921
1
199,842
No
output
1
99,921
1
199,843
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n, L, v1, v2, k = map(int, input().split()) dif = v2 - v1 n = (n + k - 1) // 2 * k p1 = (n * v2 - dif) * L p2 = (n * v1 + dif) * L print(p1 / p2) ```
instruction
0
99,922
1
199,844
No
output
1
99,922
1
199,845
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n, l, v1, v2, k = map(int, input().split()) n, u = (n + k - 1) // k, v1 * (n - 1) a, b, c, d, e, f = u + v2, u, l, n, 1-n, l/v2 D, E, F = a * e - b * d, c * e - f * b, a * f - d * c print((E * n + F * (n - 1)) / D) ```
instruction
0
99,923
1
199,846
No
output
1
99,923
1
199,847
Evaluate the correctness of the submitted Python 3 solution to the coding contest problem. Provide a "Yes" or "No" response. On vacations n pupils decided to go on excursion and gather all together. They need to overcome the path with the length l meters. Each of the pupils will go with the speed equal to v1. To get to the excursion quickly, it was decided to rent a bus, which has seats for k people (it means that it can't fit more than k people at the same time) and the speed equal to v2. In order to avoid seasick, each of the pupils want to get into the bus no more than once. Determine the minimum time required for all n pupils to reach the place of excursion. Consider that the embarkation and disembarkation of passengers, as well as the reversal of the bus, take place immediately and this time can be neglected. Input The first line of the input contains five positive integers n, l, v1, v2 and k (1 ≤ n ≤ 10 000, 1 ≤ l ≤ 109, 1 ≤ v1 < v2 ≤ 109, 1 ≤ k ≤ n) — the number of pupils, the distance from meeting to the place of excursion, the speed of each pupil, the speed of bus and the number of seats in the bus. Output Print the real number — the minimum time in which all pupils can reach the place of excursion. Your answer will be considered correct if its absolute or relative error won't exceed 10 - 6. Examples Input 5 10 1 2 5 Output 5.0000000000 Input 3 6 1 2 1 Output 4.7142857143 Note In the first sample we should immediately put all five pupils to the bus. The speed of the bus equals 2 and the distance is equal to 10, so the pupils will reach the place of excursion in time 10 / 2 = 5. Submitted Solution: ``` n, l, v1, v2, k = map(int, input().split()) T = 0 if (n==3) and(l==6) and(v1==1) and(v2==2) and(k==1): l = -123123 # Как бы тупо то ни было T = 4.7142857143 t = l/v2 # Время, за которое автобус доезжает до места while l > 0: n -= k # Автобус забирает пассажиров T += t # Общее время l -= t*v1 # От общего расстояния отнимается пройденное школьниками if n < 1: break t = l/(v1+v2) # Время, за которое автобус и школьники встречаются T += t # Общее время l -= t*v1 # От общего расстояния отнимается пройденное школьниками print(format(T, '.10f')) ```
instruction
0
99,924
1
199,848
No
output
1
99,924
1
199,849
Provide a correct Python 3 solution for this coding contest problem. A taxi driver, Nakamura, was so delighted because he got a passenger who wanted to go to a city thousands of kilometers away. However, he had a problem. As you may know, most taxis in Japan run on liquefied petroleum gas (LPG) because it is cheaper than gasoline. There are more than 50,000 gas stations in the country, but less than one percent of them sell LPG. Although the LPG tank of his car was full, the tank capacity is limited and his car runs 10 kilometer per liter, so he may not be able to get to the destination without filling the tank on the way. He knew all the locations of LPG stations. Your task is to write a program that finds the best way from the current location to the destination without running out of gas. Input The input consists of several datasets, and each dataset is in the following format. N M cap src dest c1,1 c1,2 d1 c2,1 c2,2 d2 . . . cN,1 cN,2 dN s1 s2 . . . sM The first line of a dataset contains three integers (N, M, cap), where N is the number of roads (1 ≤ N ≤ 3000),M is the number of LPG stations (1≤ M ≤ 300), and cap is the tank capacity (1 ≤ cap ≤ 200) in liter. The next line contains the name of the current city (src) and the name of the destination city (dest). The destination city is always different from the current city. The following N lines describe roads that connect cities. The road i (1 ≤ i ≤ N) connects two different cities ci,1 and ci,2 with an integer distance di (0 < di ≤ 2000) in kilometer, and he can go from either city to the other. You can assume that no two different roads connect the same pair of cities. The columns are separated by a single space. The next M lines (s1,s2,...,sM) indicate the names of the cities with LPG station. You can assume that a city with LPG station has at least one road. The name of a city has no more than 15 characters. Only English alphabet ('A' to 'Z' and 'a' to 'z', case sensitive) is allowed for the name. A line with three zeros terminates the input. Output For each dataset, output a line containing the length (in kilometer) of the shortest possible journey from the current city to the destination city. If Nakamura cannot reach the destination, output "-1" (without quotation marks). You must not output any other characters. The actual tank capacity is usually a little bit larger than that on the specification sheet, so you can assume that he can reach a city even when the remaining amount of the gas becomes exactly zero. In addition, you can always fill the tank at the destination so you do not have to worry about the return trip. Example Input 6 3 34 Tokyo Kyoto Tokyo Niigata 335 Tokyo Shizuoka 174 Shizuoka Nagoya 176 Nagoya Kyoto 195 Toyama Niigata 215 Toyama Kyoto 296 Nagoya Niigata Toyama 6 3 30 Tokyo Kyoto Tokyo Niigata 335 Tokyo Shizuoka 174 Shizuoka Nagoya 176 Nagoya Kyoto 195 Toyama Niigata 215 Toyama Kyoto 296 Nagoya Niigata Toyama 0 0 0 Output 846 -1
instruction
0
100,275
1
200,550
"Correct Solution: ``` import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time,copy,functools sys.setrecursionlimit(10**7) inf = 10**20 eps = 1.0 / 10**13 mod = 10**9+7 dd = [(-1,0),(0,1),(1,0),(0,-1)] ddn = [(-1,0),(-1,1),(0,1),(1,1),(1,0),(1,-1),(0,-1),(-1,-1)] def LI(): return [int(x) for x in sys.stdin.readline().split()] def LI_(): return [int(x)-1 for x in sys.stdin.readline().split()] def LF(): return [float(x) for x in sys.stdin.readline().split()] def LS(): return sys.stdin.readline().split() def I(): return int(sys.stdin.readline()) def F(): return float(sys.stdin.readline()) def S(): return input() def pf(s): return print(s, flush=True) def main(): rr = [] def f(n,m,cap): cap *= 10 s,t = LS() e = collections.defaultdict(list) for _ in range(n): a,b,c = LS() c = int(c) e[a].append((b,c)) e[b].append((a,c)) cs = set([S() for _ in range(m)]) def search(s,t): d = collections.defaultdict(lambda: inf) d[(s,cap)] = 0 q = [] heapq.heappush(q, (0, (s,cap))) v = collections.defaultdict(bool) while len(q): k, u = heapq.heappop(q) if v[u]: continue v[u] = True if u[0] == t: return k for uv, ud in e[u[0]]: uc = u[1] - ud if uc < 0: continue if uv in cs: uc = cap uv = (uv, uc) if v[uv]: continue vd = k + ud if d[uv] > vd: d[uv] = vd heapq.heappush(q, (vd, uv)) return None r = search(s,t) if r is None: return -1 return r while 1: n,m,l = LI() if n == 0: break rr.append(f(n,m,l)) # print('rr', rr[-1]) return '\n'.join(map(str,rr)) print(main()) ```
output
1
100,275
1
200,551
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only w_i liters of gasoline in the i-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. Input The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of cities. The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_{i} ≤ 10^9) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next n - 1 lines describes road and contains three integers u, v, c (1 ≤ u, v ≤ n, 1 ≤ c ≤ 10^9, u ≠ v), where u and v — cities that are connected by this road and c — its length. It is guaranteed that graph of road connectivity is a tree. Output Print one number — the maximum amount of gasoline that he can have at the end of the path. Examples Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 Note The optimal way in the first example is 2 → 1 → 3. <image> The optimal way in the second example is 2 → 4. <image>
instruction
0
100,336
1
200,672
Tags: data structures, dp, trees Correct Solution: ``` n=int(input()) w=list(map(int,input().split())) edges=[[] for i in range(n)] for i in range(n-1): a,b,c=map(int,input().split()) edges[a-1].append((b-1,c)) edges[b-1].append((a-1,c)) parents=[None]*n layers=[{0}] while True: newlayer=[] for guy in layers[-1]: for neigh in edges[guy]: if neigh[0]!=parents[guy]: newlayer.append(neigh[0]) parents[neigh[0]]=guy if newlayer!=[]: layers.append(set(newlayer)) else: break b1=[None]*n b2=[None]*n for layer in layers[::-1]: for guy in layer: goods=[] for guy1 in edges[guy]: if guy1[0]!=parents[guy]: goods.append(b1[guy1[0]]-guy1[1]) big1=0 big2=0 for boi in goods: if boi>big1: big1,big2=boi,big1 elif boi>big2: big2=boi b1[guy]=w[guy]+big1 b2[guy]=w[guy]+big1+big2 print(max(b2)) ```
output
1
100,336
1
200,673
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only w_i liters of gasoline in the i-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. Input The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of cities. The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_{i} ≤ 10^9) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next n - 1 lines describes road and contains three integers u, v, c (1 ≤ u, v ≤ n, 1 ≤ c ≤ 10^9, u ≠ v), where u and v — cities that are connected by this road and c — its length. It is guaranteed that graph of road connectivity is a tree. Output Print one number — the maximum amount of gasoline that he can have at the end of the path. Examples Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 Note The optimal way in the first example is 2 → 1 → 3. <image> The optimal way in the second example is 2 → 4. <image>
instruction
0
100,337
1
200,674
Tags: data structures, dp, trees Correct Solution: ``` import sys from collections import deque sys.setrecursionlimit(1000000) input = sys.stdin.readline n=int(input()) W=list(map(int,input().split())) EDGE=[list(map(int,input().split())) for i in range(n-1)] #n=30000 #W=[10 for i in range(n)] #EDGE=[[i+1,i+2,1] for i in range(n-1)] EDGELIST=[[] for i in range(n+1)] for i,j,c in EDGE: EDGELIST[i].append([j,c]) EDGELIST[j].append([i,c]) QUE = deque([1]) COST=[[None] for i in range(n+1)] COST[1]=W[0] USED=[0]*(n+1) USED[1]=1 HLIST=[] EDGELIST2=[[] for i in range(n+1)] while QUE: x=QUE.pop() for to ,length in EDGELIST[x]: if USED[to]==0: COST[to]=COST[x]-length+W[to-1] QUE.append(to) EDGELIST2[x].append(to) USED[x]=1 HLIST.append(x) MAXCOST=dict() def best(i,j):#i→jから繋がるsubtreeで最大のcost if MAXCOST.get((i,j))!=None: return MAXCOST[(i,j)] else: ANS=COST[j] for k,_ in EDGELIST[j]: if k==i: continue if ANS<best(j,k): ANS=best(j,k) MAXCOST[(i,j)]=ANS return ANS ANS=max(W) for i in HLIST[::-1]: for j in EDGELIST2[i]: if ANS<best(i,j)-COST[i]+W[i-1]: ANS=best(i,j)-COST[i]+W[i-1] CLIST=[] for j in EDGELIST2[i]: CLIST.append(best(i,j)) if len(CLIST)<=1: continue else: CLIST.sort(reverse=True) if ANS<CLIST[0]+CLIST[1]-COST[i]*2+W[i-1]: ANS=CLIST[0]+CLIST[1]-COST[i]*2+W[i-1] print(ANS) ```
output
1
100,337
1
200,675
Provide tags and a correct Python 3 solution for this coding contest problem. The Fair Nut is going to travel to the Tree Country, in which there are n cities. Most of the land of this country is covered by forest. Furthermore, the local road system forms a tree (connected graph without cycles). Nut wants to rent a car in the city u and go by a simple path to city v. He hasn't determined the path, so it's time to do it. Note that chosen path can consist of only one vertex. A filling station is located in every city. Because of strange law, Nut can buy only w_i liters of gasoline in the i-th city. We can assume, that he has infinite money. Each road has a length, and as soon as Nut drives through this road, the amount of gasoline decreases by length. Of course, Nut can't choose a path, which consists of roads, where he runs out of gasoline. He can buy gasoline in every visited city, even in the first and the last. He also wants to find the maximum amount of gasoline that he can have at the end of the path. Help him: count it. Input The first line contains a single integer n (1 ≤ n ≤ 3 ⋅ 10^5) — the number of cities. The second line contains n integers w_1, w_2, …, w_n (0 ≤ w_{i} ≤ 10^9) — the maximum amounts of liters of gasoline that Nut can buy in cities. Each of the next n - 1 lines describes road and contains three integers u, v, c (1 ≤ u, v ≤ n, 1 ≤ c ≤ 10^9, u ≠ v), where u and v — cities that are connected by this road and c — its length. It is guaranteed that graph of road connectivity is a tree. Output Print one number — the maximum amount of gasoline that he can have at the end of the path. Examples Input 3 1 3 3 1 2 2 1 3 2 Output 3 Input 5 6 3 2 5 0 1 2 10 2 3 3 2 4 1 1 5 1 Output 7 Note The optimal way in the first example is 2 → 1 → 3. <image> The optimal way in the second example is 2 → 4. <image>
instruction
0
100,338
1
200,676
Tags: data structures, dp, trees Correct Solution: ``` import os,io input=io.BytesIO(os.read(0,os.fstat(0).st_size)).readline n=int(input()) w=list(map(int,input().split())) ans=max(w) graph=[] for i in range(n): graph.append([]) for i in range(n-1): u,v,c=map(int,input().split()) graph[u-1].append((v-1,c)) graph[v-1].append((u-1,c)) children=[] parents=[-1]*n for i in range(n): children.append([]) stack=[(0,-1)] while stack: curr,parent=stack.pop() for i,j in graph[curr]: if i!=parent: children[curr].append((i,j)) parents[i]=curr stack.append((i,curr)) donechildren=[0]*n value=[0]*n stack=[] for i in range(n): if not children[i]: stack.append(i) while stack: curr=stack.pop() k=[] for child,cost in children[curr]: k.append(value[child]-cost) k.sort() if len(children[curr])>=2: ans=max(ans,k[-1]+k[-2]+w[curr]) if children[curr]: value[curr]=max(w[curr],w[curr]+k[-1]) else: value[curr]=w[curr] ans=max(ans,value[curr]) if curr==0: break parent=parents[curr] donechildren[parent]+=1 if donechildren[parent]==len(children[parent]): stack.append(parent) print(ans) ```
output
1
100,338
1
200,677