The problem
A railway has n stations and two-way lines between them. A line is a bridge if closing it leaves the network in more separate parts than before. A station is a cut station (an articulation point) if closing it, with all its lines, leaves the stations that remain in more separate parts than before. Return a pair (bridges, cuts): the positions in lines of the bridges, and the cut stations, both in increasing order.
lines = [(0, 1), (0, 2), (1, 2), (2, 3),
(3, 4), (3, 5), (4, 5), (4, 6)]
weak_points(7, lines) # ([3, 7], [2, 3, 4])
weak_points(7, lines + [(3, 2)]) # ([7], [2, 3, 4])
This is lesson 3’s figure, with A to G as 0 to 6. The network may already be in several parts. Two lines may join the same two stations (then neither of them is a bridge), and a line may join a station to itself (it is never a bridge).
Limits
- Up to 100,000 stations and about 120,000 lines.
- The search can go 100,000 levels deep, so recursion is too deep. Closing each line in turn and counting parts again is too slow. The big tests have 4 seconds each.
Builds on CONN-3 Bridges and articulation points.
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 | Two lines between the same stations | Not run | |
| 3 | One line | Not run | |
| 4 | A star | Not run | |
| 5 | Start with one child | Not run | |
| 6 | A ring | Not run | |
| 7 | Two parts, a loop line, a lone station | Not run | |
| 8 | Two triangles sharing a station | Not run | |
| 9 | A path of 100,000 | Not run | |
| 10 | 100,000 random lines | Not run | |
| 11 | A ring with a double line | Not run |