Parcel-delivery app~25 min2s · 256 MBtarget O(max_legs x m) time, O(n) spaceshortest-paths
A freight network joins hubs, numbered from 0, with one-way legs. Each leg has a cost in units. A shipment from a source hub to a target hub may use several legs, and each leg adds handling time.
Planners want a table, not one number. For every limit from 1 leg up to a maximum, they want the cheapest cost of a route with at most that many legs. The table shows how much a shipper saves by allowing more legs.
Write cost_ladder(n, legs, source, target, max_legs).
n hubs, numbered from 0 to n - 1.legs[i] is [from, to, cost]: a one-way leg. Several legs may join the same pair, and a cost may be 0.source to target. A route of zero legs exists when source equals target, at cost 0.max_legs numbers. Entry j - 1 is the lowest cost of a route with at most j legs, or -1 when there is no such route.Input: n = 5, legs = [[0,4,900],[0,1,100],[1,2,100],[2,4,300],[1,4,500],[2,3,50],[3,4,40]], source = 0, target = 4, max_legs = 5
Output: [900, 600, 500, 290, 290]With 1 leg only the direct leg works, at 900. With 2 legs, 0, 1, 4 costs 600. With 3 legs, 0, 1, 2, 4 costs 500. With 4 legs, 0, 1, 2, 3, 4 costs 290, and a fifth leg adds nothing.
The solution runs one round for each leg. Round k holds the cheapest cost to each hub with at most k legs. A round reads only the costs of the previous round.
| After round | Hub 0 | Hub 1 | Hub 2 | Hub 3 | Hub 4 |
|---|---|---|---|---|---|
| 0 | 0 | none | none | none | none |
| 1 | 0 | 100 | none | none | 900 |
| 2 | 0 | 100 | 200 | none | 600 |
| 3 | 0 | 100 | 200 | 250 | 500 |
| 4 | 0 | 100 | 200 | 250 | 290 |
| 5 | 0 | 100 | 200 | 250 | 290 |
The cost to hub 4 after each round is the ladder: 900, 600, 500, 290, 290.
Input: n = 3, legs = [[0,1,5]], source = 0, target = 2, max_legs = 3
Output: [-1, -1, -1]Hub 2 has no leg into it, so no route exists for any limit.
Input: n = 2, legs = [[0,1,5]], source = 0, target = 0, max_legs = 2
Output: [0, 0]The source is the target, so a route of zero legs costs 0 for every limit.
1 ≤ n ≤ 1,000, 0 ≤ source < n and 0 ≤ target < n0 ≤ legs.length ≤ 10,000, and each leg is [from, to, cost] with 0 ≤ from, to < n and 0 ≤ cost ≤ 1,000,0001 ≤ max_legs ≤ 60Trying every route of at most max_legs legs can visit about d^max_legs routes for d legs out of each hub. For d = 10 and 60 legs that is 10^60. Running one round for each leg costs the number of legs per round, so at most 60 × 10,000 = 6 × 10^5 steps.