-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdinic.cpp
More file actions
130 lines (117 loc) · 2.67 KB
/
Copy pathdinic.cpp
File metadata and controls
130 lines (117 loc) · 2.67 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
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
129
130
#include <bits/stdc++.h>
#define pb push_back
typedef long long ll;
using namespace std;
struct MaxFlowDinic {
struct edge {
int from, to;
ll flow, cap;
};
int n;
vvi g;
vector<edge> edges;
vi q, d, ptr;
MaxFlowDinic(int _n) {
n = _n;
g.assign(n, {});
q.assign(n, 0);
d.assign(n, 0);
ptr.assign(n, 0);
}
void addEdge(int from, int to, ll cap) {
g[from].pb(edges.size());
edges.pb({from, to, 0, cap});
g[to].pb(edges.size());
edges.pb({to, from, 0, 0});
}
// constructs the level graph:
// d[i] = distance from source to i by minimum number of nonzero capacity edges
// doable by simple bfs
// returns 1 if sink is reachable by source via nonzero capacity edges
bool bfs(int source, int sink) {
fill(all(d), -1);
int head = 0, tail = 0;
q[tail++] = source;
d[source] = 0;
while (head < tail) {
int x = q[head++];
for (int i : g[x]) {
int y = edges[i].to;
if (d[y] == -1 && edges[i].flow < edges[i].cap) {
d[y] = d[x] + 1;
q[tail++] = y;
}
}
}
return d[sink] != -1;
}
ll dfs(int u, ll flow, int sink) {
if (!flow) return 0;
if (u == sink) return flow;
for (; ptr[u] < g[u].size(); ++ptr[u]) {
int i = g[u][ptr[u]];
int v = edges[i].to;
if (d[v] == d[u] + 1 && edges[i].flow < edges[i].cap) {
ll pushed = dfs(v, min(flow, edges[i].cap - edges[i].flow), sink);
if (pushed) {
edges[i].flow += pushed;
edges[i ^ 1].flow -= pushed;
return pushed;
}
}
}
return 0;
}
ll maxflow(int source, int sink) {
ll flow = 0;
while (bfs(source, sink)) {
fill(all(ptr), 0);
while (ll pushed = dfs(source, 1e18, sink)) {
flow += pushed;
}
}
return flow;
}
};
{
/*
In a graph whose edges have capacity 0 or 1,
the following subroutine finds a path in the
graph. This modifies the graph. If you call
it again, you will get another path, disjoint
from the first one. Call it k times (where
k is the maximum flow) to get the maximum
number of disjoint paths.
*/
flowgraph<505> g;
int maxflow;
vi curr;
int n, m;
void dfs(int x) {
curr.pb(x);
if (x == n) return;
for (int i : g.g[x]) {
int y = g.edges[i].to;
if (g.edges[i].flow == 1 && g.edges[i].cap == 1) {
g.edges[i].flow = 0;
dfs(y);
return;
}
}
}
}
int main(){
MaxFlowDinic z;
int n, m;
cin >> n >> m;
MaxFlowDinic z(n);
for(int i = 0; i < m; i++){
int u, v, c; cin >> u >> v >> c;
if(u != v){
z.addedge(u, v, c);
z.addedge(v, u, c);
}
}
cout << z.maxflow() << endl;
return 0;
}