Ride-hailing app~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacedijkstra
You work on a ride-sharing app. A city has n stops, numbered 0 to n - 1, joined by one-way legs. Every leg has a fare in units, and a fare can be 0.
A rider has one coupon that makes any single leg of the trip free. The rider chooses the leg, and may also leave the coupon unused. The coupon cannot be used twice, and a leg that is ridden twice is paid for each time.
Your team lead asks: "What is the lowest total fare from the start stop to the destination?" The city can have 30,000 stops and 60,000 legs.
Write cheapest_with_coupon(n, roads, source, target).
roads[k] = [a, b, fare] is a one-way leg from stop a to stop b that costs fare, between 0 and 1,000,000,000 units. Legs can repeat.source to target, where each leg starts where the previous one ended. The coupon makes the fare of one leg of the trip 0.source = target, the trip has no legs and the fare is 0.-1 when target cannot be reached.Input: n = 5, roads = [[0, 1, 4], [1, 2, 5], [2, 4, 1], [0, 3, 3], [3, 4, 8]], source = 0, target = 4
Output: 3There are two trips from stop 0 to stop 4. With the coupon on the most expensive leg of each trip:
| Trip | Fares | Fare with the coupon on the dearest leg |
|---|---|---|
| 0 → 1 → 2 → 4 | 4 + 5 + 1 = 10 | 5 |
| 0 → 3 → 4 | 3 + 8 = 11 | 3 |
Without the coupon the trips cost 10 and 11. The best fare is 3: use the coupon on the leg that costs 8.
Input: n = 3, roads = [[1, 0, 2], [1, 2, 1]], source = 0, target = 2
Output: -1No leg leaves stop 0, so stop 2 cannot be reached.
Input: n = 2, roads = [[0, 1, 4]], source = 1, target = 1
Output: 0The rider is already at the destination, so the trip has no legs and costs 0.
1 ≤ n ≤ 30,0000 ≤ len(roads) ≤ 60,0000 ≤ roads[k][0], roads[k][1] < n, and 0 ≤ roads[k][2] ≤ 1,000,000,0000 ≤ source, target < nTrying each leg as the free one, with a shortest-path search each time, makes 60,000 searches of about 90,000 steps each, which is 5.4 billion steps. The coupon is used at most once, and the search only needs to know whether it was used already. That doubles the number of states, and one search is enough.