GRPH-P1

Is there a direct line?

Practice 1 of 7Graphs9 tests

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

  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
2No linesNot run
3A vertex and itselfNot run
4A line given twiceNot run
5No questionsNot run
6Both directions, many timesNot run
71,000 verticesNot run
8A hub with 200,000 linesNot run
9100,000 vertices, 200,000 linesNot run