Payments app~30 min2s · 256 MBtarget O((relays + 1) × m) time, O(n) spaceclassic twin: lc-787shortest-paths
A payments app moves money between banks. A transfer goes one way from one bank to another and charges a fee. A payment may pass through relay banks, and each bank between the sender's bank and the receiver's bank is a relay.
A rule limits the number of relays. The fee team wants the lowest total fee, and when several routes cost the same, the one with the fewest transfers, because each transfer adds delay.
Write cheapest_transfer(n, links, source, target, relays).
0 to n - 1. links[i] = [a, b, fee] is a one-way transfer from bank a to bank b with a fee. A pair of banks may have several links.t transfers has t - 1 relays. A route may use at most relays relays, so at most relays + 1 transfers.[fee, transfers] for the route with the lowest total fee. Among routes with that fee, use the one with the fewest transfers.[0, 0] when source equals target, and [-1, -1] when no allowed route exists.Input: n = 4, links = [[0, 1, 50], [1, 2, 50], [0, 2, 100], [2, 3, 20], [0, 3, 200]], source = 0, target = 3, relays = 2
Output: [120, 2]The solution runs rounds. After round h, fee[b] is the cheapest fee to bank b using at most h transfers. A round reads only the fees of the round before.
| Round (transfers) | Bank 0 | Bank 1 | Bank 2 | Bank 3 |
|---|---|---|---|---|
| 0 | 0 | - | - | - |
| 1 | 0 | 50 | 100 | 200 |
| 2 | 0 | 50 | 100 | 120 |
| 3 | 0 | 50 | 100 | 120 |
Bank 3 first reaches 120 in round 2, through 0 -> 2 -> 3. Round 3 finds the same fee through 0 -> 1 -> 2 -> 3, but with more transfers, so the answer is [120, 2].
Input: n = 4, links = [[0, 1, 50], [1, 2, 50], [0, 2, 100], [2, 3, 20], [0, 3, 200]], source = 0, target = 3, relays = 0
Output: [200, 1]No relay is allowed, so only the direct transfer from bank 0 to bank 3 can be used.
Input: n = 4, links = [[0, 1, 50], [1, 2, 50], [0, 2, 100], [2, 3, 20], [0, 3, 200]], source = 3, target = 0, relays = 2
Output: [-1, -1]No link leaves bank 3, so bank 0 cannot be reached.
1 ≤ n ≤ 1,000, and 0 ≤ len(links) ≤ 5,000links[i] = [a, b, fee] with 0 ≤ a, b < n and 1 ≤ fee ≤ 1,000,0000 ≤ source, target < n, and 0 ≤ relays ≤ 100A route can have up to 101 transfers, and a bank can have many outgoing links, so the number of routes is huge. One round that tries every link takes 5,000 steps, and 101 rounds take about 505,000 steps.