-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathH.cpp
More file actions
82 lines (67 loc) · 2.05 KB
/
H.cpp
File metadata and controls
82 lines (67 loc) · 2.05 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
#include <iostream>
#include <vector>
#include <climits>
#include <cstring>
using namespace std;
class MaxFlow {
public:
MaxFlow(vector<vector<int>>& graph) : graph(graph), ROW(graph.size()) {}
bool dfs(int s, int t, vector<int>& parent) {
vector<bool> visited(ROW, false);
vector<int> stack;
stack.push_back(s);
visited[s] = true;
while (!stack.empty()) {
int u = stack.back();
stack.pop_back();
for (int v = 0; v < ROW; ++v) {
if (!visited[v] && graph[u][v] > 0) {
stack.push_back(v);
visited[v] = true;
parent[v] = u;
if (v == t) {
return true;
}
}
}
}
return false;
}
int ford_fulkerson(int source, int sink) {
vector<int> parent(ROW, -1);
int max_flow = 0;
while (dfs(source, sink, parent)) {
int path_flow = INT_MAX;
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
path_flow = min(path_flow, graph[u][v]);
}
for (int v = sink; v != source; v = parent[v]) {
int u = parent[v];
graph[u][v] -= path_flow;
graph[v][u] += path_flow;
}
max_flow += path_flow;
}
return max_flow;
}
private:
vector<vector<int>>& graph;
int ROW;
};
int main() {
int N, M;
cin >> N >> M;
vector<vector<int>> graph(N, vector<int>(N, 0));
for (int i = 0; i < M; ++i) {
int u, v, capacity;
cin >> u >> v >> capacity;
graph[u - 1][v - 1] = capacity; // 将站点编号调整为 0 基数
}
MaxFlow max_flow_solver(graph);
int source = 0; // 源点为发电站(编号1,索引0)
int sink = N - 1; // 汇点为变电站(编号N,索引N-1)
int result = max_flow_solver.ford_fulkerson(source, sink);
cout << result << endl;
return 0;
}