利用匈牙利算法实现二分图最大匹配
主要是递归和贪心的思想
Code:
1 #include<bits/stdc++.h> 2 #define LL long long 3 #define rg register 4 #define us unsigned 5 #define eps 1e-6 6 #define INF 0x3f3f3f3f 7 #define ls k<<1 8 #define rs k<<1|1 9 #define tmid (tr[k].l+tr[k].r)>>1 10 #define nmid (l+r)>>1 11 #define Thispoint tr[k].l==tr[k].r 12 #define pushup tr[k].wei=tr[ls].wei+tr[rs].wei 13 using namespace std; 14 inline void Read(int &x){ 15 int f=1; 16 char c=getchar(); 17 x=0; 18 while(c<'0'||c>'9'){ 19 if(c=='-')f=-1; 20 c=getchar(); 21 } 22 while(c>='0'&&c<='9'){ 23 x=(x<<3)+(x<<1)+c-'0'; 24 c=getchar(); 25 } 26 x*=f; 27 } 28 inline void Print(int x){ 29 if(x<0){ 30 x=~(x-1); 31 putchar('-'); 32 } 33 if(x>9)Print(x/10); 34 putchar(x%10+'0'); 35 } 36 #define N 1010 37 int n,m,e,ans,match[N]; 38 bool mp[N][N],vis[N]; 39 bool DFS(int x){ 40 for(int i=1;i<=m;i++){ 41 if(!vis[i]&&mp[x][i]){ 42 vis[i]=1; 43 if(!match[i]||DFS(match[i])){ 44 match[i]=x; 45 return 1; 46 } 47 } 48 } 49 return 0; 50 } 51 int main(){ 52 Read(n),Read(m),Read(e); 53 for(int i=1;i<=e;i++){ 54 int u,v; 55 Read(u),Read(v); 56 if(v<=m&&u<=n)mp[u][v]=1; 57 } 58 for(int i=1;i<=n;i++){ 59 ans+=DFS(i); 60 memset(vis,0,sizeof(vis)); 61 } 62 Print(ans); 63 return 0; 64 }