[模板]匈牙利算法 (二分图最大匹配)
每次都去找想要的点,如果当前已经被占用了,那么标记一下,然后去找这个点的主人是否还有其他能连的点,若有,连这个点,然后当前的这个点就能连自己想要的点了
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <set>
#include <unordered_set>
#include <unordered_map>
#define ll long long
#define fi first
#define se second
#define pb push_back
#define me memset
const int N = 1e6 + 10;
const int mod = 1e9 + 7;
const int INF = 0x3f3f3f3f;
using namespace std;
typedef pair<int,int> PII;
typedef pair<ll,ll> PLL;
int n,m,e;
vector<int> v[N];
bool st[N];
int match[N];
bool find(int x){
for(auto w:v[x]){
if(!st[w]){
st[w]=true;
if(match[w]==0 || find(match[w])){
match[w]=x;
return true;
}
}
}
return false;
}
int main() {
//ios::sync_with_stdio(false);cin.tie(0);cout.tie(0);
scanf("%d %d %d",&n,&m,&e);
for(int i=1;i<=e;++i){
int a,b;
scanf("%d %d",&a,&b);
v[a].pb(b);
}
int res=0;
for(int i=1;i<=n;++i){
me(st,false,sizeof(st));
if(find(i)) res++;
}
printf("%d\n",res);
return 0;
}
𝓐𝓬𝓱𝓲𝓮𝓿𝓮𝓶𝓮𝓷𝓽 𝓹𝓻𝓸𝓿𝓲𝓭𝓮𝓼 𝓽𝓱𝓮 𝓸𝓷𝓵𝔂 𝓻𝓮𝓪𝓵
𝓹𝓵𝓮𝓪𝓼𝓾𝓻𝓮 𝓲𝓷 𝓵𝓲𝓯𝓮