Maximum Flow

Pipes carry water from a reservoir s to a plant t. On this network the most that can arrive is 23 units a second. Three full pipes, of 12, 7 and 4, prove that no plan beats 23. A planner that cannot undo a choice stops at 19.

Pick a planner and press Run. Watch each path fill its pipes. Then we build, piece by piece: the two rules of flow, the residual network, augmenting paths, the min cut, matching and push-relabel.

You need directed graphs, BFS and a little Python. We build the rest from zero.

Based on Chapter 26 of Introduction to Algorithms (CLRS, third edition) by Cormen, Leiserson, Rivest and Stein. The network is the book's Figure 26.1, with v1 to v4 renamed a to d. It builds on Chapter 22, Graph Algorithms. The explanations, toys and devices are our own.

Send water three ways

Capacities are CLRS Figure 26.1. Each pipe shows flow / capacity. Greedy and Ford-Fulkerson try neighbours in the order s, a, b, c, d, t.

Chapter 0

Pipes to the Plant

Fill paths by hand and watch a sensible plan get stuck below the best one

A city has one reservoir, s, and one treatment plant, t. Nine pipes join them through four junctions, a, b, c and d. Each pipe has a capacity: the most water it can carry each second. How much water can reach the plant each second?

A natural plan: find a path from s to t that still has room, fill it, and repeat. Be that planner below. Each button is a path. A press pushes as much water as the path's tightest pipe allows.

Fill paths by hand

Press paths in any order. The small number on each button is the room it has left. A path with no room greys out.

These five buttons are every path from s to t that follows the pipe directions. The network can carry 23.

Press s, a, c, b, d, t, then s, a, c, t, then s, b, d, c, t. You carry 4 + 8 + 7 = 19, and every button greys out. The first path sent 4 units through c → b. That detour sent 4 units from c down to b, though c could send them straight to t. It also filled d → t, the pipe that water from s through b needed. To reach 23, the planner must be able to take a choice back.

This is the maximum flow problem: in a directed graph with capacities, send as much as possible from a source s to a sink t. Cars on roads and packets in a network fit the same form. So does matching people to tasks (Chapter 6).

The failure. Symptom: a path-filling planner reports 19 and stops. Measure: every path must use a → c, d → c or d → t, and those hold 12 + 7 + 4 = 23. A gap between 19 and 23 means the plan is not proven best. Fix: allow undo (Chapter 2), and prove the result with a cut (Chapter 5).

The road

  1. Flow networks: the capacity rule, the conservation rule and the value.
  2. The residual network: room left, and room to undo.
  3. Ford-Fulkerson: push along augmenting paths until none is left.
  4. Edmonds-Karp: shortest paths first, so capacities do not matter.
  5. Max-flow min-cut: the cut that proves the answer.
  6. Bipartite matching: pair students and projects with flow.
  7. Min cut at work: image segmentation and disjoint paths.
  8. Push-relabel: water that runs downhill, one vertex at a time.
  9. Field guide: the table, the checklist, the code.
The planner stops at 19 although 23 is possible. Why?

Chapter 1

Flow Networks: Two Rules and a Value

Set the water on five pipes and find out which plans are legal

Take a smaller network. Pipes s → a and s → b hold 10 each, a cross pipe a → b holds 2, a → t holds 8 and b → t holds 12. A flow network is a directed graph like this one, with a capacity on each edge, a source and a sink.

A plan gives each pipe an amount of water. Call the amount on the pipe from u to v f(u, v), and its capacity c(u, v). The first rule: no pipe carries less than nothing or more than it can hold.

Say it aloud

Zero is at most f of u v, and f of u v is at most c of u v.

0
zero the least a pipe can carry. No pipe runs backward.
f(u, v)
f of u v the water on the pipe from u to v, in units a second.
c(u, v)
c of u v the capacity of that pipe. It is 0 where there is no pipe.
In plain words

For each pipe, check that f(u, v) is not negative and not above c(u, v).

With numbers

The cross pipe has c(a, b) = 2. f(a, b) = 2 is legal. f(a, b) = 3 breaks the rule by 1 unit.

The second rule is about junctions. Water does not appear or vanish at a or b. What flows in, flows out.

Say it aloud

For every vertex u other than s and t, the sum over v of f of v u equals the sum over v of f of u v.

Σv f(v, u)
the sum over v of f of v u all water that flows into u, added over every vertex v.
Σv f(u, v)
the sum over v of f of u v all water that flows out of u.
u ≠ s, t
u is not s or t the rule holds at every junction. The source only sends and the sink only receives.
In plain words

At each junction u, add the water on the pipes into u. Add the water on the pipes out of u. The two totals must be equal.

With numbers

Plan: f(s, a) = 10, f(a, b) = 2, f(a, t) = 8. At a, in is 10 and out is 2 + 8 = 10. The rule holds.

The value of a flow, written |f|, is the net water that leaves s: the total out of s minus any water that flows back into s. The maximum flow problem asks for a legal flow with the largest value.

Set the water on each pipe

Drag each slider. A pipe above its capacity turns red. Each junction shows its water in and out.

A made-up network. Sliders go 3 units past each capacity so that you can break the first rule.

Plan A sends 8 on s → a → t and 10 on s → b → t: |f| = 18. Plan B adds 2 on s → a → b → t: |f| = 20. Both pipes out of s are now full, and 10 + 10 = 20, so no plan can beat 20.

The failure. Symptom: a simulator reports more water at t than leaves s. Measure: at each junction, compute in minus out. Any nonzero value is a leak. Fix: check conservation after every update, as the device does.

Junction v (not s or t) gets 7 units in and sends 5 out. Every pipe is within its capacity. Is this a legal flow?

Chapter 2

The Residual Network: Room Left, and Undo

Draw the stalled plan as arrows of room and find the path that greedy could not see

Go back to the plan that stalled at 19. Pipes s → b and b → d still have room, but no path of pipes with room reaches t. The fix is a second kind of room: room to send less on a pipe that already carries water.

The residual network Gf shows both kinds. For each pipe it draws up to two arrows. A forward arrow shows the room left. A backward arrow shows how much flow you may cancel. Call the room of the arrow from u to v the residual capacity cf(u, v).

Say it aloud

c-f of u v equals c of u v minus f of u v, and c-f of v u equals f of u v.

cf(u, v)
c-f of u v the forward room on the pipe u → v under flow f.
c(u, v)
c of u v the pipe's capacity.
f(u, v)
f of u v the water the pipe carries now.
cf(v, u)
c-f of v u the backward room: how much of f(u, v) you may cancel. It points from v to u.
In plain words

For each pipe u → v, draw a forward arrow with room c(u, v) − f(u, v). Draw a backward arrow v → u with room f(u, v). Leave out any arrow with room 0.

With numbers

Pipe c → b has capacity 9 and carries 4. Forward room cf(c, b) = 9 − 4 = 5. Backward room cf(b, c) = 4.

Pushing 1 unit along the backward arrow b → c means that c sends 1 unit less to b. The water b got from c must now come from somewhere else, and c gains 1 unit to send elsewhere.

Find the hidden path

Switch to the residual view. Grey arrows are room left; purple arrows are undo room. Then press Augment.

The start is the stall of Chapter 0: paths s, a, c, b, d, t (4), s, a, c, t (8) and s, b, d, c, t (7).

In the residual view a path appears: s → b (room 6), the undo arrow b → c (room 4) and c → t (room 5). Its tightest arrow allows 4. Push 4: f(s, b) rises from 7 to 11, f(c, b) falls from 4 to 0, and f(c, t) rises from 15 to 19. Junction b still sends 11 into d, now all from s. The total is 23.

The failure. Symptom: code that searches only forward arrows stops below the maximum, here at 19. Measure: build the residual network and search it from s. If t is reachable, the flow is not maximum. Fix: give every pipe its reverse arrow when you build the graph.

In the residual network, an arrow from v to u has room 5, and there is no pipe v → u. What does it mean?

Chapter 3

Ford-Fulkerson: Push Along Augmenting Paths

Step the method through four paths, one of them through an undo arrow

The Ford-Fulkerson method repeats one move. A path from s to t in the residual network is an augmenting path. Find one, push water along it, and search again.

  1. Start with f(u, v) = 0 on every pipe.
  2. Search the residual network for a path p from s to t.
  3. If there is none, stop. f is a maximum flow (Chapter 5 proves it).
  4. Push the bottleneck of p: add it on forward arrows, subtract it on backward arrows. Go to step 2.

How much can a path carry? Call the path p and the room of each arrow on it cf(u, v).

Say it aloud

c-f of p equals the minimum, over the arrows u v on p, of c-f of u v.

cf(p)
c-f of p the bottleneck: the most the path p can carry.
min(u, v) on p
the minimum over the arrows u v on p the smallest value among the arrows of the path.
cf(u, v)
c-f of u v the room of one arrow on the path, forward or backward.
In plain words

Read the room on each arrow of p. The smallest one is cf(p). Any more water would overfill that arrow.

With numbers

The first path on the big network is s, a, c, b, d, t. Its rooms are 16, 12, 9, 14 and 4. So cf(p) = 4, set by pipe d → t.

Step the method

Each Step pushes the warm path and finds the next one. Switch views to see the arrows the search uses.

The search is depth-first and tries neighbours in the order s, a, b, c, d, t.

PathRooms on the pathPushTotal
s, a, c, b, d, t16, 12, 9, 14, 444
s, a, c, t12, 8, 20812
s, b, c, t13, 4 (undo), 12416
s, b, d, c, t9, 10, 7, 8723

Path three cancels the 4 units of the first path's detour. With integer capacities, each push adds at least 1 unit. So the method stops after at most |f*| pushes, where |f*| is the maximum value. Each search costs O(E) for E pipes, so the total is O(E · |f*|).

The failure. Symptom: a max-flow routine passes small tests but returns too little on others. Measure: after each push, check that the flow on u → v and its reverse entry sum to zero. Fix: every push of b on u → v must also take b off v → u.

An augmenting path has rooms 9, 3 and 7. How much does Ford-Fulkerson push along it?

Chapter 4

Edmonds-Karp: Shortest Paths First

Raise the capacities and watch an unlucky path choice slow down while BFS does not

Ford-Fulkerson does not say which path to pick. A bad pick can be slow. Take four vertices. Pipes s → a, s → b, a → t and b → t each hold C, and a cross pipe a → b holds 1. The maximum is 2C.

An unlucky search alternates two paths: s, a, b, t and s, b, a, t. The second one uses the undo arrow b → a. Each path carries 1 unit, so the run needs 2C pushes. With C = 1,000 that is 2,000 pushes.

Raise C and count the pushes

Drag C, pick a search, then press Run. The bars count pushes on a log scale.

1,000

We force the unlucky choice on purpose, to show the worst case. A depth-first search can fall into it on graphs like this one.

Edmonds-Karp fixes the pick: always push along a shortest augmenting path, counted in arrows, found by BFS (Chapter 22). Here BFS finds s, a, t and s, b, t first. That is 2 pushes for any C.

Why does BFS help on every network? CLRS proves two facts. The BFS distance from s to each vertex never shrinks from one push to the next. And so each pipe can be the bottleneck at most V/2 times. Call the number of vertices V and the number of pipes E.

Say it aloud

The number of pushes is at most E times V over 2.

pushes
pushes how many augmenting paths Edmonds-Karp uses before it stops.
E
E the number of pipes. Each push fills at least one of them.
V/2
V over 2 how often one pipe can be the bottleneck. V is the number of vertices.
In plain words

Each push fills the arrow that is its bottleneck. Before that arrow can be the bottleneck again, its distance from s must grow by 2. Distances stop at V, so each of the E pipes gets that role at most V/2 times.

With numbers

The big network has V = 6 and E = 9. The bound is 9 × 3 = 27 pushes. Edmonds-Karp uses 3: s, a, c, t (12), s, b, d, t (4) and s, b, d, c, t (7).

Each BFS costs O(E), so Edmonds-Karp runs in O(V E2). The capacities do not appear in the bound. For V = 1,000 and E = 10,000, the push bound is 5,000,000 whatever the capacities are.

The failure. Symptom: max flow takes minutes on a graph with large capacities. Measure: count pushes. If the count grows with the capacities, the search is not shortest-first. Fix: find each path with BFS.

In the four-vertex network, set C = 500. How many pushes do the unlucky choice and Edmonds-Karp need?

Chapter 5

Max-Flow Min-Cut: The Proof in Three Pipes

Move junctions between two sides and find the cut whose capacity equals the flow

How do we know that 23 is the most? Split the vertices in two, with s on one side and t on the other. Every unit of water must cross between the sides.

An s-t cut (S, T) splits the vertices into a set S that holds s and a set T that holds t. Its capacity is the total capacity of the pipes that go from S to T.

Say it aloud

c of S T equals the sum, over u in S and v in T, of c of u v.

c(S, T)
c of S T the capacity of the cut, in units a second.
Σu ∈ S, v ∈ T
the sum over u in S and v in T add one term for each pipe that starts in S and ends in T.
c(u, v)
c of u v the capacity of that pipe.
In plain words

List the pipes that cross from S to T. Add their capacities. Pipes that cross from T back to S add nothing.

With numbers

S = {s, a}. The pipes from S to T are s → b (13) and a → c (12). So c(S, T) = 25. Pipe b → a goes from T to S and does not count.

Now measure the water that crosses the same cut. Count pipes from S to T as plus and pipes from T to S as minus. Call this net crossing f(S, T).

Say it aloud

The value of f equals f of S T, and f of S T is at most c of S T.

|f|
the value of f the net water that leaves s.
f(S, T)
f of S T the net water across the cut: S to T minus T to S.
c(S, T)
c of S T the capacity of the cut.
In plain words

Junctions keep nothing, so the net water across any cut equals |f|. Forward pipes carry at most their capacity and backward pipes only subtract, so f(S, T) is at most c(S, T).

With numbers

Take the flow of 23 and S = {s, a}: f(s, b) = 11 plus f(a, c) = 12, minus f(b, a) = 0, gives 23. That is at most c(S, T) = 25.

Draw the cut

Toggle which junctions sit with s. Pink pipes cross from S to T. The flow is the maximum flow of 23.

There are 16 cuts, one for each choice of sides for a, b, c and d. Their capacities run from 23 to 62.

One cut hits 23 exactly, and Ford-Fulkerson hands it to you when it stops. Let S be every vertex the last search still reaches: {s, a, b, d}. Every pipe out of S is full, and the one pipe into S, c → b, is empty. So f(S, T) = c(S, T) = 12 + 7 + 4 = 23.

This is the max-flow min-cut theorem (CLRS Theorem 26.6). Three statements are the same: f is a maximum flow; the residual network has no augmenting path; |f| = c(S, T) for some cut. A minimum cut is a cut of least capacity, and its capacity equals the maximum flow value.

The failure. Symptom: a max-flow routine has a bug that no test catches. Measure: compare |f| with the capacity of the reachable cut. Fix: if they differ, the routine is wrong. The cut is a free check.

After a max flow, the search reaches {s, a, c}. The pipes between the sides are a → b (capacity 5), c → d (3) and b → a (7). What is the min cut capacity?

Chapter 6

Bipartite Matching as a Flow

Pair students with projects, then fix a greedy pairing with one augmenting path

Five students each list the projects they would take. Each student gets at most one project, and each project at most one student. How many pairs can you make?

This is maximum bipartite matching. A bipartite graph has two groups, L and R, and every edge joins L to R. A matching is a set of edges with no shared vertex. Flow solves it in four steps:

  1. Add a source s and a pipe of capacity 1 from s to each student.
  2. Give each student-to-project edge capacity 1.
  3. Add a sink t and a pipe of capacity 1 from each project to t.
  4. Run max flow. The student-to-project pipes that carry 1 are the pairs.

Why are the amounts whole? The integrality theorem (CLRS Theorem 26.10): with integer capacities, Ford-Fulkerson finds a max flow with integer amounts. So each pipe carries 0 or 1, and the unit pipes at s and t stop a student or a project from being used twice.

Match students to projects

Press Greedy, then Augment. Tap a student, then a project, to add or remove an interest.

Made-up interests. Greedy gives each student, in order, the first free project on their list.

The interests: Ana {ML, Web}, Ben {ML}, Cy {DB, Web}, Dee {DB}, Eli {OS, UI}. Greedy pairs Ana with ML, Cy with DB and Eli with OS: 3 pairs. Ben and Dee get nothing.

Search the residual network from Ben. Ben → ML has room. ML is taken, but the undo arrow ML → Ana lets Ana give it up, and Ana → Web → t is free. Push 1: Ben gets ML, Ana moves to Web, and there are 4 pairs.

The search from Dee runs DB, Cy, Web, Ana, ML, Ben and dead-ends.

A proof of 4: ML, Web, DB and Eli touch every edge. A set of vertices that touches every edge is a vertex cover. Each pair needs its own cover vertex, so no matching beats 4. Kőnig's theorem says that in a bipartite graph the smallest cover equals the largest matching. The min cut gives that cover.

A matching has at most V/2 pairs, so there are at most V/2 pushes of O(E) each: O(VE).

The failure. Symptom: an assignment tool leaves Ben out, though a better pairing exists. Measure: for each unmatched student, search for an augmenting path. Fix: augment along it instead of stopping at first choices.

In the flow network for matching, what stops one student from taking two projects?

Chapter 7

Min Cut at Work

Turn labelling a noisy image into a cut, then reduce three more problems to flow

Many problems are a min cut in disguise. The pattern: each choice becomes a side of the cut, and each cost becomes a pipe that the cut must sever.

Take a noisy image. Label each pixel object or background. Two costs apply. A pixel pays if its label disagrees with its brightness. A pair of neighbours pays λ (lambda) if their labels differ, because objects are mostly smooth.

  1. Let s stand for object and t for background. Each pixel is a vertex.
  2. Pipe s → pixel: the cost of calling the pixel background. The cut severs it when the pixel lands on the t side.
  3. Pipe pixel → t: the cost of calling the pixel object.
  4. Pipes both ways between neighbours, capacity λ each. The cut severs one when the two land on different sides.

A cut gives every pixel a label, and its capacity is exactly the total cost. So the min cut is the cheapest labelling.

Labels (pixel 1, pixel 2)Cost at λ = 0Cost at λ = 3
object, object1 + 6 = 77
object, background1 + 4 = 5 (best)5 + 3 = 8
background, background9 + 4 = 1313

Two neighbouring pixels have brightness 9 and 4 on a scale of 0 to 10. Calling a pixel object costs 10 minus its brightness; calling it background costs its brightness. At λ = 0, pixel 2 is background. At λ = 3, splitting costs 8, so pixel 2 joins the object for 7 (the best row).

Segment by min cut

Left: the noisy image. Right: the labels from the min cut. Drag λ and watch the specks vanish.

0

An illustrative image: a disc of brightness 7 on a background of 3, plus random noise. A red dot marks a label that differs from the hidden disc. Each λ runs a fresh Edmonds-Karp on 102 vertices.

Three more reductions, each from CLRS or its exercises:

ProblemBuildAnswer
Most paths from s to t with no shared edgecapacity 1 on every edgethe max flow value
Most paths with no shared middle vertexsplit each vertex v into vin → vout with capacity 1the max flow value
Several sources and sinksa super source with endless pipes to each source; a super sink the same wayone max flow

The failure. Symptom: the mask is full of specks. Measure: count neighbour pairs with different labels. Fix: raise λ. In the device, λ = 1 cuts the wrong pixels from 18 to 4, and from λ = 6 the whole disc vanishes. Tune λ on images with known answers.

Why do neighbouring pixels get pipes of capacity λ in both directions?

Chapter 8

Push-Relabel: Water Runs Downhill

Step a vertex-by-vertex method that floods first and drains the surplus later

Augmenting paths work on whole paths. Push-relabel, from Goldberg and Tarjan (1988), works on one vertex at a time. Picture each vertex at a height. Water may only run downhill, one level at a time.

