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
- 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 | Already a route | Not run | |
| 3 | The start is the end | Not run | |
| 4 | Not joined at all | Not run | |
| 5 | The long way is free | Not run | |
| 6 | Front, not back | Not run | |
| 7 | A loop and a line given twice | Not run | |
| 8 | Every line the wrong way | Not run | |
| 9 | 1,000 stations | Not run | |
| 10 | 100,000 stations, 200,000 lines | Not run | |
| 11 | A chain of 100,000, every line backwards | Not run | |
| 12 | Two halves | Not run |