Advertisement
Dang_Quan_10_Tin

HopCroft_Karp

Nov 8th, 2020 (edited)
230
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. struct HopCroft_Karp
  2. {
  3.     const int NoMatch = -1;
  4.     vector<int> h, S, match;
  5.     vector<vector<int>> adj;
  6.     int nx, ny;
  7.     bool found;
  8.     HopCroft_Karp(int nx = 0, int ny = 0)
  9.     {
  10.         this->nx = nx;
  11.         this->ny = ny;
  12.         S.reserve(nx);
  13.         h.resize(ny + 5);
  14.         adj.resize(nx + 5);
  15.         match.resize(ny + 5, NoMatch);
  16.     }
  17.     void Clear()
  18.     {
  19.         for (int i = 1; i <= nx; ++i)
  20.             adj[i].clear();
  21.         S.clear();
  22.         fill(match.begin(), match.end(), NoMatch);
  23.     }
  24.     void AddEdge(int x, int y)
  25.     {
  26.         adj[x].emplace_back(y);
  27.     }
  28.     bool BFS()
  29.     {
  30.         fill(h.begin(), h.end(), 0);
  31.         queue<int> q;
  32.         for (auto x : S)
  33.             for (auto i : adj[x])
  34.                 if (h[i] == 0)
  35.                 {
  36.                     q.emplace(i);
  37.                     h[i] = 1;
  38.                 }
  39.         while (q.size())
  40.         {
  41.             int x, ypop = q.front();
  42.             q.pop();
  43.             if ((x = match[ypop]) == NoMatch)
  44.                 return true;
  45.             for (auto i : adj[x])
  46.                 if (h[i] == 0)
  47.                 {
  48.                     h[i] = h[ypop] + 1;
  49.                     q.emplace(i);
  50.                 }
  51.         }
  52.         return false;
  53.     }
  54.     void dfs(int v, int lv)
  55.     {
  56.         for (auto i : adj[v])
  57.             if (h[i] == lv + 1)
  58.             {
  59.                 if (match[i] == NoMatch)
  60.                     found = 1;
  61.                 else
  62.                     dfs(match[i], lv + 1);
  63.                 if (found)
  64.                 {
  65.                     match[i] = v;
  66.                     return;
  67.                 }
  68.             }
  69.     }
  70.     int MaxMatch()
  71.     {
  72.         int ans(0);
  73.         for (int i = 1; i <= nx; ++i)
  74.             S.emplace_back(i);
  75.         while (BFS())
  76.         {
  77.             for (int i = S.size() - 1; ~i; --i)
  78.             {
  79.                 found = 0;
  80.                 dfs(S[i], 0);
  81.                 if (found)
  82.                 {
  83.                     ++ans;
  84.                     S[i] = S.back();
  85.                     S.pop_back();
  86.                 }
  87.             }
  88.         }
  89.         return ans;
  90.     }
  91.  
  92. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement