The problem
A railway network has n stations, numbered 0 to n − 1, and a list of direct lines. Each line (u, v) joins stations u and v, and trains run both ways. Return a list with one answer for each question (u, v) in queries: True if a line joins u and v directly, False if not.
edges = [(0, 1), (1, 2), (2, 3), (3, 0), (1, 3)]
direct_lines(5, edges, [(0, 1), (1, 0), (0, 2), (4, 1)])
# [True, True, False, False]
The same line may be listed more than once. No line joins a station to itself, so a question (u, u) is always False.
Limits
- Up to 200,001 stations, 200,000 lines and 200,000 questions.
- One station may have 200,000 lines. Reading through a list of its neighbours for every question is far too slow. The big tests have 3 seconds each.
Builds on GRPH-1 Representing graphs.
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 | No lines | Not run | |
| 3 | A vertex and itself | Not run | |
| 4 | A line given twice | Not run | |
| 5 | No questions | Not run | |
| 6 | Both directions, many times | Not run | |
| 7 | 1,000 vertices | Not run | |
| 8 | A hub with 200,000 lines | Not run | |
| 9 | 100,000 vertices, 200,000 lines | Not run |