Advertisement
Riz1Ahmed

MaxFlow(Ford-Fulkerson)

Feb 20th, 2019
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.32 KB | None | 0 0
  1. /*********** MaxFlow(Ford-Fulkerson) ************
  2. Given a graph with weight. Find Maximum Flow of water
  3. from S to T. Where, the edges are as a pipeline.*/
  4.  
  5. #include <bits/stdc++.h>
  6. using namespace std;
  7. #define V 6 ///No of Vertices
  8. bool bfs(int rGraph[V][V],int s,int t,int par[]){
  9.     bool visited[V];
  10.     memset(visited,0,sizeof(visited));
  11.     queue <int> q;
  12.     q.push(s), visited[s]=true, par[s]=-1;
  13.     while (!q.empty()) {
  14.         int u = q.front(); q.pop();
  15.         for (int v=0; v<V; v++)
  16.             if (visited[v]==false && rGraph[u][v]>0)
  17.                 q.push(v),par[v]=u,visited[v]=true;
  18.     }
  19.     return (visited[t]==true); ///If a path Existed.
  20. }
  21. int fordFulkerson(int graph[V][V],int s,int t){
  22. ///parent=for store path. rGraph=Just a Copy of graph
  23.     int u,v,mxflow=0,rGraph[V][V],par[V];
  24.     for (u=0; u<V; u++) for (v=0; v<V; v++)
  25.         rGraph[u][v]=graph[u][v];
  26.     ///BFS=If there have a path
  27.     while (bfs(rGraph, s, t, par)){
  28.         int path=INT_MAX;
  29.         /// Find Min weight(Max Flow)
  30.         for (v=t; v!=s; v=par[v])
  31.             u=par[v], path=min(path,rGraph[u][v]);
  32.  
  33.         ///Update the paths
  34.         for (v=t; v != s; v=par[v])
  35.             u=par[v],
  36.             rGraph[u][v]-=path,
  37.             rGraph[v][u]+=path;
  38.         mxflow+=path;
  39.     }
  40.     return mxflow;
  41. }
  42. int main(){
  43.     int graph[V][V]={ {0,16, 13,  0,  0, 0},
  44.                       {0, 0, 10, 12,  0, 0},
  45.                       {0, 4,  0,  0, 14, 0},
  46.                       {0, 0,  9,  0,  0,20},
  47.                       {0, 0,  0,  7,  0, 4},
  48.                       {0, 0,  0,  0,  0, 0} };
  49.     printf("The maximum flow is %d\n",fordFulkerson(graph, 0, 5));
  50.     return 0;
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement