Corezzi

Dinic

Feb 18th, 2019
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.57 KB | None | 0 0
  1. class Dinic{
  2.     struct Edge{
  3.         int to;
  4.         int c;
  5.         int flow;
  6.     };
  7.    
  8.     vector<Edge> edges;
  9.     vector<vector<int>> g;
  10.     vector<int> lvl;
  11.     int s,t;
  12.     const int INF = 100000;
  13.     const int VCOUNT;
  14.    
  15. public:
  16.     Dinic(int VCOUNT) : VCOUNT(VCOUNT), g(VCOUNT), lvl(VCOUNT){}
  17.  
  18.     void addEdge(int u, int v, int cap){
  19.         Edge dir = {v,cap,0};
  20.         Edge aug = {u,0,0};
  21.         g[u].push_back(edges.size());
  22.         edges.push_back(dir);
  23.         g[v].push_back(edges.size());
  24.         edges.push_back(aug);
  25.     }
  26.    
  27.     void clearAll(){
  28.         for(auto &a : g)a.clear();
  29.         edges.clear();
  30.     }
  31.    
  32.     void clearFlow(){
  33.         for(auto &e : edges)e.flow = 0;
  34.     }
  35.    
  36.     bool BFS(){
  37.         fill(lvl.begin(), lvl.end(), -1);
  38.         queue<int> q;
  39.         q.push(s);
  40.         lvl[s] = 0;
  41.        
  42.         while(!q.empty()){
  43.             int v = q.front(); q.pop();
  44.             if(v == t) break;
  45.            
  46.             for(auto u : g[v]){
  47.                 Edge &e = edges[u];
  48.                 if(lvl[e.to] < 0 && e.flow < e.c){
  49.                     lvl[e.to] = lvl[v] + 1;
  50.                     q.push(e.to);
  51.                 }
  52.             }
  53.         }
  54.        
  55.         return lvl[t] != -1;
  56.     }
  57.    
  58.     int DFS(int v, int minFlow){
  59.         if(v == t || minFlow == 0) return minFlow;
  60.         int flow = 0;
  61.        
  62.         for(auto adj : g[v]){
  63.             Edge &e = edges[adj];
  64.             if(lvl[e.to] == lvl[v]+1 && e.flow < e.c){
  65.                 int ret = DFS(e.to, min(minFlow, e.c - e.flow));
  66.                 if(ret > 0){
  67.                     e.flow += ret;
  68.                     edges[adj^1].flow -= ret;
  69.                     flow += ret;
  70.                     minFlow -= ret;
  71.                     if(ret <= 0)break;
  72.                 }
  73.             }
  74.         }
  75.        
  76.         return flow;
  77.     }
  78.    
  79.     int maxFlow(int s, int t){
  80.         this->s = s;
  81.         this->t = t;
  82.        
  83.         int mf = 0;
  84.         while(BFS()){
  85.             int f = DFS(s, INF);
  86.             mf += f;
  87.             if(f == 0) break;
  88.         }
  89.        
  90.         return mf;
  91.     }
  92. };
Advertisement
Add Comment
Please, Sign In to add comment