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
- 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 | Over capacity | Not run | |
| 3 | Flow lost at a station | Not run | |
| 4 | A negative flow | Not run | |
| 5 | The empty flow | Not run | |
| 6 | Flow into the source | Not run | |
| 7 | A loop of flow | Not run | |
| 8 | Repeated lines and a line to itself | Not run | |
| 9 | Wrong number of values | Not run | |
| 10 | 100,000 stations | Not run | |
| 11 | 100,000 stations, one wrong number | Not run |