FLOW-P2

The most trains

Practice 2 of 5Network flow9 tests

The problem

Return the value of a maximum flow from s to t: the most trains an hour that can leave s and reach t, keeping both rules of P1.

lines = [(0, 1, 10), (0, 2, 10), (1, 2, 2),
         (1, 3, 4), (1, 4, 8), (2, 4, 9),
         (4, 3, 6), (3, 5, 10), (4, 5, 10)]
max_flow(6, lines, 0, 5)      # 19
max_flow(4, [(0, 1, 1), (0, 2, 1), (1, 2, 1),
             (1, 3, 1), (2, 3, 1)], 0, 3)   # 2

In the second network, the path 0 → 1 → 2 → 3 sends one train, and then no path is left in the network itself. The residual graph of lesson 2 still has a path, because it can undo the train on 1 → 2.

Limits

  • Up to 50 stations and 300 lines, capacities up to 100. Any augmenting-path method is fast enough.

Builds on FLOW-2 Ford-Fulkerson.

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
2The diamondNot run
3No way throughNot run
4Repeated linesNot run
5Lines both waysNot run
6Lines of capacity 0 and loopsNot run
7Sink is not the last stationNot run
8A path that blocks anotherNot run
950 stationsNot run