Skip to content

Commit 18d4ad0

Browse files
committed
Update Dinic
1 parent 5570279 commit 18d4ad0

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

dinic.cpp

+14-18
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ void add_edge(ll u, ll v, ll c) {
1919
}
2020
}
2121

22-
bool bfs(ll lim) {
22+
bool bfs() {
2323
fill(dist.begin(), dist.end(),INF);
2424
dist[src] = 0;
2525
q.push(src);
@@ -28,7 +28,7 @@ bool bfs(ll lim) {
2828
ll u = q.front(); q.pop();
2929

3030
for (ll to : adj[u]) {
31-
if (dist[to] == INF and capacity[u][to] - flow[u][to] >= lim) {
31+
if (dist[to] == INF and flow[u][to] < capacity[u][to]) {
3232
dist[to] = dist[u] + 1;
3333
q.push(to);
3434
}
@@ -39,38 +39,34 @@ bool bfs(ll lim) {
3939
return dist[dest] != INF;
4040
}
4141

42-
bool dfs(ll u, ll curr_flow) {
42+
ll dfs(ll u, ll curr_flow) {
4343
if (curr_flow == 0 or u == dest) {
4444
return curr_flow;
4545
}
4646

4747
for (; pt[u] < adj[u].size(); pt[u]++) {
4848
ll to = adj[u][pt[u]];
4949

50-
if (dist[to] == dist[u] + 1 and capacity[u][to] - flow[u][to] >= curr_flow) {
51-
bool pushed = dfs(to, curr_flow);
52-
if (pushed) {
53-
flow[u][to] += curr_flow;
54-
flow[to][u] -= curr_flow;
55-
return true;
50+
if (dist[to] == dist[u] + 1) {
51+
ll pushed = dfs(to, min(curr_flow, capacity[u][to] - flow[u][to]));
52+
if (pushed > 0) {
53+
flow[u][to] += pushed;
54+
flow[to][u] -= pushed;
55+
return pushed;
5656
}
5757
}
5858
}
5959

60-
return false;
60+
return 0;
6161
}
6262

6363
ll dinic() {
64-
ll flow = 0, lim = (1 << 30);
65-
while (lim >= 1) {
66-
if (!bfs(lim)) {
67-
lim >>= 1;
68-
continue;
69-
}
64+
ll flow = 0;
65+
while (bfs()) {
7066
fill(pt.begin(), pt.end(),0);
7167

72-
while (dfs(src, lim)) {
73-
flow += lim;
68+
while (ll pushed = dfs(src, INF)) {
69+
flow += pushed;
7470
}
7571
}
7672
return flow;

0 commit comments

Comments
 (0)