-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxFlow.cpp
More file actions
84 lines (66 loc) · 1.64 KB
/
MaxFlow.cpp
File metadata and controls
84 lines (66 loc) · 1.64 KB
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
#include <bits/stdc++.h>
using namespace std;
const int INF = INT_MAX;
int fordFulkerson(vector<vector<int>> &graph, int source, int sink)
{
int n = graph.size();
vector<vector<int>> residualGraph(graph);
vector<int> parent(n, -1);
int maxFlow = 0;
while (true)
{
vector<bool> visited(n, false);
queue<int> q;
q.push(source);
visited[source] = true;
while (!q.empty())
{
int u = q.front();
q.pop();
for (int v = 0; v < n; ++v)
{
if (!visited[v] && residualGraph[u][v] > 0)
{
q.push(v);
parent[v] = u;
visited[v] = true;
}
}
}
if (!visited[sink])
{
break; // No augmenting path found
}
int pathFlow = INF;
for (int v = sink; v != source; v = parent[v])
{
int u = parent[v];
pathFlow = min(pathFlow, residualGraph[u][v]);
}
for (int v = sink; v != source; v = parent[v])
{
int u = parent[v];
residualGraph[u][v] -= pathFlow;
residualGraph[v][u] += pathFlow;
}
maxFlow += pathFlow;
}
return maxFlow;
}
int main()
{
int N, M;
cin >> N >> M;
vector<vector<int>> graph(N + 1, vector<int>(N + 1, 0));
int s, t;
cin >> s >> t;
for (int i = 1; i <= M; i++)
{
int u, v, c;
cin >> u >> v >> c;
graph[u][v] = c;
}
int maxFlow = fordFulkerson(graph, s, t);
cout << maxFlow << endl;
return 0;
}