Matrix_code

flow - Hungarian

Oct 1st, 2017 (edited)
149
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.10 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N = 55;
  5.  
  6. typedef int Type;
  7. const Type INF = 0x3f3f3f3f;
  8.  
  9. struct Hungary {
  10.     int n, m;                 // left and right side dimension
  11.     Type g[N][N];             // Given Matrix
  12.     Type Lx[N], Ly[N], slack[N];
  13.     int left[N], right[N];    // Matching vertex of other side
  14.     bool S[N], T[N];          // Status of Left and right
  15.  
  16.     void init(int n, int m) {
  17.         this->n = n;
  18.         this->m = m;
  19.         memset(g, 0, sizeof(g));
  20.     }
  21.     bool dfs(int i) {
  22.         S[i] = true;
  23.         for (int j = 0; j < m; j++) {
  24.             if (T[j]) continue;
  25.             Type tmp = Lx[i] + Ly[j] - g[i][j];
  26.             if (!tmp) {
  27.                 T[j] = true;
  28.                 if (left[j] == -1 || dfs(left[j])) {
  29.                     left[j] = i;
  30.                     right[i] = j;
  31.                     return true;
  32.                 }
  33.             } else slack[j] = min(slack[j], tmp);
  34.         }
  35.         return false;
  36.     }
  37.  
  38.     void update() {
  39.         Type a = INF;
  40.         for (int i = 0; i < m; i++)
  41.             if (!T[i]) a = min(a, slack[i]);
  42.         for (int i = 0; i < n; i++)
  43.             if (S[i]) Lx[i] -= a;
  44.         for (int i = 0; i < m; i++)
  45.             if (T[i]) Ly[i] += a;
  46.     }
  47.  
  48.     Type km() {
  49.         memset(left, -1, sizeof(left));
  50.         memset(right, -1, sizeof(right));
  51.         memset(Ly, 0, sizeof(Ly));
  52.         for (int i = 0; i < n; i++) {
  53.             Lx[i] = -INF;
  54.             for (int j = 0; j < m; j++)
  55.                 Lx[i] = max(Lx[i], g[i][j]);
  56.         }
  57.         for (int i = 0; i < n; i++) {
  58.             for (int j = 0; j < m; j++) slack[j] = INF;
  59.             while (1) {
  60.                 memset(S, false, sizeof(S));
  61.                 memset(T, false, sizeof(T));
  62.                 if (dfs(i)) break;
  63.                 else update();
  64.             }
  65.         }
  66.         Type ans = 0;
  67.         for (int i = 0; i < n; i++) {
  68.             //if (right[i] == -1) return -1;
  69.             //if (g[i][right[i]] == -INF) return -1;
  70.             ans += g[i][right[i]];
  71.         }
  72.         return ans;
  73.     }
  74. } h;
Add Comment
Please, Sign In to add comment