Sub topic 15
Application: Maximum Bipartite Matching
This chapter assumes you have read the earlier chapters on Edmonds-Karp, the paired-edge MaxFlow class, the integrality theorem, and super sources and sinks. It also assumes you know what a bipartite graph is. Here you will turn a matching problem into a flow network, prove that the two problems have the same answer, and recover the actual pairs from the final flow.
The Problem
A bipartite graph splits its vertices into a left set L and a right set R, and every edge joins a left vertex to a right vertex. A matching is a set of edges in which no two edges share an endpoint. A maximum matching is a matching with the largest possible number of edges.
A typical instance assigns workers to jobs. Each worker can do some of the jobs, each worker takes at most one job, and each job needs at most one worker. The goal is to fill as many jobs as possible.
Greedy assignment fails. Suppose worker 0 can do jobs 0 and 1, worker 1 can do only job 0, and you give job 0 to worker 0 first. Worker 1 is then stuck, even though the assignment 0→1, 1→0 matches both workers. You need a way to undo earlier choices, and the reverse edges of the residual graph provide one.
The Reduction
Build a directed flow network from the bipartite graph:
| Piece of the network | Edges | Capacity | What it enforces |
|---|---|---|---|
| Super source s | s → u for every u in L | 1 | Each left vertex is matched at most once |
| Middle edges | u → v for every allowed pair (u, v) | 1 | A pair is used at most once |
| Super sink t | v → t for every v in R | 1 | Each right vertex is matched at most once |
All edges point from left to right. You then compute a maximum flow from s to t. Its value is the size of a maximum matching.
Why the Flow Value Equals the Matching Size
The proof has two directions.
A matching gives a flow of the same value. Take a matching M. For each pair (u, v) in M, send one unit along s → u → v → t. No two pairs share a left vertex, so each edge s → u carries at most 1. No two pairs share a right vertex, so each edge v → t carries at most 1. Conservation holds at every vertex. The flow value is |M|, so the maximum flow is at least the maximum matching.
An integral flow gives a matching of the same value. All capacities are integers, so by the integrality theorem Ford-Fulkerson (and therefore Edmonds-Karp) returns a flow f in which every edge carries 0 or 1. Let M be the set of middle edges u → v with f(u, v) = 1. Vertex u receives at most one unit from s, so conservation lets at most one unit leave u, and u appears in at most one pair of M. The same argument on the edge v → t shows each right vertex appears at most once. M is therefore a matching. Every unit of flow crosses exactly one middle edge, so |M| equals the flow value.
Together these show that the maximum flow equals the maximum matching size.
Augmenting Paths Are Alternating Paths
Go back to the greedy failure. After the flow s → L0 → R0 → t, the residual graph contains the reverse edge R0 → L0. The next BFS can find
s → L1 → R0 → L0 → R1 → t.
Pushing one unit along this path cancels the flow on L0 → R0 and sends flow on L1 → R0 and L0 → R1. In matching terms, worker 0 moves to job 1 and worker 1 takes job 0. In matching theory this kind of path is called an augmenting alternating path. It alternates between unmatched edges (forward) and matched edges (backward), and each augmentation grows the matching by exactly one.
Implementation
The code below repeats the MaxFlow class from the implementation chapter so that the block runs on its own. It also records the index of each middle edge, which lets it report which pairs were matched. A middle edge with original capacity 1 is in the matching exactly when its remaining residual capacity is 0.
from collections import deque
class MaxFlow:
def __init__(self, n):
self.n = n
self.graph = [[] for _ in range(n)]
self.to = []
self.cap = []
def add_edge(self, u, v, c):
self.graph[u].append(len(self.to))
self.to.append(v)
self.cap.append(c)
self.graph[v].append(len(self.to))
self.to.append(u)
self.cap.append(0)
def max_flow(self, s, t):
flow = 0
while True:
parent_edge = [-1] * self.n
visited = [False] * self.n
visited[s] = True
queue = deque([s])
while queue and not visited[t]:
u = queue.popleft()
for e in self.graph[u]:
v = self.to[e]
if not visited[v] and self.cap[e] > 0:
visited[v] = True
parent_edge[v] = e
queue.append(v)
if not visited[t]:
return flow
bottleneck = float('inf')
v = t
while v != s:
e = parent_edge[v]
bottleneck = min(bottleneck, self.cap[e])
v = self.to[e ^ 1]
v = t
while v != s:
e = parent_edge[v]
self.cap[e] -= bottleneck
self.cap[e ^ 1] += bottleneck
v = self.to[e ^ 1]
flow += bottleneck
def max_bipartite_matching(left, right, pairs):
# Node 0 is the source, 1..left are left vertices,
# left+1..left+right are right vertices, and the last node is the sink
n = left + right + 2
s, t = 0, n - 1
mf = MaxFlow(n)
for i in range(left):
mf.add_edge(s, 1 + i, 1)
for j in range(right):
mf.add_edge(1 + left + j, t, 1)
middle = []
for i, j in pairs:
middle.append((len(mf.to), i, j)) # index of the forward edge
mf.add_edge(1 + i, 1 + left + j, 1)
size = mf.max_flow(s, t)
matched = [(i, j) for e, i, j in middle if mf.cap[e] == 0]
return size, matched
size, matched = max_bipartite_matching(
3, 3, [(0, 0), (0, 1), (1, 0), (2, 1), (2, 2)])
print(size) # 3
print(matched) # [(0, 1), (1, 0), (2, 2)]Each left index i becomes node 1 + i and each right index j becomes node 1 + left + j, so the two sides never share a node number.
Running Time
The general Edmonds-Karp bound is O(V E²). Matching networks allow a tighter bound. The flow value is at most min(|L|, |R|), which is less than V. Each augmentation adds exactly one unit and costs one BFS, which takes O(V + E) time. The total is O(V · (V + E)), which is O(V E) when the graph has no isolated vertices. Plain Ford-Fulkerson with DFS gets the same bound, because its O(E · f) bound also applies with f ≤ V. The Hopcroft-Karp algorithm finds many shortest augmenting paths in one phase and runs in O(E √V). It is the bipartite special case of Dinic's algorithm, which the final chapter covers.
Common Errors
- Undirected middle edges. If you add v → u as well as u → v, flow can run right to left and the result is no longer a matching. Add middle edges only from left to right. The reverse residual edges are already created for you.
- Missing unit capacities on the source and sink edges. If s → u has capacity greater than 1, one left vertex can be matched several times. Middle edges can have any capacity of 1 or more without changing the answer, because the unit edges at s and t already limit the flow. Unit capacity is still the clearest choice.
- Index collisions. If left vertex 0 and right vertex 0 map to the same node, the network is wrong and the code gives no error. Always offset the right side.
- Reading pairs from the wrong edges. The reverse edge e ^ 1 has capacity 1 after a match, so check the forward edge index e.
- Float capacities. Integer capacities are what make the integrality argument hold. Keep them as integers.
Edge Cases and Variations
- Duplicate pairs become parallel edges. The paired-edge representation handles them, and the matching still uses the pair at most once because the unit edges at s and t limit it.
- Isolated vertices and unequal side sizes need no special handling. The answer is simply at most min(|L|, |R|).
- Capacitated assignment. If worker u can take up to ku jobs, give s → u capacity ku. If job v needs up to cv workers, give v → t capacity cv. The answer is still integral.
- Minimum vertex cover (König's theorem). After the maximum flow, let Z be the set of vertices reachable from s in the residual graph. The left vertices not in Z, together with the right vertices in Z, form a minimum vertex cover, and its size equals the maximum matching. This follows from the minimum cut you extracted in the earlier chapter: the cut can cross only source and sink edges once you give middle edges infinite capacity.
Exercise
Left vertices A, B, C and right vertices X, Y have edges A–X, B–X, C–X, C–Y. Build the flow network, give the maximum matching size, and explain why it cannot be larger using a cut.
Show answer
Edges: s→A, s→B, s→C (cap 1); A→X, B→X, C→X, C→Y (cap 1); X→t, Y→t (cap 1). The maximum matching has size 2, for example A–X and C–Y. The cut that separates {t} from the rest crosses X→t and Y→t, so its capacity is 2. No flow can exceed it, so no matching can exceed 2.
Exercise
In maxbipartitematching, a student adds middle edges with mf.addedge(1 + i, 1 + left + j, 1) and also mf.addedge(1 + left + j, 1 + i, 1). Give a concrete reason the reported matching can be wrong.
Show answer
The extra right-to-left edges let flow travel paths such as s → L0 → R0 → L1 → R1 → t, where L1 receives flow from R0 instead of from s. The flow value still equals the matching size, because the unit edges at s and t still bound it. But the set of middle edges with zero forward capacity can now include two pairs that share a vertex (L0–R0 and the R0→L1 edge). The recovered pairs are therefore no longer a valid matching. Middle edges must be directed left to right only.
Exercise
Each of 4 workers can take at most 2 jobs, and each of 5 jobs needs exactly one worker. Which capacities change in the construction, and what is the largest possible flow value?
Show answer
Set the capacity of each source edge s → worker to 2. Keep the middle edges and the job → t edges at 1. The flow value is at most min(4 · 2, 5) = 5, and integrality guarantees an integral assignment that reaches the maximum.