RaFiN_

Dinic

Mar 28th, 2019
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.98 KB | None | 0 0
  1. const int MAX=10100;
  2. int que[MAX];
  3. template <class T>
  4. struct Edge {
  5.    int to, next;
  6.    T cap, flow;
  7.    Edge(int to, int next, T cap) {
  8.       this->to = to;
  9.       this->next = next;
  10.       this->cap = cap;
  11.       this->flow = 0;
  12.    }
  13. };
  14. template <class T>
  15. struct Dinic {
  16.    T INF;
  17.    const int nodes;
  18.    int source, sink, lvl[MAX], nodeEnd[MAX], last[MAX];
  19.    vector < Edge <T> > edgeList;
  20.  
  21.    Dinic(int n) : nodes(n), INF(numeric_limits<T>::max() / 4) { fill(nodeEnd, nodeEnd+n, -1); }
  22.    void addEdge(int u, int v, T cap = 1) {
  23.       edgeList.push_back(Edge<T> (v, nodeEnd[u], cap));
  24.       nodeEnd[u] = (int)edgeList.size()-1;
  25.       edgeList.push_back(Edge<T> (u, nodeEnd[v], 0));
  26.       nodeEnd[v] = (int)edgeList.size()-1;
  27.    }
  28.  
  29.    // bfs
  30.    bool createLevel() {
  31.       memset(lvl, -1, nodes * sizeof(int));
  32.       int qs = 0, qt = 0;
  33.       que[qs] = source, lvl[source] = 0;
  34.  
  35.       while(qs <= qt) {
  36.          int nd = que[qs++], ch;
  37.          for(int i = nodeEnd[nd]; i != -1; i = edgeList[i].next)
  38.             if(lvl[ch = edgeList[i].to] == -1 && edgeList[i].cap > edgeList[i].flow)
  39.                lvl[ch] = lvl[nd] + 1, que[++qt] = ch;
  40.       }
  41.  
  42.       return lvl[sink] != -1;
  43.    }
  44.  
  45.    // dfs
  46.    T blockingFlow(int nd, T flow) {
  47.       if(nd == sink) return flow;
  48.       int ch;
  49.       T pflow = flow;
  50.  
  51.       for(int &i = last[nd]; i != -1; i = edgeList[i].next) if(lvl[ch = edgeList[i].to] == lvl[nd]+1) {
  52.          T pushed = blockingFlow(ch, min(pflow, edgeList[i].cap - edgeList[i].flow));
  53.          pflow -= pushed;
  54.          edgeList[i].flow += pushed;
  55.          edgeList[i ^ 1].flow -= pushed;
  56.          if(!pflow) break;
  57.       }
  58.  
  59.       return flow - pflow;
  60.    }
  61.  
  62.    T maxFlow(int src, int snk) {
  63.       //REP(i, edgeList.size()) edgeList[i].flow = 0;
  64.       source = src, sink = snk;
  65.       T tot = 0;
  66.  
  67.       while(createLevel()) {
  68.          memcpy(last, nodeEnd, nodes * sizeof(int));
  69.          tot += blockingFlow(source, INF);
  70.       }
  71.  
  72.       return tot;
  73.    }
  74. };
Add Comment
Please, Sign In to add comment