|
| 1 | +#include<cstdio> |
| 2 | +#include<queue> |
| 3 | +#include<cstring> |
| 4 | +#include<vector> |
| 5 | +#include<iostream> |
| 6 | +using namespace std; |
| 7 | +int c[10][10]; |
| 8 | +int flowPassed[10][10]; |
| 9 | +vector<int> g[10]; |
| 10 | +int parList[10]; |
| 11 | +int currentPathC[10]; |
| 12 | +int bfs(int sNode, int eNode)//breadth first search |
| 13 | +{ |
| 14 | + memset(parList, -1, sizeof(parList)); |
| 15 | + memset(currentPathC, 0, sizeof(currentPathC)); |
| 16 | + queue<int> q;//declare queue vector |
| 17 | + q.push(sNode); |
| 18 | + parList[sNode] = -1;//initialize parlist’s source node |
| 19 | + currentPathC[sNode] = 999;//initialize currentpath’s source node |
| 20 | + while(!q.empty())// if q is not empty |
| 21 | + { |
| 22 | + int currNode = q.front(); |
| 23 | + q.pop(); |
| 24 | + for(int i=0; i<g[currNode].size(); i++) |
| 25 | + { |
| 26 | + int to = g[currNode][i]; |
| 27 | + if(parList[to] == -1) |
| 28 | + { |
| 29 | + if(c[currNode][to] - flowPassed[currNode][to] > 0) |
| 30 | + { |
| 31 | + parList[to] = currNode; |
| 32 | + currentPathC[to] = min(currentPathC[currNode], |
| 33 | + c[currNode][to] - flowPassed[currNode][to]); |
| 34 | + if(to == eNode) |
| 35 | + { |
| 36 | + return currentPathC[eNode]; |
| 37 | + } |
| 38 | + q.push(to); |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + } |
| 43 | + return 0; |
| 44 | +} |
| 45 | +int edmondsKarp(int sNode, int eNode) |
| 46 | +{ |
| 47 | + int maxFlow = 0; |
| 48 | + while(true) |
| 49 | + { |
| 50 | + int flow = bfs(sNode, eNode); |
| 51 | + if (flow == 0) |
| 52 | + { |
| 53 | + break; |
| 54 | + } |
| 55 | + maxFlow += flow; |
| 56 | + int currNode = eNode; |
| 57 | + while(currNode != sNode) |
| 58 | + { |
| 59 | + int prevNode = parList[currNode]; |
| 60 | + flowPassed[prevNode][currNode] += flow; |
| 61 | + flowPassed[currNode][prevNode] -= flow; |
| 62 | + currNode = prevNode; |
| 63 | + } |
| 64 | + } |
| 65 | +return maxFlow; |
| 66 | +} |
| 67 | +int main() |
| 68 | +{ |
| 69 | + int nodCount, edCount; |
| 70 | + cout<<"enter the number of nodes and edges\n"; |
| 71 | + cin>>nodCount>>edCount; |
| 72 | + int source, sink; |
| 73 | + cout<<"enter the source and sink\n"; |
| 74 | + cin>>source>>sink; |
| 75 | + for(int ed = 0; ed < edCount; ed++) |
| 76 | + { |
| 77 | + cout<<"enter the start and end vertex along with capacity\n"; |
| 78 | + int from, to, cap; |
| 79 | + cin>>from>>to>>cap; |
| 80 | + c[from][to] = cap; |
| 81 | + g[from].push_back(to); |
| 82 | + g[to].push_back(from); |
| 83 | + } |
| 84 | + int maxFlow = edmondsKarp(source, sink); |
| 85 | + cout<<endl<<endl<<"Max Flow is:"<<maxFlow<<endl; |
| 86 | +} |
0 commit comments