Skip to content

Commit 84fca96

Browse files
Chilleesimonlindholm
authored andcommitted
Added implementation of Dinic's (#82)
1 parent 2a02c64 commit 84fca96

File tree

2 files changed

+51
-0
lines changed

2 files changed

+51
-0
lines changed

content/graph/Dinic.h

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/**
2+
* Author: chilli
3+
* Date: 2019-04-26
4+
* License: CC0
5+
* Source: https://cp-algorithms.com/graph/dinic.html
6+
* Description: Flow algorithm with guaranteed complexity $O(V^2E)$.
7+
* $O(\sqrt{V}E)$ for bipartite graphs, $O(\min(V^{1/2}, E^{2/3})E))$ for unit graphs.
8+
* To obtain the actual flow, look at positive values only.
9+
* Status: Tested on SPOJ FASTFLOW and SPOJ MATCHING
10+
*/
11+
struct Dinic {
12+
struct Edge {
13+
int to, rev;
14+
ll c, f;
15+
};
16+
vi lvl, ptr, q;
17+
vector<vector<Edge>> adj;
18+
Dinic(int n) : lvl(n), ptr(n), q(n), adj(n) {}
19+
void addEdge(int a, int b, ll c, int rcap = 0) {
20+
adj[a].push_back({b, sz(adj[b]), c, 0});
21+
adj[b].push_back({a, sz(adj[a]) - 1, rcap, 0});
22+
}
23+
ll dfs(int v, int t, ll f) {
24+
if (v == t || !f) return f;
25+
for (int& i = ptr[v]; i < sz(adj[v]); i++) {
26+
Edge& e = adj[v][i];
27+
if (lvl[e.to] == lvl[v] + 1)
28+
if (ll p = dfs(e.to, t, min(f, e.c - e.f))) {
29+
e.f += p, adj[e.to][e.rev].f -= p;
30+
return p;
31+
}
32+
}
33+
return 0;
34+
}
35+
ll calc(int s, int t) {
36+
ll flow = 0; q[0] = s;
37+
do {
38+
lvl = ptr = vi(sz(q));
39+
int qi = 0, qe = lvl[s] = 1;
40+
while (qi < qe && !lvl[t]) {
41+
int v = q[qi++];
42+
trav(e, adj[v])
43+
if (!lvl[e.to] && e.f < e.c)
44+
q[qe++] = e.to, lvl[e.to] = lvl[v] + 1;
45+
}
46+
while (ll p = dfs(s, t, LLONG_MAX)) flow += p;
47+
} while (lvl[t]);
48+
return flow;
49+
}
50+
};

content/graph/chapter.tex

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ \section{Network flow}
1212
\kactlimport{PushRelabel.h}
1313
\kactlimport{MinCostMaxFlow.h}
1414
\kactlimport{EdmondsKarp.h}
15+
% \kactlimport{Dinic.h}
1516
\kactlimport{MinCut.h}
1617
\kactlimport{GlobalMinCut.h}
1718

0 commit comments

Comments
 (0)