Matrix_code

flow - MaxFlow Dinic

Apr 25th, 2016 (edited)
186
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.17 KB | None | 0 0
  1. /*
  2.  
  3.  Maxflow Dinic Implementation. Work for both directed and Undirected Graph
  4.  Complexity : V^2E
  5.  
  6.  * init(number_of_node)
  7.  * addEdge(from, to, cap)
  8.  * dinitz(source,dest)
  9.  
  10.  $ MAXNODE : 3000
  11.  $ For Undirected Graph : edge and reverse edge capacity = cap
  12.  
  13.  */
  14. #include<bits/stdc++.h>
  15. using namespace std;
  16. const int maxn = 1005;
  17. const int INF = 1e9;
  18. typedef int T;
  19. struct Edge
  20. {
  21.     int u, v;
  22.     T cap, flow;
  23.     Edge(int u, int v, T c, T f):u(u), v(v), cap(c), flow(f) {}
  24. };
  25.  
  26. struct Dinic
  27. {
  28.     int n, m, s, t;
  29.     vector<Edge> edge;
  30.     vector<int> G[maxn];
  31.     bool vis[maxn];
  32.     int d[maxn];
  33.     int cur[maxn];
  34.    
  35.     void init(int n)
  36.     {
  37.         this->n=n;
  38.         for(int i=0; i<=n; i++) G[i].clear();
  39.         edge.clear();
  40.     }
  41.    
  42.     void addEdge(int u, int v, T cap)
  43.     {
  44.         edge.push_back(Edge(u, v, cap, 0)); edge.push_back(Edge(v, u, 0, 0));
  45.         m=edge.size();
  46.         G[u].push_back(m-2); G[v].push_back(m-1);
  47.     }
  48.    
  49.     bool bfs()
  50.     {
  51.         memset(vis, 0, sizeof vis);
  52.         queue<int> q;
  53.         q.push(s);
  54.         d[s]=0;
  55.         vis[s]=1;
  56.         while(!q.empty()){
  57.             int x=q.front();q.pop();
  58.             for(int i=0; i<G[x].size(); i++){
  59.                 Edge& e=edge[G[x][i]];
  60.                 if(!vis[e.v] && e.cap>e.flow){
  61.                     vis[e.v]=true;
  62.                     d[e.v]=d[x]+1;
  63.                     q.push(e.v);
  64.                 }
  65.             }
  66.         }
  67.         return vis[t];
  68.     }
  69.    
  70.     T dfs(int x, T a)
  71.     {
  72.         if(x==t || a==0)return a;
  73.         T flow=0, f;
  74.         for(int& i=cur[x]; i<G[x].size(); i++){
  75.             Edge& e=edge[G[x][i]];
  76.             if(d[x]+1==d[e.v] && (f=dfs(e.v, min(a, e.cap-e.flow)))>0){
  77.                 e.flow+=f;
  78.                 edge[G[x][i]^1].flow-=f;
  79.                 flow+=f;
  80.                 a-=f;
  81.                 if(a==0)break;
  82.             }
  83.         }
  84.         return flow;
  85.     }
  86.    
  87.     T dinitz(int s, int t)
  88.     {
  89.         this->s=s;
  90.         this->t=t;
  91.         T flow=0;
  92.         while(bfs()){
  93.             memset(cur, 0, sizeof cur);
  94.             flow+=dfs(s, INF);
  95.         }
  96.         return flow;
  97.     }
  98. } maxf;
Add Comment
Please, Sign In to add comment