Online store~35 min2s · 256 MBtarget O(n^2 x m) time, O(n^2) spaceshortest-paths
A shop runs loyalty programmes, numbered from 0. An offer lets a customer swap points in one programme for points in another. An offer says that give points of the first programme buy get points of the second.
A customer can chain offers into a loop that returns to the first programme. The loop gains when the customer ends with more points than they started with. Each swap has a fixed cost in time, so you want the fewest swaps in a gaining loop.
Write shortest_profit_loop(n, offers).
n programmes, numbered from 0 to n - 1.offers[i] is [from, to, give, get]: a one-way offer. give points of from buy get points of to, so the rate is get / give.Input: n = 4, offers = [[0,1,1,2],[1,2,1,3],[2,0,5,1],[0,3,1,1],[3,0,3,2]]
Output: 3The loop 0, 1, 2, 0 has rates 2, 3 and 1/5, so one point becomes 2 × 3 × 0.2 = 1.2 points. The loop 0, 3, 0 has rates 1 and 2/3, which gives 0.667, a loss.
The solution lets amounts grow by one swap at a time. The table shows, for each programme, how much of itself one point becomes after exactly k swaps, as the best choice of offers.
| After k swaps | Programme 0 | Programme 1 | Programme 2 | Programme 3 |
|---|---|---|---|---|
| 1 | none | none | none | none |
| 2 | 0.6667 | none | none | 0.6667 |
| 3 | 1.2000 | 1.2000 | 1.2000 | none |
After 3 swaps, a programme holds 1.2 points of itself, more than 1. So the answer is 3.
Input: n = 2, offers = [[0,1,1,2],[1,0,3,1]]
Output: 0The first offer doubles the points, and the second returns a third of them. One point becomes 2/3, a loss.
Input: n = 2, offers = [[0,1,1,3],[1,0,2,1]]
Output: 2One point becomes 3 points, and 2 points become 1, so 3 points become 1.5. The loop of 2 swaps gains.
1 ≤ n ≤ 400 ≤ offers.length ≤ 800, and each offer is [from, to, give, get] with 0 ≤ from, to < n and 1 ≤ give, get ≤ 400Listing every simple loop can mean more loops than any power of n, so a dense table of 40 programmes is out of reach. Extending the best amounts one swap at a time costs n × m per swap. For at most n swaps that is 40 × 40 × 800 = 1.3 × 10^6 steps.