Simple Algorithm
Algorithms & Data Structures · Optimal · 28 min

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 O(mn)O(m\sqrt n) 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, O(n)O(\sqrt n) phases and O(mn)O(m\sqrt n) 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 O(n3)O(n^3) using dual potentials, and know how general (non-bipartite) matching differs.

Augmenting paths: Berge’s lemma

DerivationProof
  1. M⊕M∗=vertex-disjoint paths and cycles, alternating between M and M∗M \oplus M^* = \text{vertex-disjoint paths and cycles, alternating between } M \text{ and } M^*

    If an augmenting path exists, flipping it gives a larger matching. Conversely, suppose a matching M∗M^* is larger than MM, and look at the symmetric difference. Every vertex touches at most one edge of each matching, so it has degree at most 2 there:

  2. ∣M∗∣−∣M∣=∑components C(∣C∩M∗∣−∣C∩M∣)>0\abs{M^*} - \abs{M} = \sum_{\text{components } C} \big(\abs{C \cap M^*} - \abs{C \cap M}\big) > 0

    An alternating cycle has even length, with equally many edges of each matching. The components hold more edges of M∗M^* than of MM in total, so some component is a path with one more M∗M^* edge than MM edge:

  3. #{disjoint M-augmenting paths in M⊕M∗} ≥ ∣M∗∣−∣M∣\#\{\text{disjoint } M\text{-augmenting paths in } M \oplus M^*\} \ \ge\ \abs{M^*} - \abs{M}

    That path starts and ends with edges of M∗M^*, at vertices that no edge of MM touches inside the path, and none outside it either (their degree in M⊕M∗M \oplus M^* would be 2). So both ends are free in MM: it is an MM-augmenting path. In fact M⊕M∗M \oplus M^* contains at least ∣M∗∣−∣M∣\abs{M^*} - \abs{M} vertex-disjoint augmenting paths.

Check your understanding

A matching MM has 5 edges, and PP is an MM-augmenting path with 7 edges. How many edges does M⊕PM \oplus P have?

  1. 7
  2. 12
  3. 6
  4. 2
Show the answer

C. 6

A 7-edge augmenting path has 4 edges outside MM and 3 inside. Flipping removes those 3 and adds the 4: 5−3+4=65 - 3 + 4 = 6. 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 O(nm)O(nm) 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 ℓ\ell 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 ℓ\ell, and all of them are flipped. Each phase costs O(m)O(m). In flow terms, this is Dinic's algorithm on the unit-capacity matching network.

DerivationWhy √n phases suffice
  1. ℓ1<ℓ2<ℓ3<⋯ ,ℓk≥2k−1\ell_1 < \ell_2 < \ell_3 < \cdots, \qquad \ell_k \ge 2k - 1

    (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.

  2. (∣M∗∣−∣M∣)⋅n < n⟹∣M∗∣−∣M∣<n\big(\abs{M^*} - \abs{M}\big) \cdot \sqrt n \ <\ n \quad\Longrightarrow\quad \abs{M^*} - \abs{M} < \sqrt n

    (b) After n\sqrt n phases, every augmenting path has more than n\sqrt n edges, hence more than n\sqrt n vertices. Let M∗M^* be a maximum matching. By Berge's proof, M⊕M∗M \oplus M^* contains at least ∣M∗∣−∣M∣\abs{M^*} - \abs{M} vertex-disjoint augmenting paths, each of them long:

  3. O(n)⋅O(m)=O(mn)O(\sqrt n) \cdot O(m) = O(m\sqrt n)

    Each later phase adds at least one edge, so at most n\sqrt n phases follow. In total there are about 2n2\sqrt n phases of O(m)O(m) each:

cpp
#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 O(m)O(m). Even the worst-case bound, mn≈108m\sqrt n \approx 10^8 for n=105n = 10^5 and m=3×105m = 3 \times 10^5, fits a typical time limit, and real inputs need far fewer phases.

König, Hall and vertex covers

DerivationProof: build the cover from alternating paths
  1. K=(L∖Z) ∪ (R∩Z)K = (L \setminus Z) \ \cup\ (R \cap Z)

    Any cover needs one endpoint of each matching edge, and those endpoints are distinct, so every cover has at least ∣M∣\abs{M} vertices. For the converse, let MM be maximum, UU the free left vertices, and ZZ the vertices reachable from UU by alternating paths (left to right on unmatched edges, right to left on matched ones). Define

  2. ∀(l,r)∈E:l∈K  or  r∈K\forall (l, r) \in E: \quad l \in K \ \text{ or } \ r \in K

    KK covers every edge (l,r)(l, r). If l∉Zl \notin Z, then l∈Kl \in K. If l∈Zl \in Z and the edge is unmatched, the search continues to rr, so r∈Z∩R⊆Kr \in Z \cap R \subseteq K. If l∈Zl \in Z and the edge is matched, then l∉Ul \notin U, so the search reached ll through its partner: again r∈Zr \in Z.

  3. ∣K∣=∣M∣=ν(G)=τ(G)\abs{K} = \abs{M} = \nu(G) = \tau(G)

    ∣K∣=∣M∣\abs{K} = \abs{M}. Each r∈R∩Zr \in R \cap Z is matched, or the alternating path to it would be augmenting, contradicting Berge. Each l∈L∖Zl \in L \setminus Z is matched, since free left vertices are in U⊆ZU \subseteq Z. And no matching edge has both ends in KK: if r∈Zr \in Z, the search continues to its partner, which is then in ZZ and not in KK. So each matching edge has exactly one end in KK, and every vertex of KK is matched:

Predict before you look

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 Z={3,a,2}Z = \{3, a, 2\} and the cover is K={1,4}∪{a}K = \{1, 4\} \cup \{a\}: three vertices touching all seven edges, as König promises.

Consequences.

  • Every kk-regular bipartite graph with k≥1k \ge 1 has a perfect matching: XX sends out k∣X∣k\abs{X} edges, which land in N(X)N(X), where at most k∣N(X)∣k\abs{N(X)} fit.
  • In a bipartite graph, a maximum independent set is the complement of a minimum cover: n−ν(G)n - \nu(G) vertices. In a general graph that problem is NP-hard.
  • In any graph without isolated vertices, the fewest edges touching every vertex number n−ν(G)n - \nu(G) (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, nn workers must take nn jobs, one each, and worker ii on job jj costs cijc_{ij}: find a perfect matching of minimum total cost. Its linear program has an integral optimum, and its dual gives every row a potential uiu_i and every column a potential vjv_j:

min⁡∑i,jcij xij  s.t. each row and column of x sums to 1, x≥0max⁡∑iui+∑jvj  s.t. ui+vj≤cij\min \sum_{i,j} c_{ij}\, x_{ij}\ \ \text{s.t. each row and column of } x \text{ sums to } 1,\ x \ge 0 \qquad\quad \max \sum_i u_i + \sum_j v_j\ \ \text{s.t. } u_i + v_j \le c_{ij}
An edge is tight if ui+vj=ciju_i + v_j = c_{ij}. Feasible potentials are lower bounds on the cost that each worker and each job must contribute.

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 δ\delta be the smallest slack cij−ui−vjc_{ij} - u_i - v_j from a tree row to a column outside the tree; adding δ\delta to uu on the tree's rows and subtracting it from vv 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 O(n2)O(n^2), and the whole algorithm O(n3)O(n^3).

python
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 cost

A compact O(n3)O(n^3) version that is common in contest libraries. minv[j] is column jj'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 n×mn \times m matrix with n≤mn \le m, run it with mm columns.

Predict before you look

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 2+6+1+4=132 + 6 + 1 + 4 = 13, 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 O(n4)O(n^4) time; Munkres (1957) showed it polynomial, and Edmonds and Karp, and independently Tomizawa, brought it to O(n3)O(n^3). 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 cij−ui−vjc_{ij} - u_i - v_j 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 O(F⋅mlog⁡n)O(F \cdot m \log n) for a flow of value FF, which is pseudo-polynomial; strongly polynomial algorithms exist (Tardos, 1985; Orlin, 1993), and for integer costs at most CC the assignment problem takes O(mnlog⁡(nC))O(m\sqrt n \log(nC)) 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, O(n2m)O(n^2 m) 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 O(mn)O(m\sqrt n) 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 O(nω)O(n^\omega) time, where ω\omega is the matrix-multiplication exponent.

Check your understanding

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?

  1. Hopcroft–Karp, after two-coloring the students
  2. Edmonds's blossom algorithm, or Micali–Vazirani
  3. A maximum flow from ss through every student, then every student again, to tt
  4. 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; M⊕M∗M \oplus M^* contains ∣M∗∣−∣M∣\abs{M^*} - \abs{M} disjoint augmenting paths.
  • Hopcroft–Karp flips a maximal set of disjoint shortest augmenting paths per phase; path lengths grow every phase, so O(n)O(\sqrt n) phases of O(m)O(m) give O(mn)O(m\sqrt n).
  • König: in bipartite graphs, maximum matching = minimum vertex cover, and the cover is read off the alternating-path search; Hall's condition ∣N(X)∣≥∣X∣\abs{N(X)} \ge \abs{X} characterizes matchings that saturate one side.
  • The Hungarian algorithm maintains dual potentials and tight edges and solves the assignment problem in O(n3)O(n^3); it is successive shortest paths for min-cost flow with Johnson-style reduced costs.
  • General graphs need Edmonds's blossoms (Micali–Vazirani: O(mn)O(m\sqrt n)); 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.

Question 1

A matching MM cannot be extended by adding any single edge. What follows?

  1. MM is maximum
  2. MM is maximum if the graph is bipartite
  3. MM is maximal, but it can still be smaller than a maximum matching, by up to a factor of 2
  4. MM is perfect
Show the answer

C. MM 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.

Question 2

Why does Hopcroft–Karp need only O(n)O(\sqrt n) phases?

  1. Each phase at least doubles the size of the matching
  2. Each phase matches at least n\sqrt n vertices
  3. Breadth-first search finds all augmenting paths at once
  4. After n\sqrt n phases every augmenting path is long, and the disjoint augmenting paths of M⊕M∗M \oplus M^* then number fewer than n\sqrt n
Show the answer

D. After n\sqrt n phases every augmenting path is long, and the disjoint augmenting paths of M⊕M∗M \oplus M^* then number fewer than n\sqrt n

Shortest augmenting paths get longer every phase. Once they exceed n\sqrt n edges, at most n\sqrt n vertex-disjoint ones fit in nn vertices, so the matching is fewer than n\sqrt n edges short of maximum, and each later phase gains at least one.

Question 3

In a bipartite graph, the left vertices 1, 2 and 3 are each adjacent only to the right vertices a and b. What follows?

  1. No matching saturates the left side; every matching leaves at least one of 1, 2, 3 unmatched
  2. A perfect matching may still exist if the right side is large enough
  3. The graph is not bipartite
  4. 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

X={1,2,3}X = \{1, 2, 3\} has ∣N(X)∣=2<3\abs{N(X)} = 2 < 3, 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 ∣L∣−1\abs{L} - 1 edges.

Question 4

The Hungarian algorithm stops with a perfect matching whose edges are all tight, ui+vj=ciju_i + v_j = c_{ij}, for feasible potentials. Why is that matching optimal?

  1. Because it was built greedily from the cheapest edges
  2. Because every row was matched to its cheapest column
  3. Because its cost equals ∑ui+∑vj\sum u_i + \sum v_j, which is a lower bound on the cost of every perfect matching
  4. Because the potentials are all non-negative
Show the answer

C. Because its cost equals ∑ui+∑vj\sum u_i + \sum v_j, which is a lower bound on the cost of every perfect matching

Feasibility gives ciσ(i)≥ui+vσ(i)c_{i\sigma(i)} \ge u_i + v_{\sigma(i)} for every perfect matching σ\sigma; summing, every matching costs at least ∑u+∑v\sum u + \sum v. 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 n5/2n^{5/2} 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 O(∣V∣ ∣E∣)O(\sqrt{|V|}\,|E|) algorithm for finding maximum matching in general graphs," Proceedings of the 21st IEEE Symposium on Foundations of Computer Science (1980).