-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFord Fulkerson.cpp
115 lines (78 loc) · 1.73 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
#include<bits/stdc++.h>
using namespace std;
const int mx = 105;
int par[mx];
int graph[mx][mx];
int rGraph[mx][mx];
bool vis[mx];
int n;
bool bfs(int s, int t)
{
memset(vis, 0, sizeof(vis));
memset(par, -1, sizeof(par));
queue <int> q;
q.push(s);
vis[s] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v=1; v<=n; v++)
{
if (vis[v]==false && rGraph[u][v] > 0)
{
q.push(v);
par[v] = u;
vis[v] = true;
}
}
}
return (vis[t] == true);
}
int fordFulkerson(int s, int t)
{
memset(rGraph, 0, sizeof(rGraph));
for (int u = 1; u <= n; u++)
for (int v = 1; v <= n; v++)
rGraph[u][v] = graph[u][v];
int max_flow = 0;
while (bfs(s, t))
{
int path_flow = INT_MAX;
for (int v = t; v != s; v = par[v])
{
int u = par[v];
path_flow = min(path_flow, rGraph[u][v]);
}
for (int v = t; v != s; v = par[v])
{
int u = par[v];
rGraph[u][v] -= path_flow;
rGraph[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
int main()
{
int test, cs = 0;
scanf("%d", &test);
while(test--)
{
memset(graph, 0, sizeof(graph));
scanf("%d", &n);
int s, t, c;
scanf("%d %d %d", &s, &t,&c);
while(c--)
{
int u, v, w;
scanf("%d %d %d", &u, &v, &w);
graph[u][v] += w;
graph[v][u] += w;
}
int res = fordFulkerson(s, t);
printf("Case %d: %d\n", ++cs, res);
}
return 0;
}