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 , the fractional matching LP and its dual are
Integer solutions of the first are matchings, integer solutions of the second (with , automatic at an optimum) are vertex covers. With and the integer optima,
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 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 and .
The program computes all four numbers for a bipartite graph and for a 5-cycle, solving the integer versions by brute force.
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 sits strictly between and : the all- 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:
- Find a maximum matching by repeatedly augmenting along alternating paths.
- Let 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).
- Output .
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 is matched (otherwise there would be an augmenting path and would not be maximum), and every vertex of is matched (unmatched left vertices are in ). No matching edge joins to (step 4 would have put its left end into ). So contains exactly one endpoint of each matching edge, . And is a cover: an edge with has by step 3 (or by step 4 if ), and an edge with is covered by .
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 , and compete for only two right vertices, so one of them stays unmatched. The alternating search from reaches and then , so and the cover is . 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 and right vertices in separate arrays.
#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 , the LP pair becomes over the bipartite matching polytope and subject to , . 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 (, complementary slackness), and adjusts potentials when it gets stuck. The mini project uses this pair as its certificate.
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 (maximum matching = minimum vertex cover) always hold?
- All graphs
- Bipartite graphs
- Odd cycles
- Complete graphs
What are and for the 5-cycle?
- Both 2
- Both
- 2 and 3
- and 3
In König's construction, which vertices form the cover?
- All matched vertices
- , with the vertices reachable from unmatched left vertices by alternating paths
- The unmatched vertices