4eyes4u

Dinic's algorithm

Oct 31st, 2016
160
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.84 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=1000;
  5. const int M=500;
  6. const int inf=1e9;
  7.  
  8. struct Edge
  9. {
  10.     int u, v, cap, flow, next;
  11. } grana[M];
  12.  
  13. int n, m, head[N], dist[N];
  14. int E, src, snk;
  15.  
  16. void add_edge (int u, int v, int c1, int c2)
  17. {
  18.     grana[E++]=(Edge){u, v, c1, 0, head[u]};
  19.     head[u]=E-1;
  20.     grana[E++]=(Edge){v, u, c2, 0, head[v]};
  21.     head[v]=E-1;
  22. }
  23.  
  24. bool bfs ()
  25. {
  26.     fill(dist, dist+N, -1);
  27.     queue<int> q;
  28.     dist[src]=0;
  29.  
  30.     for (q.push(src);!q.empty();q.pop())
  31.     {
  32.         int v=q.front();
  33.         for (int e=head[v];e!=-1;e=grana[e].next)
  34.         {
  35.             int xt=grana[e].v;
  36.             if (grana[e].cap>grana[e].flow && dist[xt]==-1)
  37.             {
  38.                 dist[xt]=dist[v]+1;
  39.                 q.push(xt);
  40.             }
  41.         }
  42.     }
  43.  
  44.     return (dist[snk]!=-1);
  45. }
  46.  
  47. int dfs (int v, int minCap)
  48. {
  49.     if (minCap==0) return 0;
  50.     if (v==snk) return minCap;
  51.  
  52.     for (int e=head[v];e!=-1;e=grana[e].next)
  53.     {
  54.         int xt=grana[e].v;
  55.         if (dist[xt]!=dist[v]+1) continue;
  56.         int augment=dfs(xt, min(minCap, grana[e].cap-grana[e].flow));
  57.         if (augment)
  58.         {
  59.             grana[e].flow+=augment;
  60.             grana[e^1].flow-=augment;
  61.             return augment;
  62.         }
  63.     }
  64.  
  65.     return 0;
  66. }
  67.  
  68. int Dinic()
  69. {
  70.     int flow=0;
  71.     src=1, snk=n;
  72.  
  73.     while (true)
  74.     {
  75.         if (!bfs()) break;
  76.         while (true)
  77.         {
  78.             int curFlow=dfs(src, inf);
  79.             if (curFlow==0) break;
  80.             flow+=curFlow;
  81.         }
  82.     }
  83.  
  84.     return flow;
  85. }
  86.  
  87. int main()
  88. {
  89.     scanf ("%d%d", &n, &m);
  90.     fill(head, head+N, -1);
  91.     for (int i=0;i<m;i++)
  92.     {
  93.         int a, b, c;
  94.         scanf ("%d%d%d", &a, &b, &c);
  95.         add_edge(a, b, c, 0);
  96.     }
  97.  
  98.     printf ("%d", Dinic());
  99.  
  100.     return 0;
  101. }
Advertisement
Add Comment
Please, Sign In to add comment