匈牙利算法

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <string.h>
 4 using namespace std;
 5 const int N = 509,M = 100009;
 6 int n1,n2,m,idx,res;
 7 int h[N],e[M],ne[M];
 8 int match[N];
 9 bool st[N];
10 
11 void add(int a,int b)
12 {
13     e[idx] = b;
14     ne[idx] = h[a];
15     h[a] = idx++;
16 }
17 
18 bool find(int x)
19 {
20     for(int i = h[x];i != -1;i = ne[i])
21     {
22         int j = e[i];
23         if(!st[j])
24         {
25             st[j] = true;
26             if(!match[j] || find(match[j]))
27             {
28                 match[j] = x;
29                 return true;
30             }
31         }
32     }
33     return false;
34 }
35 
36 int main()
37 {
38     memset(h,-1,sizeof h);
39     cin >> n1 >> n2 >> m;
40     while(m--)
41     {
42         int a,b;
43         cin >> a >> b;
44         add(a,b);
45     }
46     
47     for(int i = 1;i <= n1;++i)
48     {
49         memset(st,false,sizeof st);
50         if(find(i)) res++;
51     }
52     cout << res << endl;
53     return 0;
54 }

 

posted @ 2021-10-22 21:35  Modest-Hamilton  阅读(93)  评论(0)    收藏  举报