Payments app~30 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacedijkstra
You work on a payments network. A payment moves between n processors, numbered 0 to n - 1, over one-way links. Every link charges a fee in units, and the fee is always at least 1.
A payment goes from a source processor to a target processor, and its total fee is the sum of the fees of the links it uses. Several routes can have the same lowest total fee. Operators want to know how balanced the traffic can be.
Your team lead asks: "What is the lowest fee, how many routes reach it, and how few links does such a route need?" The network can have 50,000 processors and 100,000 links.
Write cheapest_routes(n, links, source, target).
links[k] = [a, b, fee] is a one-way link from a to b with the given fee, which is at least 1. Links can repeat, and every copy is a different link.source to target, where each link starts where the previous one ended.1,000,000,007, and the fewest links among those routes.source = target, the lowest fee is 0 with 1 route of 0 links. When target cannot be reached, return [-1, 0, -1].Input: n = 5, links = [[0, 1, 2], [0, 2, 1], [2, 1, 1], [1, 3, 3], [2, 3, 4], [3, 4, 1], [1, 4, 5]], source = 0, target = 4
Output: [6, 3, 3]All the routes from processor 0 to processor 4, from the cheapest:
| Route | Links | Total fee |
|---|---|---|
| 0 → 1 → 3 → 4 | 3 | 6 |
| 0 → 2 → 1 → 3 → 4 | 4 | 6 |
| 0 → 2 → 3 → 4 | 3 | 6 |
| 0 → 1 → 4 | 2 | 7 |
| 0 → 2 → 1 → 4 | 3 | 7 |
The lowest fee is 6. Three routes reach it, and the shortest of them uses 3 links. The result is [6, 3, 3].
Input: n = 3, links = [[1, 0, 2], [1, 2, 1]], source = 0, target = 2
Output: [-1, 0, -1]No link leaves processor 0, so processor 2 cannot be reached.
Input: n = 2, links = [[0, 1, 4]], source = 1, target = 1
Output: [0, 1, 0]The source is the target. The lowest fee is 0, with one route that uses no links.
1 ≤ n ≤ 50,0000 ≤ len(links) ≤ 100,0000 ≤ links[k][0], links[k][1] < n, and 1 ≤ links[k][2] ≤ 1,000,000,0000 ≤ source, target < nThe number of simple routes can be exponential. A chain of 24,999 pairs of processors, each linked to both of the next pair, has 2 to the power 24,999 routes. Listing them is impossible. Fees are positive, so a cheapest route never repeats a processor, and a heap can settle the processors one at a time in order of fee.