Advertisement
4eyes4u

Edmonds-Karp algorithm

Oct 23rd, 2016
128
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.45 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. const int N=510;
  5. const int INF=1e9;
  6.  
  7. struct Node
  8. {
  9.     vector<int> adj;
  10.     int parent;
  11. } g[N];
  12.  
  13. int n, m, flow, augment;
  14. int cap[N][N];
  15. int s, t;
  16.  
  17. void bfs ()
  18. {
  19.     augment=0;
  20.     for (int i=1;i<=n;i++) g[i].parent=0;
  21.     g[s].parent=-1;
  22.  
  23.     queue<int> q, minCap;
  24.     q.push(s);
  25.     minCap.push(INF);
  26.  
  27.     while (!q.empty())
  28.     {
  29.         int v=q.front();
  30.         int curCap=minCap.front();
  31.         q.pop(); minCap.pop();
  32.  
  33.         for (int i=0;i<g[v].adj.size();i++)
  34.         {
  35.             int xt=g[v].adj[i];
  36.             if (cap[v][xt]>0 && g[xt].parent==0)
  37.             {
  38.                 q.push(xt);
  39.                 minCap.push(min(curCap, cap[v][xt]));
  40.                 g[xt].parent=v;
  41.                 if (xt==t) augment=min(curCap, cap[v][xt]);
  42.             }
  43.         }
  44.     }
  45.  
  46.     if (augment>0)
  47.     {
  48.         int v=t;
  49.         while (v!=s)
  50.         {
  51.             cap[g[v].parent][v]-=augment;
  52.             cap[v][g[v].parent]+=augment;
  53.             v=g[v].parent;
  54.         }
  55.     }
  56. }
  57.  
  58. void EdmondsKarp ()
  59. {
  60.     s=1; t=n;
  61.  
  62.     do
  63.     {
  64.         bfs();
  65.         flow+=augment;
  66.     }
  67.     while (augment);
  68. }
  69.  
  70. int main()
  71. {
  72.     scanf ("%d%d", &n, &m);
  73.     for (int i=0;i<m;i++)
  74.     {
  75.         int a, b, c;
  76.         scanf ("%d%d%d", &a, &b, &c);
  77.         g[a].adj.push_back(b);
  78.         cap[a][b]=c;
  79.     }
  80.  
  81.     EdmondsKarp();
  82.  
  83.     printf ("%d", flow);
  84.  
  85.     return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement