PATH-P5

Routes between asked pairs

Practice 5 of 7Shortest paths11 tests

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

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2No linesNot run
3Lines given twice, and a loopNot run
4A refundNot run
5A loop below 0Not run
6A refund from a station to itselfNot run
7A route through every stationNot run
8Free lines both waysNot run
9150 stations, 10,000 linesNot run
10150 stations, every pair joinedNot run
11150 stations with one bad loopNot run