TExcelTAD
Home › Linear Programming & Duality for Algorithms › Bipartite Matching and König's Theorem

Bipartite Matching and König's Theorem

In any graph, a matching can use at most one edge at each vertex, and a vertex cover must contain an endpoint of each matching edge, so every matching is at most as large as every vertex cover. In a triangle the two numbers are 1 and 2. König's theorem (König, 1931) says that in a bipartite graph they are always equal. This lesson derives the theorem from LP duality plus integrality, explains what goes wrong for odd cycles, and then gives the constructive proof as an algorithm that outputs a maximum matching together with a vertex cover of the same size: a certificate that the matching is maximum. Maximum Bipartite Matching in Part I solved the same problem by reduction to max flow.

The LP pair

For a graph G=(V,E)G = (V, E), the fractional matching LP and its dual are

ν∗(G)=max⁡{∑exe:∑e∋vxe≤1 ∀v, x≥0},τ∗(G)=min⁡{∑vyv:yu+yv≥1 ∀uv∈E, y≥0}.\begin{aligned} \nu^*(G) = \max \Big\{ \sum_{e} x_e : \sum_{e \ni v} x_e \le 1 \ \forall v,\ x \ge 0 \Big\}, \qquad \tau^*(G) = \min \Big\{ \sum_v y_v : y_u + y_v \ge 1 \ \forall uv \in E,\ y \ge 0 \Big\} . \end{aligned}

Integer solutions of the first are matchings, integer solutions of the second (with y≤1y \le 1, automatic at an optimum) are vertex covers. With ν(G)\nu(G) and τ(G)\tau(G) the integer optima,

ν(G)≤ν∗(G)=τ∗(G)≤τ(G),\nu(G) \le \nu^*(G) = \tau^*(G) \le \tau(G),

where the middle equality is strong duality and the outer inequalities hold because restricting to integers can only make a max smaller and a min larger. König's theorem is the statement that for bipartite GG both outer inequalities are equalities. That follows from integrality: the vertex-edge incidence matrix of a bipartite graph is totally unimodular (Bipartite, Network and Interval Matrices), so both LPs have integral optimal vertices, so ν=ν∗\nu = \nu^* and τ∗=τ\tau^* = \tau.

The program computes all four numbers for a bipartite graph and for a 5-cycle, solving the integer versions by brute force.

python · try it yourself
from itertools import combinations
from scipy.optimize import linprog

def four_numbers(n, edges):
    inc = [[1 if v in e else 0 for e in edges] for v in range(n)]
    nu_star = -linprog([-1] * len(edges), A_ub=inc, b_ub=[1] * n, bounds=[(0, None)] * len(edges), method="highs").fun
    cover_rows = [[-1 if v in e else 0 for v in range(n)] for e in edges]
    tau_star = linprog([1] * n, A_ub=cover_rows, b_ub=[-1] * len(edges), bounds=[(0, None)] * n, method="highs").fun
    nu = max(k for k in range(len(edges) + 1) for M in combinations(edges, k)
             if len({v for e in M for v in e}) == 2 * k)
    tau = min(k for k in range(n + 1) for C in combinations(range(n), k) if all(u in C or v in C for u, v in edges))
    return nu, round(float(nu_star), 6), round(float(tau_star), 6), tau

bip = [(0, 4), (0, 5), (1, 4), (2, 5), (2, 6), (3, 6), (3, 7), (1, 7)]   # left 0-3, right 4-7
c5 = [(0, 1), (1, 2), (2, 3), (3, 4), (4, 0)]
for name, n, edges in [("bipartite", 8, bip), ("5-cycle", 5, c5)]:
    nu, nus, taus, tau = four_numbers(n, edges)
    print(f"{name:9}  nu = {nu}  nu* = {nus}  tau* = {taus}  tau = {tau}")
bipartite  nu = 4  nu* = 4.0  tau* = 4.0  tau = 4
5-cycle    nu = 2  nu* = 2.5  tau* = 2.5  tau = 3

On the bipartite graph all four numbers are 4. On the 5-cycle the LP value 52\frac{5}{2} sits strictly between ν=2\nu = 2 and τ=3\tau = 3: the all-12\frac{1}{2} vector is optimal on both sides, and neither inequality is tight.

