Maximum matching of bipartite Hungarian Algorithm

The bipartite graph is a bipartite graph, i.e., a graph can be divided into two parts.

For example with men and women, boys and girls having an affair, between the same sex does not exist ambiguous (same-sex love is, just as heterosexual procreation) , there is an edge between them, then we can separate the boys, girls, boys on the left, girls on the right

We can be found in boys is not connected to the left side, girls on the right is, they exist only with the opposite sex opposite side, then this is a bipartite graph.

 

As for matching problem is also well understood, there can be seen as husband and wife, a boy can have several ambiguous opposite sex, but only one wife, the girls, too; a couple that is a set of matching

So in a given bipartite graph, find the maximum matching is that there is at most a few couples.

 

Seeking bipartite graph maximum matching Hungarian algorithm presented here:

The speaker of the Bo strong push Hungary: https://blog.csdn.net/dark_scope/article/details/8880547

 

Luo Gu given a template question: P3386 [template] bipartite graph matching

Here is my code:

1  / * 
2  bipartite graph maximum matching template
 . 3  CZQ
 . 4  * / 
. 5  
. 6 #include <cstdio>
 . 7 #include <CString>
 . 8 #include <the iostream>
 . 9  the using  namespace STD;
 10  const  int N = 1E3 + 10 ;
 . 11  
12 is  int n-, m, E;
 13 is  int Edges [N] [N];
 14  int VIS [N], REC [N];
 15  // REC recording pairing 
16  
. 17 inline BOOL match ( int now)
 18 is  {
19     for(int i = 1; i <= m; i++)
20     {
21         if(edges[now][i] == 1 && vis[i] == 0)
22         {
23             vis[i] = 1;
24             if(rec[i] == 0 || match(rec[i]))
25             {
26                 rec[i] = now;
27                 return true;
28             }
29         }
30     }
31     return false;
32 }
33 
34 int main()
35 {
36     memset(rec, 0, sizeof(rec));
37     memset(edges, 0, sizeof(edges));
38     cin >> n >> m >> e;
39     for(int i = 1; i <= e; i++)
40     {
41         int u, v;
42         cin >> u >> v;
43         edges[u][v] = 1;
44     }
45 
46     int ans = 0;
47 
48     for(int i = 1; i <= n; i++)
49     {
50         memset(vis, 0, sizeof(vis));
51         if(match(i))    ans++;
52     }
53 
54     cout << ans << endl;
55 
56     return 0;
57 }

 

P3386 [template] bipartite graph matching

P3386 [template] bipartite graph matching template P3386 [P3386] [bipartite graph matching bipartite graph matching template]

P3386 [template] bipartite graph matching

 

Guess you like

Origin www.cnblogs.com/nonameless/p/11762547.html