Kuhn's algorithm — maximum matching in a bipartite graph
Kuhn's algorithm — maximum matching in a bipartite graph
Given a bipartite graph with parts:
- left: ,
- right: ,
Kuhn's algorithm — maximum matching in a bipartite graph
Given a bipartite graph with parts:
It is required to find a maximum matching — the maximum set of edges that do not share common vertices.
The Kuhn algorithm is a direct application of Berge's theorem:
A matching is maximum ⇔ there are no augmenting paths in the graph.
The algorithm works as follows:
An augmenting path is a path that:
After alternating edges along the path, the size of the matching increases by 1.
For a vertex of the left part:
That is:
→ connect with
For all :
Each DFS —
Run up to times:
In the worst case:
Important:
int n, k;
vector<vector<int>> g;
vector<int> mt;
vector<char> used;
bool try_kuhn(int v) {
if (used[v]) return false;
used[v] = true;
for (int to : g[v]) {
if (mt[to] == -1 || try_kuhn(mt[to])) {
mt[to] = v;
return true;
}
}
return false;
}
int main() {
// reading the graph
mt.assign(k, -1);
for (int v = 0; v < n; v++) {
used.assign(n, false);
try_kuhn(v);
}
// output the matching
for (int i = 0; i < k; i++) {
if (mt[i] != -1) {
cout << mt[i] + 1 << " " << i + 1 << "\n";
}
}
}