Hungarian Algorithm bipartite

   Algorithms for bipartite graph - Hungary

  • example:

https://www.luogu.org/problem/P3386

  • Ideas:

First, find a bipartite graph is a bunch of things (such as dogs), like some of the things (such as meat), but they like different meats, seeking to maximize the number of dogs to meet the problem. So we can draw a map, put the dog in the side, put the meat on the side. If the i-dogs, like the j-th meat, then, from the i -> j even a directed edge. We then dfs greedy thoughts. We define choose [i] denotes the i th meat is obtained first choose [i] dog. Then we define a vis the array to prevent infinite loop. We enumerate 1 ~ n, dfs is determined whether the i dogs eat meat. dfs, we enumerate i liked the meat, if the j-th meat is not eaten || eat this meat dog can eat other meat, then return 1 (and current dog can eat meat), otherwise return 0 . If you return 1, it ans ++ (and can eat their favorite dog meat number ++). Note: Each dfs have to put vis empty. The last answer is ans. 

  • Code:
 1 #include <bits/stdc++.h>
 2 #define INF 0x3f3f3f3f
 3 using namespace std;
 4 int n, m, edge, head[100001], vis[100001], choose[100001], num, ans;
 5 struct node
 6 {
 7     int next, to;
 8 }stu[10000001];
 9 inline void add(int x, int y)//存图 
10 {
11     stu[++num].next = head[x];
12 is      STU [NUM] .to = Y;
 13 is      head [X] = NUM;
 14      return ;
 15  }
 16 inline int DFS ( int U) // greedy DFS 
. 17  {
 18 is      for (Register int I = head [U]; I ; STU I = [I] .next) // enumeration something like this point 
. 19      {
 20 is          int K = STU [I] .to;
 21 is          IF (VIS [K])
 22 is          {
 23 is              Continue ;
 24          }
 25          VIS [k] =. 1 ;
 26 is          IF (the Choose [K] || DFS (the Choose [K])!) // If something unwanted or to the person to be something else 
27          {
 28              the Choose [K] = U; // this owner things became u a 
29              return  . 1 ;
 30          }
 31 is      }
 32      return  0 ;
 33 is  }
 34 is  Signed main ()
 35  {
 36      Scanf ( " % D% D% D " , & n-, & m, & Edge);
 37 [      for (Register int I = . 1 , X, Y; I <= Edge; ++I)
 38 is      {
 39          Scanf ( " % D% D " , & X, & Y);
 40          IF (X> n-|| Y> m) // Laid determination at 
41 is          {
 42 is              Continue ;
 43 is          }
 44 is          the Add (X, Y ); // build edge 
45      }
 46 is      for (Register int I = . 1 ; I <= n-; ++ I)
 47      {
 48          Memset (VIS, 0 , the sizeof (VIS)); // Clear 
49         DFS = + ANS (I); // direct enough + 
50      }
 51 is      the printf ( " % D " , ANS);
 52 is      return  0 ;
 53 is }

 

Guess you like

Origin www.cnblogs.com/qqq1112/p/11620774.html