Ad platform~30 min2s · 256 MBtarget O(k m) time, O(n) spaceclassic twin: lc-787shortest-paths
An ad team moves budget between n campaigns, numbered from 0. A transfer goes one way, from a campaign to another. It has a fee, in units, and some transfers pay a credit, which is a negative fee.
The team wants to move budget from one campaign to another using at most k transfers. A route may pass through a campaign more than once, so a loop of transfers that pays a net credit can be worth repeating.
Write cheapest_budget_move(n, moves, source, target, k).
moves[i] is [a, b, fee]: a transfer from campaign a to campaign b with the given fee. The fee may be negative.k transfers, each starting where the last ended, from source. It may be empty when k is 0.source that ends at target. Return 1,000,000,000,000 when no such route exists.Input: n = 4, moves = [[0,1,5],[1,2,-3],[2,1,1],[2,3,4],[0,3,20]], source = 0, target = 3, k = 5
Output: 4The loop between campaigns 1 and 2 costs -3 + 1 = -2 each time round. With 5 transfers the route 0 to 1 to 2 to 1 to 2 to 3 costs 5 - 3 + 1 - 3 + 4 = 4. Each round of the search allows one more transfer. The table gives the cheapest known cost to each campaign, with - for none yet.
| Transfers allowed | Campaign 0 | Campaign 1 | Campaign 2 | Campaign 3 |
|---|---|---|---|---|
| 0 | 0 | - | - | - |
| 1 | 0 | 5 | - | 20 |
| 2 | 0 | 5 | 2 | 20 |
| 3 | 0 | 3 | 2 | 6 |
| 4 | 0 | 3 | 0 | 6 |
| 5 | 0 | 1 | 0 | 4 |
The answer is the cost of campaign 3 in the last row.
Input: n = 3, moves = [[0,1,2]], source = 0, target = 2, k = 4
Output: 1000000000000No transfer leads to campaign 2, so there is no route.
Input: n = 3, moves = [[1,2,-3],[2,1,1]], source = 1, target = 1, k = 3
Output: -2The empty route costs 0, but one trip round the loop, 1 to 2 and back to 1, costs -3 + 1 = -2 and uses 2 transfers.
1 ≤ n ≤ 2,000, and 0 ≤ source, target < n0 ≤ moves.length ≤ 8,000, each fee is between -1,000 and 1,0000 ≤ k ≤ 1,000Trying every route of up to k transfers can mean a choice among many transfers at each step, so the number of routes grows exponentially with k. Keeping the cheapest cost to each campaign, one round for each allowed transfer, costs k × m = 1,000 × 8,000 = 8 × 10^6 steps. Costs stay below 10^6 in size, but the unreachable marker 10^12 needs 64 bits.