This repository has been archived by the owner on May 5, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Ford_fulkerson.cpp
129 lines (104 loc) · 2.19 KB
/
Ford_fulkerson.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// This is the Ford Fulkerson Algorithm for finding maxflow in a network
#include <bits/stdc++.h>
#include <vector>
#include <queue>
#include<algorithm>
using namespace std;
int bfs(int source,int sink, int n);
int augment_residue(int maxflow, int source, int sink, int n);
int fordfulkerson(int source, int sink, int n);
vector<vector<int> > graph;
vector<vector<int> > weight;
vector <int> path1;
int main(){
cout<<"Enter the number of nodes in the graph\n";
int n;
cin>>n;
vector <int> row(n+1);
graph.push_back(row);
weight.push_back(row);
for (int i=1; i<=n; i++){
cout<<"Enter the out - degree of node "<<i<<"\n";
int deg;
cin>>deg;
int node;
int wt;
vector<int> nbr(n+1,0);
vector<int> nbw(n+1,0);
if(deg>0)
{ cout<<"Enter the neighbours of the nodes, with weights\n";
for (int j=1; j<=deg; j++){
cin>>node>>wt;
nbr[node]=1;
nbw[node]=wt;
}
}
graph.push_back(nbr);
weight.push_back(nbw);
}
cout<<"\n The Maximum Flow is "<<fordfulkerson(1,n,n)<<"\n";
return 0;
}
int fordfulkerson(int source, int sink, int n){
int mf=0;
for(int i=0; i<n+1;i++){
path1.push_back(0);
}
while(bfs(source,sink,n)){
mf = augment_residue(mf,source, sink, n);
}
return mf;
}
int bfs(int source,int sink, int n){
int visited[n+1];
for(int i=0; i<n+1;i++){
visited[i]=0;
}
queue<int> q;
q.push(source);
visited[source]=1;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v=1; v<n+1; v++)
{
if (visited[v]==0 && graph[u][v] > 0)
{
q.push(v);
path1[v] = u;
visited[v] = 1;
}
}
}
if(visited[sink] == 1){
return 1;
}
else{
return 0;
}
}
int augment_residue(int maxflow, int source, int sink, int n){
int i= sink;
int temp=10000;
while(i>source){
temp = min(weight[path1[i]][i],temp);
i = path1[i];
}
maxflow+=temp;
i=sink;
while(i>source){
weight[path1[i]][i]-=temp;
weight[i][path1[i]]+=temp;
if(weight[path1[i]][i]==0){
graph[path1[i]][i] = 0;
}
if(weight[i][path1[i]]>0)
{
graph[i][path1[i]]=1;
}
i = path1[i];
}
std::fill(path1.begin(), path1.end(), 0);
return maxflow;
}