Bipartite Matching & Assignment
Hopcroft–Karp, König’s theorem and the Hungarian algorithm.
A matching is maximum exactly when no augmenting path exists (Berge, 1957). That one fact drives an algorithm, a min-max theorem from 1931, and, once pairs have costs, the Hungarian method, which Kuhn named in 1955 after the two Hungarian mathematicians whose work it builds on. In 2006 it came to light that Jacobi had already solved the assignment problem in the nineteenth century, in work published after his death, in 1890.
What you’ll learn
- Prove Berge's lemma and use it to justify augmenting-path algorithms in bipartite and general graphs.
- Analyze Hopcroft–Karp: phases of vertex-disjoint shortest augmenting paths, phases and time.
- Prove König's theorem with alternating paths, derive Hall's theorem and the deficiency formula, and extract a minimum vertex cover from a maximum matching.
- Solve the assignment problem with the Hungarian algorithm in using dual potentials, and know how general (non-bipartite) matching differs.
Augmenting paths: Berge’s lemma
If an augmenting path exists, flipping it gives a larger matching. Conversely, suppose a matching is larger than , and look at the symmetric difference. Every vertex touches at most one edge of each matching, so it has degree at most 2 there:
An alternating cycle has even length, with equally many edges of each matching. The components hold more edges of than of in total, so some component is a path with one more edge than edge:
That path starts and ends with edges of , at vertices that no edge of touches inside the path, and none outside it either (their degree in would be 2). So both ends are free in : it is an -augmenting path. In fact contains at least vertex-disjoint augmenting paths.
A matching has 5 edges, and is an -augmenting path with 7 edges. How many edges does have?
- 7
- 12
- 6
- 2
Show the answer
C. 6
A 7-edge augmenting path has 4 edges outside and 3 inside. Flipping removes those 3 and adds the 4: . Every augmentation adds exactly one edge, however long the path.
In a bipartite graph, alternating paths go left on matched edges and right on unmatched ones, so a single search from the free left vertices finds an augmenting path if one exists: that is Kuhn's algorithm from the Optimized lesson. In a general graph, an odd cycle can make that search miss augmenting paths, which is why general matching needs Edmonds's blossoms (step 5). Berge's lemma itself holds in both.
Hopcroft–Karp: many shortest paths per phase
Hopcroft–Karp (1973) works in phases. A breadth-first search from all free left vertices at once finds the length of a shortest augmenting path and arranges the vertices in layers. Depth-first searches through the layers then find a maximal set of vertex-disjoint augmenting paths of length , and all of them are flipped. Each phase costs . In flow terms, this is Dinic's algorithm on the unit-capacity matching network.
(a) is Dinic's level argument: after flipping a maximal set of disjoint shortest paths, every augmenting path of the old length would have to share an edge or vertex with a flipped one, and sharing makes it longer. Augmenting paths have odd lengths, so the length grows by at least 2 per phase.
(b) After phases, every augmenting path has more than edges, hence more than vertices. Let be a maximum matching. By Berge's proof, contains at least vertex-disjoint augmenting paths, each of them long:
Each later phase adds at least one edge, so at most phases follow. In total there are about phases of each:
#include <vector>
#include <queue>
#include <algorithm>
#include <climits>
using namespace std;
struct HopcroftKarp {
int nl, nr, lim; // lim: layer of the left vertices where shortest paths end
vector<vector<int>> adj; // adj[u] = right neighbors of left vertex u
vector<int> ml, mr, dist; // ml[u], mr[v]: partners, or -1 when free
HopcroftKarp(int nl, int nr) : nl(nl), nr(nr), adj(nl), ml(nl, -1), mr(nr, -1), dist(nl) {}
bool bfs() { // layers of left vertices, from all free ones at once
queue<int> q; lim = INT_MAX;
for (int u = 0; u < nl; u++) {
dist[u] = ml[u] < 0 ? 0 : -1;
if (ml[u] < 0) q.push(u);
}
while (!q.empty()) {
int u = q.front(); q.pop();
if (dist[u] > lim) break; // deeper layers cannot be on a shortest path
for (int v : adj[u]) {
int w = mr[v];
if (w < 0) lim = min(lim, dist[u]); // a free right vertex: a path ends here
else if (dist[w] < 0) { dist[w] = dist[u] + 1; q.push(w); }
}
}
return lim != INT_MAX;
}
bool dfs(int u) { // one shortest augmenting path, layer by layer
for (int v : adj[u]) {
int w = mr[v];
if (w < 0 ? dist[u] == lim : dist[w] == dist[u] + 1 && dfs(w)) {
ml[u] = v; mr[v] = u; return true;
}
}
dist[u] = -1; // dead end: skip u for the rest of the phase
return false;
}
int max_matching() {
int size = 0;
while (bfs()) // a phase: a maximal set of disjoint shortest paths
for (int u = 0; u < nl; u++)
if (ml[u] < 0 && dfs(u)) size++;
return size;
}
};Layers count left vertices: a free right vertex adjacent to a left vertex of layer lim ends a shortest augmenting path. Marking a dead-end vertex with dist[u] = -1 plays the role of Dinic's current-arc pointer, so each phase is . Even the worst-case bound, for and , fits a typical time limit, and real inputs need far fewer phases.
König, Hall and vertex covers
Any cover needs one endpoint of each matching edge, and those endpoints are distinct, so every cover has at least vertices. For the converse, let be maximum, the free left vertices, and the vertices reachable from by alternating paths (left to right on unmatched edges, right to left on matched ones). Define
covers every edge . If , then . If and the edge is unmatched, the search continues to , so . If and the edge is matched, then , so the search reached through its partner: again .
. Each is matched, or the alternating path to it would be augmenting, contradicting Berge. Each is matched, since free left vertices are in . And no matching edge has both ends in : if , the search continues to its partner, which is then in and not in . So each matching edge has exactly one end in , and every vertex of is matched:
Left vertices 1, 2, 3, 4; right vertices a, b, c, d; edges 1–a, 1–b, 2–a, 3–a, 4–b, 4–c, 4–d. What is the size of a maximum matching?
Show the answer
3
Vertices 1, 2 and 3 only like a and b, so at most two of them can be matched: the maximum is at most 3, and 2–a, 1–b, 4–c achieves it. The free vertex 3 reaches a and then 2 by alternating paths, so and the cover is : three vertices touching all seven edges, as König promises.
Consequences.
- Every -regular bipartite graph with has a perfect matching: sends out edges, which land in , where at most fit.
- In a bipartite graph, a maximum independent set is the complement of a minimum cover: vertices. In a general graph that problem is NP-hard.
- In any graph without isolated vertices, the fewest edges touching every vertex number (Gallai).
- Dilworth's theorem (a finite poset splits into as many chains as its largest antichain) follows from König, and so does the minimum path cover of a DAG (see Paths in DAGs).
Assignment: the Hungarian algorithm
In the assignment problem, workers must take jobs, one each, and worker on job costs : find a perfect matching of minimum total cost. Its linear program has an integral optimum, and its dual gives every row a potential and every column a potential :
The Hungarian algorithm keeps feasible potentials and a matching of tight edges, and adds the rows one at a time. From the new row it grows a tree of alternating tight edges. If the tree reaches a free column, flipping the path to it matches one more row. Otherwise let be the smallest slack from a tree row to a column outside the tree; adding to on the tree's rows and subtracting it from on the tree's columns keeps every tree edge and matched edge tight, keeps all constraints satisfied, and makes a new edge tight. Keeping each column's smallest slack in an array makes each row cost , and the whole algorithm .
def hungarian(cost):
"""cost: n x n matrix. Returns (minimum total cost, col_of_row). Keeps u[i] + v[j] <= cost."""
n, INF = len(cost), float('inf')
u, v = [0] * (n + 1), [0] * (n + 1) # 1-indexed; column 0 is a virtual start
row_of = [0] * (n + 1) # row_of[j] = row matched to column j (0 = none)
for i in range(1, n + 1): # add row i, then grow an alternating tree from it
row_of[0], j0 = i, 0
minv, way, used = [INF] * (n + 1), [0] * (n + 1), [False] * (n + 1)
while row_of[j0]: # until the tree reaches a free column
used[j0], i0, delta, j1 = True, row_of[j0], INF, 0
for j in range(1, n + 1):
if not used[j]:
slack = cost[i0 - 1][j - 1] - u[i0] - v[j]
if slack < minv[j]: minv[j], way[j] = slack, j0
if minv[j] < delta: delta, j1 = minv[j], j
for j in range(n + 1): # shift potentials: tree edges stay tight
if used[j]: u[row_of[j]] += delta; v[j] -= delta
else: minv[j] -= delta
j0 = j1
while j0: # flip the alternating path back to column 0
j1 = way[j0]; row_of[j0] = row_of[j1]; j0 = j1
col_of = [0] * n
for j in range(1, n + 1): col_of[row_of[j] - 1] = j - 1
return -v[0], col_of # -v[0] equals the optimal costA compact version that is common in contest libraries. minv[j] is column 's smallest slack to the tree and way[j] the column from which that slack was reached, so the augmenting path can be flipped without storing the tree. For an matrix with , run it with columns.
Four workers (rows) and four jobs (columns) with costs [9, 2, 7, 8], [6, 4, 3, 7], [5, 8, 1, 8], [7, 6, 9, 4]. What is the minimum total cost of an assignment?
Show the answer
13
Rows to columns 2, 1, 3, 4 cost , the unique optimum among the 24 permutations. Greedy, row by row, takes 2, then 3, leaving row 3 with cost 5 and row 4 with 4, for 14: the cheap cell 3 in row 2 blocks the even cheaper cell 1 in row 3.
History and relatives. Kuhn's 1955 method needed time; Munkres (1957) showed it polynomial, and Edmonds and Karp, and independently Tomizawa, brought it to . Seen as a flow, the algorithm is successive shortest paths for minimum-cost flow on the assignment network, with the potentials making every reduced cost non-negative so that Dijkstra's algorithm applies: Johnson's reweighting from the lesson on negative weights. For general min-cost flow, successive shortest paths take for a flow of value , which is pseudo-polynomial; strongly polynomial algorithms exist (Tardos, 1985; Orlin, 1993), and for integer costs at most the assignment problem takes by cost scaling (Gabow & Tarjan, 1989).
General graphs and the frontier
Without the bipartition, augmenting paths still decide everything (Berge), but finding them is harder. In a bipartite graph every vertex is reached by alternating paths at a fixed parity, even or odd. An odd cycle breaks this: a vertex can be reached both ways, and a search that marks it visited on the wrong parity can miss the only augmenting path.
Edmonds's blossom algorithm (1965) repairs the search: when it finds an odd alternating cycle, a blossom, it contracts the cycle into one vertex, searches the smaller graph, and expands the blossom to lift any augmenting path back to the original. It runs in polynomial time, in a direct implementation, and was the paper in which Edmonds proposed polynomial time as the meaning of "efficient". Micali and Vazirani (1980) matched Hopcroft–Karp's for general graphs. Algebra gives another route: by Tutte's theorem (1947), a graph has a perfect matching iff a symbolic matrix built from it, the Tutte matrix, has nonzero determinant; Lovász (1979) tested this by substituting random numbers, and Mucha and Sankowski (2004) find a maximum matching in time, where is the matrix-multiplication exponent.
Students must work in pairs, and any two students who are willing to work together may be paired. To form as many pairs as possible, which approach is correct?
- Hopcroft–Karp, after two-coloring the students
- Edmonds's blossom algorithm, or Micali–Vazirani
- A maximum flow from through every student, then every student again, to
- The Hungarian algorithm
Show the answer
B. Edmonds's blossom algorithm, or Micali–Vazirani
The compatibility graph is general, possibly full of odd cycles, so bipartite methods do not apply; Edmonds's blossoms handle the odd cycles in polynomial time.
Key takeaways
- Berge: a matching is maximum iff it has no augmenting path, in every graph; contains disjoint augmenting paths.
- Hopcroft–Karp flips a maximal set of disjoint shortest augmenting paths per phase; path lengths grow every phase, so phases of give .
- König: in bipartite graphs, maximum matching = minimum vertex cover, and the cover is read off the alternating-path search; Hall's condition characterizes matchings that saturate one side.
- The Hungarian algorithm maintains dual potentials and tight edges and solves the assignment problem in ; it is successive shortest paths for min-cost flow with Johnson-style reduced costs.
- General graphs need Edmonds's blossoms (Micali–Vazirani: ); bipartite matching now runs in almost-linear time through max flow, while general matching in almost-linear time is open.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A matching cannot be extended by adding any single edge. What follows?
- is maximum
- is maximum if the graph is bipartite
- is maximal, but it can still be smaller than a maximum matching, by up to a factor of 2
- is perfect
Show the answer
C. is maximal, but it can still be smaller than a maximum matching, by up to a factor of 2
On the path a–b–c–d, the single edge b–c cannot be extended, yet a–b, c–d is twice as large; the augmenting path a–b–c–d shows it. Every maximal matching has at least half the size of a maximum one, because each edge of a maximum matching touches an edge of the maximal one. Berge's lemma asks about augmenting paths, not single edges.
Why does Hopcroft–Karp need only phases?
- Each phase at least doubles the size of the matching
- Each phase matches at least vertices
- Breadth-first search finds all augmenting paths at once
- After phases every augmenting path is long, and the disjoint augmenting paths of then number fewer than
Show the answer
D. After phases every augmenting path is long, and the disjoint augmenting paths of then number fewer than
Shortest augmenting paths get longer every phase. Once they exceed edges, at most vertex-disjoint ones fit in vertices, so the matching is fewer than edges short of maximum, and each later phase gains at least one.
In a bipartite graph, the left vertices 1, 2 and 3 are each adjacent only to the right vertices a and b. What follows?
- No matching saturates the left side; every matching leaves at least one of 1, 2, 3 unmatched
- A perfect matching may still exist if the right side is large enough
- The graph is not bipartite
- Hall's condition fails, so the maximum matching has at most 2 edges
Show the answer
A. No matching saturates the left side; every matching leaves at least one of 1, 2, 3 unmatched
has , so Hall's condition fails: only two of them can be matched, whatever happens elsewhere. The deficiency formula says the maximum matching has at most edges.
The Hungarian algorithm stops with a perfect matching whose edges are all tight, , for feasible potentials. Why is that matching optimal?
- Because it was built greedily from the cheapest edges
- Because every row was matched to its cheapest column
- Because its cost equals , which is a lower bound on the cost of every perfect matching
- Because the potentials are all non-negative
Show the answer
C. Because its cost equals , which is a lower bound on the cost of every perfect matching
Feasibility gives for every perfect matching ; summing, every matching costs at least . The tight matching costs exactly that, so nothing is cheaper. The potentials are a certificate of optimality, exactly like a cut for a maximum flow.
Further reading
- C. Berge, "Two theorems in graph theory," Proceedings of the National Academy of Sciences 43(9) (1957), 842–844.
- J. E. Hopcroft & R. M. Karp, "An algorithm for maximum matchings in bipartite graphs," SIAM Journal on Computing 2(4) (1973), 225–231.
- H. W. Kuhn, "The Hungarian method for the assignment problem," Naval Research Logistics Quarterly 2 (1955), 83–97.
- J. Edmonds, "Paths, trees, and flowers," Canadian Journal of Mathematics 17 (1965), 449–467.
- S. Micali & V. V. Vazirani, "An algorithm for finding maximum matching in general graphs," Proceedings of the 21st IEEE Symposium on Foundations of Computer Science (1980).