匈牙利算法模板
代码
\(m\)为左端点 , \(n\)为右端点 , \(e\)为边数
#include<bits/stdc++.h>
using namespace std;
const int N = 5e4+10;
inline int read() {
int ans = 0, f = 1;
char ch = getchar();
while (ch < '0' || ch > '9') {
if (ch == '-')f = -1;
ch = getchar();
}
while (ch <= '9' && ch >= '0') {
ans = ans * 10 + ch - '0';
ch = getchar();
}
return ans * f;
}
vector<int> ed[N];
bool vis[N];
int n,m,e,u,v,ans , match[N];
bool dfs(int u) {
for (auto e : ed[u]) {
if (vis[e])
continue;
vis[e] = true;
if (!match[e] || dfs(match[e])) {
match[e] = u;
return true;
}
}
return false;
}
int main() {
n =read() , m=read() , e=read();
for (int i =1;i<= e; i++) {
u =read(),v=read();
ed[u].push_back(n+v);
}
for (int i = 1; i<= n;i++) {
memset(vis,false,sizeof vis);
if (dfs(i))ans++;
}
cout<<ans;
return 0;
}

浙公网安备 33010602011771号