Advertisement
Guest User

MCMF

a guest
Oct 24th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.83 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int N, M;
  5.  
  6. typedef pair<int, int> pii;
  7. const int INF = 1e9;
  8. typedef struct MCMF {
  9.     typedef struct EDGE {
  10.         int there, cap, cost, rev;
  11.  
  12.         EDGE() : there(0), cap(0), cost(0), rev(0) {}
  13.         EDGE(int there, int cap, int cost, int rev) : there(there), cap(cap), cost(cost), rev(rev) {}
  14.     };
  15.  
  16.     int N;
  17.     vector<vector<EDGE>> ADJ;
  18.     vector<int> R, INQ, C, I;
  19.  
  20.     MCMF() : N(0) {}
  21.     MCMF(int N) : N(N) { ADJ.resize(N + 1); R.resize(N + 1); INQ.resize(N + 1);  C.resize(N + 1); I.resize(N + 1); }
  22.  
  23.     void connect_edge(int index1, int index2, int cap, int cost) {
  24.         ADJ[index1].push_back(EDGE(index2, cap, cost, ADJ[index2].size()));
  25.         ADJ[index2].push_back(EDGE(index1, 0, -cost, ADJ[index1].size() - 1));
  26.     }
  27.     bool SPFA(int src, int sink) {
  28.         queue<int> Q;   Q.push(src);
  29.         fill(R.begin(), R.end(), -1);   R[src] = 0;
  30.         fill(C.begin(), C.end(), -1);   C[src] = 0;
  31.         fill(INQ.begin(), INQ.end(), 0);    INQ[src] = 1;
  32.         while (Q.size()) {
  33.             int here = Q.front();   Q.pop();
  34.             INQ[here] = 0;
  35.             for (int i = 0; i < ADJ[here].size(); i++) {
  36.                 auto e = ADJ[here][i];
  37.                 if (e.cap > 0 && (C[e.there] == -1 || C[e.there] > C[here] + e.cost)) {
  38.                     C[e.there] = C[here] + e.cost;  R[e.there] = here;  I[e.there] = i;
  39.                     if (!INQ[e.there]) INQ[e.there] = 1, Q.push(e.there);
  40.                 }
  41.             }
  42.         }
  43.         if (C[sink] == -1) return false;
  44.         return true;
  45.     }
  46.  
  47.     pii mcmf(int src, int sink) {
  48.         pii ret = { 0, 0 };
  49.         while (SPFA(src, sink)) {
  50.             int flow = INF, cost = 0;
  51.             for (int here = sink; here != src; here = R[here]) flow = min(flow, ADJ[R[here]][I[here]].cap);
  52.             for (int here = sink; here != src; here = R[here]) {
  53.                 auto &e = ADJ[R[here]][I[here]];
  54.                 cost += e.cost * flow;
  55.                 e.cap -= flow;
  56.                 ADJ[e.there][e.rev].cap += flow;
  57.             }
  58.  
  59.             ret.first += flow, ret.second += cost;
  60.         }
  61.         return ret;
  62.     }
  63. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement