Maximum Bipartite Matching
Four volunteers and four shifts; each volunteer can work only some of the shifts; each shift needs one person and each person takes at most one shift. How many shifts can be filled? Problems of this shape (applicants and jobs, students and projects, tasks and machines, kidney donors and recipients) are bipartite matching problems. Bipartite Matching in Discrete Mathematics proves Hall's theorem about when everyone can be matched. This lesson finds a maximum matching with a maximum-flow algorithm, and then strips the flow machinery away to get the short augmenting-path algorithm that programmers usually write.
Matchings
A matching in an undirected graph is a set of edges no two of which share a vertex. A vertex is matched if some edge of touches it, and free otherwise. A maximum matching has the largest possible number of edges. The graph is bipartite if with every edge between and ; BFS decides whether a graph is bipartite.
The flow network. Direct every edge from to and give it capacity 1. Add a source with an edge of capacity 1 to every vertex of , and a sink with an edge of capacity 1 from every vertex of .
Theorem. The size of a maximum matching in equals the value of a maximum flow in this network.
Proof
Matching to flow. Given a matching , send one unit along for each edge . Since no vertex is in two edges of , every edge of capacity 1 carries at most one unit and conservation holds: a flow of value .
Flow to matching. By the integrality theorem there is a maximum flow with integer values, so every edge carries 0 or 1. Let be the edges from to that carry 1. A vertex receives at most 1 unit from , so by conservation at most one of its edges carries flow; the same holds for with its single edge to . So is a matching, and the net flow across the cut is .
Running time. The maximum flow is at most , so Ford-Fulkerson needs at most augmentations of each: . The Hopcroft-Karp algorithm augments along many shortest paths at once and achieves .
Watching it work
Volunteers and shifts : can take or , only , either or , either or . Edmonds-Karp matches -, - and - with short paths. Then is left out, and the fourth augmenting path rearranges everything: takes from , takes from , takes from , and moves to .
from collections import deque
L, R = "ABCD", "WXYZ"
can = {"A": "WX", "B": "W", "C": "XY", "D": "YZ"}
cap = {("S", u): 1 for u in L} | {(u, v): 1 for u in L for v in can[u]} | {(v, "T"): 1 for v in R}
flow = {e: 0 for e in cap}
def bfs(s, t):
prev, q = {s: None}, deque([s])
while q and t not in prev:
u = q.popleft()
nbrs = [(b, 0) for (a, b) in cap if a == u and flow[(a, b)] < cap[(a, b)]] + \
[(a, 1) for (a, b) in cap if b == u and flow[(a, b)] > 0]
for v, back in sorted(nbrs):
if v not in prev:
prev[v] = (u, back); q.append(v)
return prev
while "T" in (prev := bfs("S", "T")):
path, v = ["T"], "T"
while prev[v]:
u, back = prev[v]
if back: flow[(v, u)] -= 1
else: flow[(u, v)] += 1
path.append(u); v = u
print("augmenting path:", " ".join(reversed(path)))
matching = sorted(f"{u}-{v}" for (u, v), x in flow.items() if x and u in L and v in R)
print("maximum matching:", matching)augmenting path: S A W T
augmenting path: S C X T
augmenting path: S D Y T
augmenting path: S B W A X C Y D Z T
maximum matching: ['A-X', 'B-W', 'C-Y', 'D-Z']
Augmenting paths without the network
Read the fourth path above inside the bipartite graph itself: (not in the matching), (in it, used backwards), (not in it), (in it), and so on, ending at the free vertex . It alternates between non-matching and matching edges and joins two free vertices. Swapping the edges along such an augmenting path grows the matching by one, and Berge's theorem says a matching is maximum exactly when no augmenting path exists. A DFS from each free left vertex finds one: try every neighbour ; if is free, take it; otherwise try to re-match 's partner elsewhere, recursively. That is Kuhn's algorithm, . The program compares it with the flow version on random bipartite graphs.
import random
from collections import deque
def kuhn(left, adj):
match_r = {}
def try_assign(u, seen):
for v in adj[u]:
if v in seen:
continue
seen.add(v)
if v not in match_r or try_assign(match_r[v], seen):
match_r[v] = u
return True
return False
return sum(try_assign(u, set()) for u in left), match_r
def flow_matching(left, right, adj):
cap = {("s", ("L", u)): 1 for u in left}
cap |= {(("L", u), ("R", v)): 1 for u in left for v in adj[u]}
cap |= {(("R", v), "t"): 1 for v in right}
out = {}
for (a, b) in cap:
out.setdefault(a, []).append((a, b)); out.setdefault(b, []).append((a, b))
flow = dict.fromkeys(cap, 0)
value = 0
while True:
prev, q = {"s": None}, deque(["s"])
while q and "t" not in prev:
u = q.popleft()
for (a, b) in out[u]:
if a == u and flow[(a, b)] == 0 and b not in prev:
prev[b] = (a, b); q.append(b)
elif b == u and flow[(a, b)] == 1 and a not in prev:
prev[a] = (a, b); q.append(a)
if "t" not in prev:
return value
v = "t"
while v != "s":
a, b = prev[v]
if b == v: flow[(a, b)] = 1; v = a
else: flow[(a, b)] = 0; v = b
value += 1
rng = random.Random(44)
sizes = []
for trial in range(200):
nl, nr = rng.randint(1, 12), rng.randint(1, 12)
adj = {u: [v for v in range(nr) if rng.random() < 0.2] for u in range(nl)}
k, match_r = kuhn(range(nl), adj)
assert k == flow_matching(range(nl), range(nr), adj)
assert len(set(match_r.values())) == len(match_r) == k # a valid matching
sizes.append(k)
print("Kuhn's algorithm and max flow agree on 200 random bipartite graphs")
print(f"matching sizes from {min(sizes)} to {max(sizes)}, average {sum(sizes) / len(sizes):.2f}")Kuhn's algorithm and max flow agree on 200 random bipartite graphs
matching sizes from 0 to 11, average 3.85
The practice problem Maximum Bipartite Matching asks for the size of a maximum matching.
In C++
Kuhn's algorithm in C++ is a dozen lines. It solves the volunteer problem.
#include <cstdio>
#include <functional>
#include <string>
#include <vector>
int main() {
const std::string left = "ABCD", right = "WXYZ";
std::vector<std::vector<int>> adj = {{0, 1}, {0}, {1, 2}, {2, 3}}; // A: W X, B: W, C: X Y, D: Y Z
std::vector<int> match_r(right.size(), -1);
std::vector<bool> seen;
std::function<bool(int)> try_assign = [&](int u) {
for (int v : adj[u]) {
if (seen[v]) continue;
seen[v] = true;
if (match_r[v] < 0 || try_assign(match_r[v])) { match_r[v] = u; return true; }
}
return false;
};
int size = 0;
for (int u = 0; u < static_cast<int>(left.size()); ++u) {
seen.assign(right.size(), false);
if (try_assign(u)) ++size;
}
std::printf("maximum matching has %d edges:", size);
for (int v = 0; v < static_cast<int>(right.size()); ++v)
if (match_r[v] >= 0) std::printf(" %c-%c", left[match_r[v]], right[v]);
std::printf("\n");
}maximum matching has 4 edges: B-W A-X C-Y D-Z
Test yourself
In the flow network for bipartite matching, what capacity do the edges get?
- The degree of the vertex
- 1 on every edge
- on the middle edges
- The number of vertices
Why does Ford-Fulkerson find a maximum bipartite matching in time?
- Because BFS is linear
- Because the maximum flow is at most , so there are at most augmentations of each
- Because matchings are unique
- Because the graph is acyclic
What is an augmenting path for a matching ?
- Any path between two vertices of
- A path between two free vertices whose edges alternate between non-matching and matching edges
- A path of matching edges only
- A cycle of even length