[模板]匈牙利演算法 (二分圖最大匹配)
阿新 • • 發佈:2020-07-31
每次都去找想要的點,如果當前已經被佔用了,那麼標記一下,然後去找這個點的主人是否還有其他能連的點,若有,連這個點,然後當前的這個點就能連自己想要的點了
程式碼:
#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; }