FLOW-P1

Is this a flow?

Practice 1 of 5Network flow11 tests

The problem

A railway has n stations and one-way lines (u, v, c): at most c trains an hour can run from u to v. A plan gives flow[i] trains an hour on line i. The plan is a flow from the source s to the sink t when it keeps two rules (lesson 1): every line carries between 0 and its capacity, and at every station other than s and t, the trains that arrive equal the trains that leave. Return the value of the flow, the trains leaving s minus the trains arriving at s, or None if a rule is broken.

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)]
flow_value(6, lines,
           [10, 9, 0, 4, 6, 9, 5, 9, 10], 0, 5)   # 19
flow_value(6, lines,
           [10, 9, 0, 4, 6, 9, 5, 9, 11], 0, 5)   # None

In the second call the last line carries 11 on a capacity of 10. Lines may repeat, and a line may join a station to itself. Return None also when flow does not have one number per line.

Limits

  • Up to 100,000 stations and 100,000 lines.
  • Going through every line once per station is too slow. The big tests have 3 seconds each.

Builds on FLOW-1 Flow networks.

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.

11 tests, not run yet
Test results
#TestResultReads · time
1The exampleNot run
2Over capacityNot run
3Flow lost at a stationNot run
4A negative flowNot run
5The empty flowNot run
6Flow into the sourceNot run
7A loop of flowNot run
8Repeated lines and a line to itselfNot run
9Wrong number of valuesNot run
10100,000 stationsNot run
11100,000 stations, one wrong numberNot run