In the middle of a run, a junction may hold more water than it sends on. This state is a preflow. The surplus at u is its excess. A vertex other than s and t with excess is active.

  1. Set the height of s to V and every other height to 0. Fill every pipe out of s.
  2. Take an active vertex u.
  3. Push: if an arrow u → v has room and u is one level above v, send the smaller of u's excess and that room.
  4. Relabel: if u still has excess and no arrow goes one level down, lift u.
  5. Repeat until no vertex is active.

How high does u go? Call u's height h(u), and look only at the arrows u → v that have room.

Say it aloud

h of u becomes one plus the minimum, over arrows u v whose room c-f of u v is above zero, of h of v.

h(u)
h of u the height of the active vertex u. The arrow means "becomes".
1 +
one plus one level above the lowest neighbour, so the next push can go there.
mincf(u, v) > 0
the minimum over arrows u v with room look only at residual arrows out of u that can take water.
h(v)
h of v the height of the vertex at the far end of such an arrow.
In plain words

Among the arrows out of u that have room, find the lowest neighbour v. Set h(u) to h(v) + 1. Now u can push to v.

With numbers

On the big network, a holds 4 extra units after it fills a → c. Its only arrow with room is the undo arrow back to s, and h(s) = 6. So h(a) = 1 + 6 = 7, and a pushes its 4 units back to s.

Watch the water run downhill

Each vertex sits at its height. Yellow numbers are excess. Step through the 2 fills and 24 operations.

Generic push-relabel on CLRS Figure 26.1. Active vertices wait in a first-in, first-out queue. Each tries its neighbours in the order s, a, b, c, d, t.

The run takes 2 initial fills, 13 pushes and 11 relabels. Water reaches t through c → t (12, then 7) and d → t (4). Vertices b and d trade the last units back and forth, rising each time, until b climbs to 7 and returns 2 units to s. The result is 23 again. Six units went back to s: 4 from a and 2 from b.

MethodTimeIdea
Generic push-relabelO(V2 E)any active vertex, any order (CLRS 26.4)
Relabel-to-frontO(V3)discharge vertices from a list, move a lifted one to the front (CLRS 26.5)
DinitzO(V2 E)BFS levels, then all shortest paths at once (a blocking flow)

The failure. Symptom: the program never ends; two vertices trade the same units forever. Measure: log the pushes. The same pair repeats with no relabel between. Fix: push only when h(u) = h(v) + 1. Then a vertex must rise before it pushes back, and CLRS shows that no height passes 2V − 1.

An active vertex u has room to v1 at height 3 and to v2 at height 5. It cannot push. What is its new height?

Chapter 9

Field Guide

Keep the terms, the numbers, the checks and the code in one place

A flow obeys capacity and conservation. The residual network adds undo arrows. Push along augmenting paths until none is left, and the vertices you can still reach form a cut whose capacity equals your flow. That cut is the proof.

TermMeaningNumber from this lesson
Capacity rule0 ≤ f(u, v) ≤ c(u, v)f(a, b) = 3 breaks c = 2
Conservationin = out at every junctionat a: 10 in, 2 + 8 out
Residual roomc − f forward, f backwardc → b: 5 forward, 4 undo
Bottlenecksmallest room on the path16, 12, 9, 14, 4: push 4
Greedy, no undofill paths, never cancelstalls at 19
Edmonds-Karpshortest path by BFS3 pushes; bound 27
Min cutreachable set after the last search{s, a, b, d}: 12 + 7 + 4 = 23
Matchingunit pipes s → L → R → tgreedy 3, max 4
Push-relabelpush downhill, lift when stuck13 pushes, 11 relabels
AlgorithmPath choiceTime
Ford-Fulkerson (1956)any augmenting pathO(E · |f*|) with integer capacities
Dinitz (1970)blocking flow on BFS levelsO(V2 E); O(E √V) for bipartite matching (Hopcroft-Karp)
Edmonds-Karp (1972)shortest path by BFSO(V E2)
Push-relabel (1988)no paths; local pushesO(V2 E) generic, O(V3) relabel-to-front
Chen and others (2022)interior-point method with dynamic data structuresE1 + o(1), almost linear

Check before you trust a max flow

  1. Add a reverse arrow for every pipe when you build the graph.
  2. On every push, add b on u → v and take b off v → u.
  3. Find paths with BFS, so the run time does not grow with capacities.
  4. After the run, check conservation at every junction.
  5. Compute the reachable set S and check c(S, T) = |f|.
  6. For a reduction, check that a cut's capacity equals the cost you meant.

The core, in code

pythonfrom collections import deque, defaultdict

def max_flow(edges, s, t):                    # edges: list of (u, v, capacity)
    cap = defaultdict(int); adj = defaultdict(set)
    for u, v, c in edges:
        cap[u, v] += c
        adj[u].add(v); adj[v].add(u)          # the reverse arrow too
    flow = defaultdict(int)                     # flow[v, u] == -flow[u, v]
    room = lambda u, v: cap[u, v] - flow[u, v]
    total = 0
    while True:
        par = {s: None}; q = deque([s])           # BFS: shortest path first
        while q and t not in par:
            u = q.popleft()
            for v in adj[u]:
                if v not in par and room(u, v) > 0:
                    par[v] = u; q.append(v)
        if t not in par:                        # no augmenting path: done
            return total, set(par)                 # par holds the min-cut side S
        path, v = [], t
        while par[v] is not None:
            path.append((par[v], v)); v = par[v]
        b = min(room(u, v) for u, v in path)      # the bottleneck
        for u, v in path:
            flow[u, v] += b; flow[v, u] -= b
        total += b

def max_matching(pairs):                       # pairs: list of (student, project)
    E = [('s', ('L', a), 1) for a in {a for a, _ in pairs}]
    E += [(('R', b), 't', 1) for b in {b for _, b in pairs}]
    E += [(('L', a), ('R', b), 1) for a, b in pairs]
    return max_flow(E, 's', 't')[0]

net = [('s','a',16), ('s','b',13), ('b','a',4), ('a','c',12), ('c','b',9),
       ('b','d',14), ('d','c',7), ('c','t',20), ('d','t',4)]
print(max_flow(net, 's', 't'))                 # (23, {'s', 'a', 'b', 'd'})
print(max_matching([('Ana','ML'), ('Ana','Web'), ('Ben','ML'), ('Cy','DB'),
    ('Cy','Web'), ('Dee','DB'), ('Eli','OS'), ('Eli','UI')]))   # 4

Where it sits in the field

Max flow is a linear program, and min cut is its dual (Chapter 29). Give each pipe a cost per unit as well, and the cheapest maximum flow comes from shortest paths by cost instead of by arrows (Chapter 24). Matching in graphs that are not bipartite needs Edmonds' blossom algorithm, a different method.

Keep going

The takeaway. Allow undo, push until no path is left, then read off the cut. The flow and the cut have the same number, and each one proves the other.
Your max-flow code returns 40. The vertices still reachable from s give a cut of capacity 46. What do you conclude?

Now press Present or Teach and explain from memory. Say why greedy stalls at 19 and what a backward arrow does. Say why Edmonds-Karp does not care about capacities, and how the last search gives the min cut. Then go back to the pipes and run all three planners. This time, name the chapter behind each colour.

Credit and source

This lesson re-teaches Chapter 26, Maximum Flow, of Introduction to Algorithms (third edition) by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest and Clifford Stein (MIT Press). Figure and theorem numbers follow that edition.

The method is from L. R. Ford and D. R. Fulkerson (1956); the BFS rule from Jack Edmonds and Richard Karp (1972) and, independently, Yefim Dinitz (1970); push-relabel from Andrew Goldberg and Robert Tarjan (1988). The almost-linear algorithm is by Li Chen, Rasmus Kyng, Yang Liu, Richard Peng, Maximilian Probst Gutenberg and Sushant Sachdeva (2022). The text, toys and devices here are our own.

CLRS Chapter 26: Maximum Flow
Introduction to Algorithms (MIT Press) · Back to Gleams