A constructive proof

LP duality gives the theorem, but an algorithm gives more: a maximum matching and a cover of the same size, which together certify each other. The construction (König's original argument, in its algorithmic form) is:

  1. Find a maximum matching MM by repeatedly augmenting along alternating paths.
  2. Let ZZ be the set of vertices reachable from the unmatched left vertices by alternating paths (non-matching edges from left to right, matching edges from right to left).
  3. Output C=(L∖Z)∪(R∩Z)C = (L \setminus Z) \cup (R \cap Z).
text
KONIG-COVER(G = (L, R, E), maximum matching M)
1  Z = unmatched vertices of L
2  repeat until Z stops growing
3      for u in Z ∩ L, every edge uw not in M:   add w to Z
4      for w in Z ∩ R, the matching edge uw:      add u to Z
5  return (L \ Z) ∪ (R ∩ Z)

Why it works. Every vertex of R∩ZR \cap Z is matched (otherwise there would be an augmenting path and MM would not be maximum), and every vertex of L∖ZL \setminus Z is matched (unmatched left vertices are in ZZ). No matching edge joins L∖ZL \setminus Z to R∩ZR \cap Z (step 4 would have put its left end into ZZ). So CC contains exactly one endpoint of each matching edge, ∣C∣=∣M∣\lvert C \rvert = \lvert M \rvert. And CC is a cover: an edge uwuw with u∈L∩Zu \in L \cap Z has w∈Zw \in Z by step 3 (or by step 4 if uw∈Muw \in M), and an edge with u∉Zu \notin Z is covered by uu.

python · try it yourself
def max_matching(L, adj):
    match = {}                                     # vertex -> partner, both directions
    def augment(u, seen):
        for w in adj[u]:
            if w not in seen:
                seen.add(w)
                if w not in match or augment(match[w], seen):
                    match[u], match[w] = w, u
                    return True
        return False
    for u in L:
        augment(u, set())
    return match

def konig_cover(L, adj, match):
    Z = {u for u in L if u not in match}
    frontier = list(Z)
    while frontier:
        u = frontier.pop()
        for w in adj[u]:
            if w not in Z and match.get(u) != w:   # non-matching edge left -> right
                Z.add(w)
                if w in match and match[w] not in Z:   # matching edge right -> left
                    Z.add(match[w])
                    frontier.append(match[w])
    R = {w for u in L for w in adj[u]}
    return sorted(set(L) - Z) + sorted(R & Z)

L = ["a", "b", "c", "d", "e"]
adj = {"a": ["1", "2"], "b": ["1"], "c": ["1"], "d": ["2", "3", "4"], "e": ["4"]}
match = max_matching(L, adj)
pairs = sorted((u, match[u]) for u in L if u in match)
cover = konig_cover(L, adj, match)
edges = [(u, w) for u in L for w in adj[u]]
print("maximum matching:", pairs)
print("vertex cover:    ", cover)
print("sizes", len(pairs), "and", len(cover), "| covers every edge:", all(u in cover or w in cover for u, w in edges))
maximum matching: [('a', '2'), ('b', '1'), ('d', '3'), ('e', '4')]
vertex cover:     ['a', 'd', 'e', '1']
sizes 4 and 4 | covers every edge: True

Vertices aa, bb and cc compete for only two right vertices, so one of them stays unmatched. The alternating search from cc reaches 11 and then bb, so Z={c,1,b}Z = \{c, 1, b\} and the cover is {a,d,e,1}\{a, d, e, 1\}. It has the same size as the matching, so both are optimal: no larger matching and no smaller cover exists, and anyone can check this without rerunning the algorithm.

In C++

The same two steps with integer vertex ids: left vertices 0..40..4 and right vertices 0..40..4 in separate arrays.

cpp · try it yourself
#include <cstdio>
#include <vector>

int nl = 5, nr = 5;
std::vector<std::vector<int>> adj = {{0, 1}, {0}, {0}, {1, 2, 3}, {3}};   // left -> right
std::vector<int> matchL(nl, -1), matchR(nr, -1);

bool augment(int u, std::vector<bool>& seen) {
    for (int w : adj[u])
        if (!seen[w]) {
            seen[w] = true;
            if (matchR[w] < 0 || augment(matchR[w], seen)) { matchL[u] = w; matchR[w] = u; return true; }
        }
    return false;
}

int main() {
    int size = 0;
    for (int u = 0; u < nl; u++) { std::vector<bool> seen(nr, false); size += augment(u, seen); }
    std::vector<bool> zl(nl, false), zr(nr, false);
    std::vector<int> stack;
    for (int u = 0; u < nl; u++) if (matchL[u] < 0) { zl[u] = true; stack.push_back(u); }
    while (!stack.empty()) {
        int u = stack.back(); stack.pop_back();
        for (int w : adj[u])
            if (!zr[w] && matchL[u] != w) {
                zr[w] = true;
                if (matchR[w] >= 0 && !zl[matchR[w]]) { zl[matchR[w]] = true; stack.push_back(matchR[w]); }
            }
    }
    const char* left = "abcde";
    std::printf("matching size %d:", size);
    for (int u = 0; u < nl; u++) if (matchL[u] >= 0) std::printf(" %c-%d", left[u], matchL[u] + 1);
    std::printf("\ncover:");
    int csize = 0;
    for (int u = 0; u < nl; u++) if (!zl[u]) { std::printf(" %c", left[u]); csize++; }
    for (int w = 0; w < nr; w++) if (zr[w]) { std::printf(" %d", w + 1); csize++; }
    std::printf("\ncover size %d\n", csize);
}
matching size 4: a-2 b-1 d-3 e-4
cover: a d e 1
cover size 4

Weighted matchings: Egerváry's theorem

With edge weights wuv≥0w_{uv} \ge 0, the LP pair becomes max⁡∑ewexe\max \sum_e w_e x_e over the bipartite matching polytope and min⁡∑vyv\min \sum_v y_v subject to yu+yv≥wuvy_u + y_v \ge w_{uv}, y≥0y \ge 0. The matrix is the same, so for integer weights both optima are integral: the maximum weight of a matching equals the minimum total of integer vertex potentials that dominate every edge weight (Egerváry, 1931). The Hungarian method (Kuhn, 1955) is a primal-dual algorithm built on this: it keeps feasible potentials, matches only along tight edges (yu+yv=wuvy_u + y_v = w_{uv}, complementary slackness), and adjusts potentials when it gets stuck. The mini project uses this pair as its certificate.

python · try it yourself
from scipy.optimize import linprog

W = [[7, 5, 3], [6, 2, 4], [3, 8, 6]]            # w[i][j] for left i, right j
n = 3
cells = [(i, j) for i in range(n) for j in range(n)]
rows = [[1 if c[0] == i else 0 for c in cells] for i in range(n)] + [[1 if c[1] == j else 0 for c in cells] for j in range(n)]
primal = linprog([-W[i][j] for i, j in cells], A_ub=rows, b_ub=[1] * (2 * n), bounds=[(0, None)] * len(cells), method="highs")
chosen = [c for c, v in zip(cells, primal.x) if v > 0.5]
dual = linprog([1] * (2 * n), A_ub=[[-1 if k in (i, n + j) else 0 for k in range(2 * n)] for i, j in cells],
               b_ub=[-W[i][j] for i, j in cells], bounds=[(0, None)] * (2 * n), method="highs")
print("max weight matching:", chosen, "weight", round(float(-primal.fun), 6))
print("min total potential:", round(float(dual.fun), 6))
max weight matching: [(0, 0), (1, 2), (2, 1)] weight 19.0
min total potential: 19.0

Test yourself

For which graphs does ν(G)=τ(G)\nu(G) = \tau(G) (maximum matching = minimum vertex cover) always hold?

  1. All graphs
  2. Bipartite graphs
  3. Odd cycles
  4. Complete graphs

What are ν∗\nu^* and τ∗\tau^* for the 5-cycle?

  1. Both 2
  2. Both 52\frac{5}{2}
  3. 2 and 3
  4. 52\frac{5}{2} and 3

In König's construction, which vertices form the cover?

  1. All matched vertices
  2. (L∖Z)∪(R∩Z)(L \setminus Z) \cup (R \cap Z), with ZZ the vertices reachable from unmatched left vertices by alternating paths
  3. L∩ZL \cap Z
  4. The unmatched vertices