guest@cp-base:~/home/graph$
templates/kuhn-matching.cpp
compilable
$cat templates/kuhn-matching

Kuhn's Matching

Maximum bipartite matching via augmenting paths in O(V*E).

[Graph]|
Jul 9, 2026
|explanatory_notes.md|
#bipartite#matching#kuhn#augmenting-path
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <bits/stdc++.h>
using namespace std;

const int MAXN = 2e5 + 5;
vector<int> adj[MAXN];
int match_r[MAXN], vis[MAXN];
int timer;

bool dfs(int u) {
    if (vis[u] == timer) return false;
    vis[u] = timer;
    for (int v : adj[u])
        if (match_r[v] == -1 || dfs(match_r[v]))
            return match_r[v] = u, true;
    return false;
}

int maxMatching(int n) {
    memset(match_r, -1, sizeof match_r);
    int ans = 0;
    for (int i = 1; i <= n; i++) {
        timer++;
        ans += dfs(i);
    }
    return ans;
}
26 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)

Kuhn's Matching

Finds maximum cardinality matching in a bipartite graph by repeatedly searching for augmenting paths.

How It Works

  • For each left vertex, DFS tries to find an augmenting path to an unmatched right vertex

  • If a right vertex is already matched, recursively try to reassign its current match

  • Rolling counter timer avoids resetting the vis array each iteration
  • Key Definitions

  • Matching — set of edges where no two share a vertex

  • Augmenting path — alternating path from unmatched left to unmatched right vertex

  • Maximum matching — matching with the greatest number of edges
  • When to Use

  • Bipartite matching problems (job assignment, pairing)

  • As a building block for vertex cover, independent set (via Konig's theorem)
  • Complexity

  • Time — O(VE)O(V \cdot E)

  • Space — O(V+E)O(V + E)