Payments app~40 min2s · 256 MBtarget O((n + m) log n) time, O(n + m) spacedijkstra
A payments app moves money between settlement hubs over payment rails. A rail goes one way between two hubs. It takes a share of the amount it carries, in basis points, plus a fixed fee.
A customer sends a sum from one hub to another, and may pass through several hubs on the way. The app wants the route that delivers the most.
Write best_delivery(n, froms, tos, rates, flats, amount, start, goal).
0 to n - 1. Rail i goes from froms[i] to tos[i]. start and goal are different.x units over rail i costs a fee of ceil(x * rates[i] / 10000) + flats[i], and x - fee units arrive. A rail can only be used when at least 1 unit arrives.amount units at hub start. A route may pass through any hubs, and each rail takes its fee from what has arrived so far.goal, or -1 if no route delivers anything.Input: n = 5, froms = [0, 0, 1, 2, 1, 3, 2], tos = [1, 2, 3, 3, 2, 4, 4], rates = [100, 50, 200, 10, 0, 25, 300], flats = [5, 20, 0, 10, 2, 1, 0], amount = 10000, start = 0, goal = 4
Output: 9884The trace always extends the hub that holds the most money.
| Pop | Hub | Amount held | Rails tried: amount that arrives |
|---|---|---|---|
| 1 | 0 | 10000 | to 1: 9895; to 2: 9930 |
| 2 | 2 | 9930 | to 3: 9910; to 4: 9632 |
| 3 | 3 | 9910 | to 4: 9884 |
| 4 | 1 | 9895 | to 3: 9697 (no better); to 2: 9893 (no better) |
| 5 | 4 | 9884 | the goal: stop |
The route 0, 2, 3, 4 delivers 9,884 units. The shorter route 0, 2, 4 loses 298 units to the 300 basis point rail and delivers only 9,632, so more hops can be better.
Input: n = 3, froms = [0, 1], tos = [1, 2], rates = [0, 0], flats = [600, 500], amount = 1000, start = 0, goal = 2
Output: -1The first rail leaves 400 units, and the second rail's fee of 500 is more than that. Nothing arrives, so the output is -1.
Input: n = 3, froms = [0, 0, 1], tos = [2, 1, 2], rates = [1000, 0, 0], flats = [0, 10, 10], amount = 500, start = 0, goal = 2
Output: 480The direct rail takes 10 per cent, so 450 units arrive. Going through hub 1 costs 20 in fixed fees, so 480 arrive. The output is 480.
2 ≤ n ≤ 100,000 (hubs); 1 ≤ froms.length ≤ 200,000 (rails); tos, rates and flats have the same length0 ≤ froms[i], tos[i] < n0 ≤ rates[i] ≤ 10,000 (basis points: 10,000 is the whole amount)0 ≤ flats[i] ≤ 1,000,000 (units)1 ≤ amount ≤ 1,000,000,000 (units); start ≠ goalTrying every route is hopeless in a network this size. Repeating "relax every rail" until nothing changes needs up to n rounds of m rails, about 2 × 10^10 steps. A priority queue can finish each hub once, richest first, in O((n + m) log n) steps. The fee product reaches 10^9 × 10^4 = 10^13, which needs 64-bit integers.