PATH-P6

Cheapest routes in a DAG

Practice 6 of 7Shortest paths9 tests

The problem

The lines form a directed acyclic graph (a DAG): following lines, you can never come back to a station. Times can be negative. Return a pair of lists (dist, ways). dist[v] is the least total time from s to v, or None if v cannot be reached. ways[v] is how many different routes from s to v take exactly that time, as the remainder after dividing by 1,000,000,007 (0 if v cannot be reached). Two routes are different if they use a different line at any point, so a line listed twice gives two routes.

dag_routes(4, [(0, 1, 1), (0, 2, 1), (1, 3, 1),
               (2, 3, 1), (0, 3, 3)], 0)
# ([0, 1, 1, 2], [1, 1, 1, 2])

Limits

  • Up to 100,000 stations and about 250,000 lines.
  • Routes can be 100,000 lines long, so recursion is too deep. Aim for O(V + E). The big tests have 4 seconds each.

Builds on PATH-6 Shortest paths in DAGs.

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.

9 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2RefundsNot run
3Stations before the startNot run
4Ties count togetherNot run
5A cheaper way replaces the countNot run
6A line given twiceNot run
740 layers of twoNot run
8A chain of 100,000, listed backwardsNot run
9100,000 stations, 250,000 linesNot run