-
Notifications
You must be signed in to change notification settings - Fork 42
Expand file tree
/
Copy pathmaxflow_matrix.cpp
More file actions
77 lines (61 loc) · 1.79 KB
/
maxflow_matrix.cpp
File metadata and controls
77 lines (61 loc) · 1.79 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
namespace MaxFlow {
const int MAX_NODES = 1005;
int SRC = 0, DEST = 1;
int nodes = 2;
int F[MAX_NODES][MAX_NODES], C[MAX_NODES][MAX_NODES];
int Parent[MAX_NODES];
queue<int> Q;
vector<int> G[MAX_NODES];
void init(int n, int s = -1, int d = -1) {
if(s == -1) s = ++n;
if(d == -1) d = ++n;
SRC = s; DEST = d;
nodes = n;
for(int i=1; i<=nodes; i++) {
for(auto vec : G[i]) {
C[i][vec] = F[i][vec] = 0;
}
G[i].clear();
}
}
void addEdge(int a, int b, int cap) {
G[a].push_back(b);
G[b].push_back(a);
C[a][b] += cap;
}
bool bfs() {
memset(Parent, 0, sizeof(Parent));
Parent[SRC] = -1;
Q.push(SRC);
while(!Q.empty()) {
int node = Q.front();
Q.pop();
for(auto vec : G[node]) {
if(!Parent[vec] && F[node][vec] < C[node][vec]) {
Parent[vec] = node;
Q.push(vec);
}
}
}
return Parent[DEST] != 0;
}
int maxFlow() {
int flow = 0;
while(bfs()) {
for(auto x : G[DEST]) {
if(Parent[x] == 0) continue;
int M = C[x][DEST] - F[x][DEST];
for(int node = x; node != SRC; node = Parent[node]) {
M = min(M, C[Parent[node]][node] - F[Parent[node]][node]);
}
F[x][DEST] += M; F[DEST][x] -= M;
for(int node = x; node != SRC; node = Parent[node]) {
F[Parent[node]][node] += M;
F[node][Parent[node]] -= M;
}
flow += M;
}
}
return flow;
}
};