The problem
Fares can be negative. For each asked pair (i, j), return the stations of a cheapest route from i to j, in order, starting with i and ending with j; a station’s route to itself is [i]. Return None for a pair with no route. If any loop of fares adds up to less than 0, return None instead of a list, because then some pairs have no cheapest route.
cheapest_routes(3, [(0, 1, 4), (0, 2, 5), (2, 1, -3)],
[(0, 1), (1, 0), (2, 2)])
# [[0, 2, 1], None, [2]]: 0 -> 2 -> 1 costs 5 - 3 = 2
cheapest_routes(3, [(0, 1, 1), (1, 2, -2), (2, 0, 0)], [(0, 2)])
# None: the loop 0 -> 1 -> 2 -> 0 costs -1
Any cheapest route passes: the tests report the cost of each route you give, or what is wrong with it. Lesson 5 describes the table of first steps that makes this cheap.
Limits
- Up to 150 stations, about 22,500 fares and 300 asked pairs.
- Aim for O(n³) (n · n · n steps) for the tables, then a few steps per route. The big tests have 5 seconds each.
Builds on PATH-5 Floyd-Warshall.
Continue on a laptop
Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.
Need a hint?0 of 3 opened
- Hint 1Nudge
- Hint 2Approach Open hint 1 first
- Hint 3Pseudocode Open hint 2 first
- Worked solutionlast resort Opens after all 3 hints
Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.
| # | Test | Result | Reads · time |
|---|---|---|---|
| 1 | The example | Not run | |
| 2 | No lines | Not run | |
| 3 | Lines given twice, and a loop | Not run | |
| 4 | A refund | Not run | |
| 5 | A loop below 0 | Not run | |
| 6 | A refund from a station to itself | Not run | |
| 7 | A route through every station | Not run | |
| 8 | Free lines both ways | Not run | |
| 9 | 150 stations, 10,000 lines | Not run | |
| 10 | 150 stations, every pair joined | Not run | |
| 11 | 150 stations with one bad loop | Not run |