Advertisement
Matrix_code

graph - Maximum Bipartite Matching Hopcroft-karp

May 1st, 2016 (edited)
139
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.33 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define MAX 20001
  5. #define NIL 0
  6. #define INF (1 << 28)
  7.  
  8. vector<int> G[MAX];
  9. int n, m, match[MAX], dist[MAX];
  10. // n: number of nodes on left side, nodes are numbered 1 to n
  11. // m: number of nodes on right side, nodes are numbered n+1 to n+m
  12. // G = NIL[0] ∪ G1[G[1---n]] ∪ G2[G[n+1---n+m]]
  13.  
  14. bool bfs() {
  15.   int i, u, v, len;
  16.   queue<int> Q;
  17.   for (i = 1; i <= n; i++) {
  18.     if (match[i] == NIL) {
  19.       dist[i] = 0;
  20.       Q.push(i);
  21.     } else
  22.       dist[i] = INF;
  23.   }
  24.   dist[NIL] = INF;
  25.   while (!Q.empty()) {
  26.     u = Q.front();
  27.     Q.pop();
  28.     if (u != NIL) {
  29.       for (auto &v : G[u])
  30.         if (dist[match[v]] == INF) {
  31.           dist[match[v]] = dist[u] + 1;
  32.           Q.push(match[v]);
  33.         }
  34.     }
  35.   }
  36.   return (dist[NIL] != INF);
  37. }
  38.  
  39. bool dfs(int u) {
  40.   int i, v, len;
  41.   if (u != NIL) {
  42.     for (auto v : G[u])
  43.       if (dist[match[v]] == dist[u] + 1) {
  44.         if (dfs(match[v])) {
  45.           match[v] = u;
  46.           match[u] = v;
  47.           return true;
  48.         }
  49.       }
  50.     dist[u] = INF;
  51.     return false;
  52.   }
  53.   return true;
  54. }
  55.  
  56. int hopcroft_karp() {
  57.   int matching = 0, i;
  58.   memset(match, NIL, sizeof match);
  59.   while (bfs()) {
  60.     for (i = 1; i <= n; i++)
  61.       if (match[i] == NIL && dfs(i))
  62.         matching++;
  63.   }
  64.   return matching;
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement