templates/kuhn-matching.cpp
compilable
$cat templates/kuhn-matching
Kuhn's Matching
Maximum bipartite matching via augmenting paths in O(V*E).
#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
timer avoids resetting the vis array each iteration