图算法--二分图的最大匹配(匈牙利算法)

二分图的最大匹配的意思就是给定一个二分图,找出最多的边,使得一个点不会同时在两条边的端点上。

举个例子就是,有一堆男生和一堆女生,每个男生和某些女生相互之间有一定的好感度,我们作为月老,秉持宁拆一座庙,不毁一桩婚的原则,希望最后的配对数目最多。

而匈牙利算法就是解决这样一个问题的算法。

匈牙利算法的理论最坏复杂度为O(n*m),但是一般不会达到这么高,是一个在实际运行过程中表现较好的算法。

 1 #include<iostream>
 2 #include<cstring>
 3 using namespace std;
 4 const int N=510,M=1e5+10;
 5 int n1,n2,m;
 6 int h[N],e[M],ne[M],idx;
 7 int match[N];
 8 bool st[N];
 9 void add(int a,int b){
10     e[idx]=b,ne[idx]=h[a],h[a]=idx++;
11 }
12 int find(int x){
13     for(int i=h[x];i!=-1;i=ne[i]){
14         int j=e[i];
15         if(!st[j]){
16             st[j]=true;
17             if(match[j]==0||find(match[j])){
18                 match[j]=x;
19                 return true;
20             }
21         }
22     }
23     return false;
24 }
25 int main(void){
26     memset(h,-1,sizeof(h));
27     cin>>n1>>n2>>m;
28     for(int i=0;i<m;i++){
29         int a,b;
30         cin>>a>>b;
31         add(a,b);
32     }
33     int res=0;
34     for(int i=1;i<=n1;i++){
35         memset(st,0,sizeof(st));
36         if(find(i)){
37             res++;
38         }
39     }
40     cout<<res;
41     return 0;
42 }
原文地址:https://www.cnblogs.com/greenofyu/p/14030078.html