Advertisement
royalsflush

Dinic

Sep 7th, 2012
52
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.71 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <algorithm>
  3. #include <string.h>
  4. #include <queue>
  5. using namespace std;
  6.  
  7. #define MAXV 5010
  8. #define MAXE 30010
  9.  
  10. const int inf = 0x3f3f3f3f;
  11. const long long llinf = 30000LL*100000000000LL;
  12.  
  13. struct edge {
  14.     long long c,f;
  15.     int src,dst,prev;
  16. };
  17.  
  18. edge ls[2*MAXE];
  19. int lastEdge[MAXV];
  20. int currEdge[MAXV];
  21. int d[MAXV];
  22. int n,m;
  23. int s,t;
  24. queue<int> q;
  25.  
  26. void makeEdge(int idx, int a, int b, int c) {
  27.     ls[idx].prev=lastEdge[a];
  28.     lastEdge[a]=idx;
  29.     ls[idx].dst=b, ls[idx].src=a;
  30.     ls[idx].c=c, ls[idx].f=0LL;
  31. }
  32.  
  33. bool bfs() {
  34.     memset(d,0x3f,sizeof(d));
  35.     q.empty();
  36.  
  37.     for (int i=0; i<n; i++)
  38.         currEdge[i]=lastEdge[i];
  39.  
  40.     q.push(s);
  41.     d[s]=0;
  42.  
  43.     while (!q.empty()) {
  44.         int u = q.front();
  45.         q.pop();
  46.  
  47.         for (int i=lastEdge[u]; i!=-1; i=ls[i].prev)
  48.             if (ls[i].c-ls[i].f>0 && d[ls[i].dst]==inf) {
  49.                 int v=ls[i].dst;
  50.                 d[v]=d[u]+1;
  51.                 q.push(v);
  52.             }
  53.     }
  54.  
  55.     return d[t]!=inf;
  56. }
  57.  
  58. long long dfs(int u, long long flow) {
  59.     if (u==t) return flow;
  60.  
  61.     for (int& i=currEdge[u]; i!=-1; i=ls[i].prev) {
  62.         if (d[ls[i].dst]!=d[u]+1 || (ls[i].c-ls[i].f==0))
  63.             continue;
  64.  
  65.         long long tmpF = dfs(ls[i].dst, min(flow,ls[i].c-ls[i].f));
  66.  
  67.         if (tmpF) {
  68.             ls[i].f+=tmpF;
  69.             ls[i^1].f-=tmpF;
  70.             return tmpF;
  71.         }
  72.     }
  73.  
  74.     return 0LL;
  75. }
  76.  
  77. long long dinic() {
  78.     long long maxFlow=0;
  79.  
  80.     while (bfs()) {
  81.         long long flow=0;
  82.         while (flow=dfs(s,llinf))
  83.             maxFlow+=flow;
  84.     }
  85.  
  86.     return maxFlow;
  87. }
  88.  
  89. int main() {
  90.     scanf("%d %d", &n,&m);
  91.     memset(lastEdge,-1,sizeof(lastEdge));  
  92.     s=0, t=n-1;
  93.  
  94.     for (int i=0; i<m; i++) {
  95.         int a,b,c;
  96.         scanf("%d %d %d", &a,&b,&c);
  97.         a--, b--;
  98.        
  99.         makeEdge(2*i,a,b,c);
  100.         makeEdge(2*i+1,b,a,c);
  101.     }
  102.  
  103.     printf("%lld\n", dinic()); 
  104.     return 0;
  105. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement