PATH-P2

Fewest lines to reverse

Practice 2 of 7Shortest paths12 tests

The problem

Every line in this network runs one way: (u, v) means trains go from u to v only. The railway can reverse any line, so that trains run from v to u instead. Return the fewest lines that must be reversed so that a train can go from station s to station t. Return -1 if even reversing lines cannot join them.

lines = [(0, 1), (2, 1), (2, 3), (4, 3)]
fewest_reversals(5, lines, 0, 4)              # 2
fewest_reversals(3, [(0, 1), (1, 2)], 0, 2)   # 0
fewest_reversals(4, [(0, 1), (2, 3)], 0, 3)   # -1

In the first call, go 0 → 1 along its line, then reverse 2 → 1 to go 1 → 2, then 2 → 3, then reverse 4 → 3. A line may be listed more than once, and a line may join a station to itself.

Limits

  • Up to 100,000 stations and 200,000 lines.
  • Aim for O(V + E). The big tests have 4 seconds each.

Builds on PATH-2 0-1 BFS.

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.

12 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Already a routeNot run
3The start is the endNot run
4Not joined at allNot run
5The long way is freeNot run
6Front, not backNot run
7A loop and a line given twiceNot run
8Every line the wrong wayNot run
91,000 stationsNot run
10100,000 stations, 200,000 linesNot run
11A chain of 100,000, every line backwardsNot run
12Two halvesNot run