Parcel-delivery app~45 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacedijkstra · shortest-paths
A delivery app shows the earliest time a courier can reach a customer. The roads are one-way, and each road has a normal travel time. Many roads also have a rush hour, a stretch of time in which the road is slower. A courier who enters a road during its rush hour takes the slower time.
A courier can also wait at a junction. Sometimes it is better to wait for a rush hour to end than to drive through it. The app wants the earliest possible arrival.
Write earliest_arrival(n, roads, start_time, source, target).
0 to n - 1. Each road is [u, v, normal, rush, begin, end], a one-way road from u to v. It takes normal minutes to cross, or rush minutes for a courier who enters at a minute t with begin <= t < end. A road with begin == end has no rush hour, and rush >= normal always.source at minute start_time. At any junction, the courier may wait for any number of minutes before entering a road.target, or -1 when it cannot be reached. If source is target, the answer is start_time.Input: n = 5, roads = [[0, 1, 4, 100, 10, 20], [1, 4, 4, 4, 0, 0], [0, 2, 10, 10, 0, 0], [2, 3, 10, 10, 0, 0], [3, 4, 10, 10, 0, 0]], start_time = 10, source = 0, target = 4
Output: 28The road from 0 to 1 takes 4 minutes, or 100 inside its rush hour from minute 10 up to minute 20. The courier starts at minute 10, so it must either drive for 100 minutes or wait until minute 20 and drive for 4.
| Step | Junction | Minute | Road taken | Option: enter now | Option: wait for the rush to end | Arrival |
|---|---|---|---|---|---|---|
| 1 | 0 | 10 | to 1 | 10 + 100 = 110 | 20 + 4 = 24 | 24 |
| 2 | 0 | 10 | to 2 | not in a rush hour | none | 20 |
| 3 | 2 | 20 | to 3 | not in a rush hour | none | 30 |
| 4 | 1 | 24 | to 4 | not in a rush hour | none | 28 |
| 5 | 3 | 30 | to 4 | not in a rush hour | none | 40 |
The earliest arrival at junction 4 is 28, through junction 1. The output is 28.
Input: n = 3, roads = [[0, 1, 5, 5, 0, 0]], start_time = 0, source = 0, target = 2
Output: -1No road leads to junction 2, so the target cannot be reached.
Input: n = 1, roads = [], start_time = 7, source = 0, target = 0
Output: 7The courier is already at the target, so the answer is the start minute.
1 ≤ n ≤ 100,000 (junctions); 0 ≤ roads.length ≤ 100,000; each road has 6 numbers0 ≤ u, v < n; 0 ≤ normal ≤ rush, and 0 ≤ begin ≤ end; every number is at most 1,000,0000 ≤ start_time ≤ 1,000,000, 0 ≤ source, target < nTrying every route is exponential, and relaxing every road again and again costs about n × m, which is 10^10 at the limits. Roads never take negative time, and leaving later never gets you there earlier, because you can always wait. That makes the earliest arrival at each junction a number you can settle in order, with a heap, in about (n + m) log n steps.