Network Flows, LP & Complexity Classes
Pushing water through pipes, optimising with constraints — and where efficient algorithms run out.
- compute a max flow with augmenting paths and read off a min cut
- model bipartite matching as a flow problem
- describe a linear program and why optima occur at corners
- explain P, NP, NP-complete and reductions in your own words
Before you start
The official Week 11 notes were not reachable when this book was assembled, so this chapter is written from the standard treatment of network flows, linear programming and complexity classes. The ideas and algorithms are the usual ones, but check the exact depth, notation and examples against the official PDSA material and lectures.
Flow networks
A flow network is a directed graph with a source s, a sink t and a non-negative capacity c(u, v) on each edge — pipes in a water system, links in a network, roads with vehicle limits. A flow assigns each edge an amount f(u, v) such that:
| Rule | Meaning |
|---|---|
| Capacity | 0 ≤ f(u, v) ≤ c(u, v) |
| Conservation | for every vertex other than s and t: total flow in = total flow out |
The value of a flow is the net amount leaving s. The maximum flow problem asks for a flow of the largest value.
Augmenting paths and the residual graph
Ford–Fulkerson repeatedly finds a path from s to t that still has spare capacity and pushes flow along it. A greedy choice of paths can get stuck short of the optimum, so we allow undoing earlier flow: for each edge u → v carrying f out of capacity c, the residual graph has a forward edge with capacity c − f (room left) and a backward edge v → u with capacity f (flow we may cancel). An augmenting path is any s → t path in the residual graph; push the bottleneck (minimum residual capacity along it).
Choosing the augmenting path with the fewest edges (BFS) guarantees at most O(V·E) augmentations, giving O(V·E²) total time — regardless of the capacity values. Choosing paths arbitrarily can take time proportional to the capacities themselves.
What is the maximum flow through these two edge-disjoint routes?
# two disjoint routes from s to t with capacities 3 and 5 on the bottlenecks routes = [[7, 3, 9], [5, 6, 8]] print(sum(min(r) for r in routes))
Why does the residual graph contain backward edges?
Max-flow min-cut theorem
An s–t cut splits the vertices into a set A containing s and the rest B containing t. Its capacity is the total capacity of edges going from A to B. Every flow must cross the cut, so flow value ≤ capacity of any cut.
The value of a maximum flow equals the capacity of a minimum s–t cut. When Ford–Fulkerson stops (no augmenting path), the set A of vertices reachable from s in the residual graph is a minimum cut.
A network has a cut of capacity 14 and a cut of capacity 17. The maximum flow is…
When Edmonds–Karp ends because BFS cannot reach t in the residual graph, the reachable set is…
Applications
Many problems reduce to max flow: bipartite matching (give every edge capacity 1, add a source linked to the left side and a sink linked to the right side — the max flow equals the size of a maximum matching), airline scheduling, image segmentation, baseball elimination, and finding the number of edge-disjoint paths.
Linear programming
Linear programming (LP) optimises a linear objective subject to linear constraints. Example — a bakery makes x loaves and y cakes: maximise profit 3x + 5y subject to x + 2y ≤ 14 (oven hours), 3x − y ≥ 0, x − y ≤ 2, x, y ≥ 0.
Each constraint cuts the plane with a line, so the feasible region is a convex polygon (in higher dimensions, a polytope). The objective is a family of parallel lines; the best value is reached at a vertex (corner) of the region. The simplex algorithm walks from vertex to vertex improving the objective; interior-point methods cross the inside. Both solve LPs efficiently in practice, and LP is solvable in polynomial time.
If variables must be integers (you cannot bake 2.5 cakes), the problem is called an integer linear program (ILP) — and it becomes NP-hard. Rounding the LP answer may not be optimal or even feasible.
Maximum flow is a special LP: variables f(u, v), constraints are capacity and conservation, objective is the flow out of s. Shortest paths and matching are LPs too. Remarkably, for these network problems an optimal solution with integer values always exists when capacities are integers.
The optimum of a linear program (if it exists and is bounded) is attained at…
What makes integer programming hard compared with ordinary LP?
Easy and hard problems: P, NP and NP-completeness
Almost every algorithm in this course runs in polynomial time — O(n^k) for some constant k. We call such problems tractable. Others seem to require exponential time. Complexity theory classifies problems, not programs.
| Class | Informal meaning | Examples |
|---|---|---|
| P | solvable in polynomial time | sorting, shortest paths, MST, max flow, LP |
| NP | a proposed solution can be checked in polynomial time | everything in P, plus SAT, Hamiltonian cycle, subset sum, vertex cover |
| NP-complete | the hardest problems in NP: every NP problem reduces to them | SAT, 3-SAT, clique, independent set, vertex cover, travelling salesman (decision version) |
| NP-hard | at least as hard as NP-complete (need not be in NP) | optimisation versions, e.g. travelling salesman minimisation |
Verifying is easier than finding
Given a puzzle (a Sudoku or a subset-sum instance), verifying a claimed answer is quick; discovering one may require searching a huge space. NP is exactly the set of problems whose yes-answers have short, quickly checkable certificates.
Reductions
Problem A reduces to B (written A ≤ B) if an algorithm for B could be turned, with polynomial extra work, into an algorithm for A. If we have a fast algorithm for B, we get one for A. To show a problem is hard, reduce a known hard problem to it. Example: independent set and vertex cover are complementary — a set S is independent exactly when all other vertices form a vertex cover, so a fast algorithm for one gives a fast algorithm for the other.
Is every problem whose solution can be quickly checked also quickly solvable? Nobody knows — it is the most famous open problem in computer science (and one of the Clay Millennium Prize problems). Almost everyone believes P ≠ NP. If any NP-complete problem had a polynomial-time algorithm, they all would.
Exact exponential search for small inputs, approximation algorithms with provable guarantees (e.g. vertex cover within a factor 2), heuristics, or special cases that are easier (trees, small parameters).
Which statement correctly describes class NP?
You prove that SAT (NP-complete) reduces to your problem X in polynomial time. This shows X is…
Pick all that are in P (as far as we know).
Chapter challenge — Week 11
In a flow network, 'conservation' means…
What does this program print?
# the network drawn in the visualiser: s=0, a=1, b=2, c=3, d=4, t=5
edges = [(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)]
n, s, t = 6, 0, 5
from collections import deque
def max_flow(n, edges, s, t):
cap = [[0] * n for _ in range(n)]
for u, v, c in edges:
cap[u][v] += c
flow = 0
while True:
parent = [-1] * n
parent[s] = s
q = deque([s])
while q and parent[t] == -1: # BFS in the residual graph
u = q.popleft()
for v in range(n):
if parent[v] == -1 and cap[u][v] > 0:
parent[v] = u
q.append(v)
if parent[t] == -1:
break # no augmenting path left
# bottleneck along the path
b, v = float("inf"), t
while v != s:
b = min(b, cap[parent[v]][v])
v = parent[v]
v = t
while v != s:
cap[parent[v]][v] -= b # use up forward capacity
cap[v][parent[v]] += b # create backward (undo) capacity
v = parent[v]
flow += b
return flow, cap
value, residual = max_flow(n, edges, s, t)
print(value)A cut has edges leaving A with capacities 5, 7 and 3. What is the capacity of the cut?
One round of Edmonds–Karp.
Which is known to be solvable in polynomial time?
Which statements are true?
In a feasible region of a linear program, the best value of a linear objective occurs at…
Practice on LeetCode
LeetCode has almost no pure max-flow problems, so these are the closest relatives: bipartite structure and NP-hard-flavoured search problems that need pruning. Max-flow practice is linked below.
Try each problem first with a brute-force idea and estimate its cost, then improve it using this chapter's technique. Links open LeetCode in a new tab; all problems listed are free. Levels follow LeetCode's own labels.
| Problem | Level | Practises | |
|---|---|---|---|
| Is Graph Bipartite? ↗ | Medium | the structure behind bipartite matching | |
| Possible Bipartition ↗ | Medium | two-colouring with constraints | |
| Subsets ↗ | Medium | 2ⁿ search space — why brute force explodes | |
| Combination Sum ↗ | Medium | exponential search with pruning | |
| Partition to K Equal Sum Subsets ↗ | Medium | NP-hard in general; backtracking + pruning | |
| N-Queens ↗ | Hard | constraint search, a classic hard-search problem |
Beyond LeetCode
- CSES — Download Speed ↗ — plain maximum flow
- CSES — Police Chase ↗ — min cut: print the edges of a minimum cut
- CSES — School Dance ↗ — bipartite matching via flow
- CSES — Distinct Routes ↗ — edge-disjoint paths via flow
Key takeaways
- A flow obeys capacity and conservation constraints; the max flow is found by repeatedly augmenting along s–t paths in the residual graph (Edmonds–Karp: BFS paths, O(V·E²)).
- Max-flow = min-cut: the best flow equals the capacity of the cheapest s–t cut. Matching and many other problems reduce to flow.
- Linear programs optimise linear objectives over polytopes; optimum at a corner; polynomial-time solvable. Requiring integers (ILP) makes them NP-hard.
- P: solvable fast. NP: solutions verifiable fast. NP-complete: hardest in NP — a fast algorithm for one gives one for all. Whether P = NP is open.
- Reductions transfer hardness: reduce a known hard problem to yours.