Ride-hailing app~30 min2s · 256 MBtarget O((stops + 1) × m) time, O(n) spaceclassic twin: lc-787shortest-paths
A ride-hailing app sells shuttle journeys between hubs, numbered from 0 to n - 1. Each connection runs one way from one hub to another and has a fare. A journey may change at hubs on the way, and each hub between the start and the end counts as one stop.
A traveller wants the cheapest journey from a start hub to an end hub with at most a given number of stops. The cheapest route overall may use too many stops, and then it is not allowed.
Write cheapest_with_stops(n, roads, source, target, stops).
roads[i] is [from, to, fare]: a one-way connection. Hubs are numbered from 0 to n - 1.source to target with k connections has k - 1 stops. A direct connection has 0 stops.stops stops, or -1 when no such route exists. When source equals target, the answer is 0.Input: n = 4, roads = [[0,1,100], [1,2,100], [0,2,500], [2,3,50], [1,3,600]], source = 0, target = 3, stops = 1
Output: 550The cheapest route overall is 0, 1, 2, 3 with a fare of 250, but it has 2 stops. With 1 stop, 0, 2, 3 costs 550 and 0, 1, 3 costs 700.
The solution runs rounds. Round k holds the cheapest fare to each hub using at most k connections. A route with 1 stop has 2 connections, so 2 rounds are needed.
| After round | Fare to hub 0 | hub 1 | hub 2 | hub 3 |
|---|---|---|---|---|
| 0 | 0 | none | none | none |
| 1 | 0 | 100 | 500 | none |
| 2 | 0 | 100 | 200 | 550 |
The fare to hub 3 after round 2 is 550. The value 200 at hub 2 comes from 0, 1, 2, which is a route with 2 connections.
Input: n = 4, roads = [[0,1,100], [1,2,100], [0,2,500], [2,3,50], [1,3,600]], source = 0, target = 3, stops = 0
Output: -1With no stop, only a direct connection is allowed, and there is none from hub 0 to hub 3.
Input: n = 4, roads = [[0,1,100], [1,2,100], [0,2,500], [2,3,50], [1,3,600]], source = 0, target = 3, stops = 2
Output: 250With 2 stops, the route 0, 1, 2, 3 is allowed.
1 ≤ n ≤ 1,0000 ≤ roads.length ≤ 10,000, and each road is [from, to, fare] with 0 ≤ fare ≤ 1,000,0000 ≤ stops ≤ 1,000Trying every route with at most stops + 1 connections can visit about d^(stops + 1) routes, where d is the number of roads leaving a hub. For d = 10 and 8 connections that is 10^8 routes. Running one round per connection costs roads.length per round, at most 10,000 × 1,001 = about 10^7 steps.