Bank app~30 min2s · 256 MBtarget O(n x m) time, O(n) spaceshortest-paths
A bank moves money between internal ledgers, numbered from 0, through one-way moves. Each move has a fee in units. Some moves pay cashback, which counts as a negative fee.
A chain of moves may return to a ledger and go round again. If one trip round a loop has a negative total, repeating it makes the cost fall below any limit. Auditors start from one ledger. They want every ledger whose cost, from that start, can be pushed down for ever.
Write unbounded_accounts(n, moves, source).
n ledgers, numbered from 0 to n - 1.moves[i] is [from, to, fee]: a one-way move. The fee may be negative. A move may join a ledger to itself.source can reach it at a total cost below any given number.Input: n = 6, moves = [[0,1,2],[1,2,-3],[2,1,1],[2,3,4],[3,4,1],[5,3,-1]], source = 0
Output: [1, 2, 3, 4]Moves 1 to 2 and 2 to 1 form a loop with total -3 + 1 = -2, and ledger 1 is reachable from ledger 0. Each trip round the loop lowers the cost by 2. Ledgers 3 and 4 can be reached from ledger 2, so their cost falls too. Ledger 5 cannot be reached from ledger 0.
The solution runs rounds of lowering costs. After n - 1 rounds, costs would be final without a paying loop. The table shows the costs of the first rounds.
| After round | Ledger 0 | Ledger 1 | Ledger 2 | Ledger 3 | Ledger 4 | Ledger 5 |
|---|---|---|---|---|---|---|
| 0 | 0 | none | none | none | none | none |
| 1 | 0 | 0 | -1 | 3 | 4 | none |
| 2 | 0 | -2 | -3 | 1 | 2 | none |
| 3 | 0 | -4 | -5 | -1 | 0 | none |
| 4 | 0 | -6 | -7 | -3 | -2 | none |
Costs of ledgers 1 to 4 keep falling. A further round of lowering marks ledgers 1 and 2, and the marks spread to 3 and 4. Ledger 0 is not marked.
Input: n = 3, moves = [[0,1,1],[1,2,1],[2,0,1]], source = 0
Output: []The loop costs 3 in total, so going round never helps.
Input: n = 4, moves = [[0,1,1],[2,3,-5],[3,2,1]], source = 0
Output: []Ledgers 2 and 3 form a loop that pays 4 each time, but ledger 0 cannot reach them.
1 ≤ n ≤ 500 and 0 ≤ source < n0 ≤ moves.length ≤ 3,000, and each move is [from, to, fee] with 0 ≤ from, to < n and -1,000 ≤ fee ≤ 1,000Listing every simple loop can mean a number of loops that grows faster than any power of n. For 500 ledgers with 3,000 moves that is far beyond reach. Running rounds over all moves costs n × m = 500 × 3,000 = 1.5 × 10^6 steps for each phase.