summaryrefslogtreecommitdiff
path: root/content/graph/dinitzScaling.cpp
diff options
context:
space:
mode:
authorGloria Mundi <gloria@gloria-mundi.eu>2025-02-13 22:07:35 +0100
committerGloria Mundi <gloria@gloria-mundi.eu>2025-02-13 22:07:35 +0100
commit04ca8f7bd16c0c855f604188d617a1bf2e8eacfd (patch)
treec0b535dc4635bf7d99c714f030578c73ba023310 /content/graph/dinitzScaling.cpp
parent7dc90ef744cf16ac4b4cb4e7d22f4c4686ae7225 (diff)
rename Dinic to Dinitz
Diffstat (limited to 'content/graph/dinitzScaling.cpp')
-rw-r--r--content/graph/dinitzScaling.cpp57
1 files changed, 57 insertions, 0 deletions
diff --git a/content/graph/dinitzScaling.cpp b/content/graph/dinitzScaling.cpp
new file mode 100644
index 0000000..fd82296
--- /dev/null
+++ b/content/graph/dinitzScaling.cpp
@@ -0,0 +1,57 @@
+struct Edge {
+ int to, rev;
+ ll f, c;
+};
+
+vector<vector<Edge>> adj;
+int s, t;
+vector<int> pt, dist;
+
+void addEdge(int u, int v, ll c) {
+ adj[u].push_back({v, (int)ssize(adj[v]), 0, c});
+ adj[v].push_back({u, (int)ssize(adj[u]) - 1, 0, 0});
+}
+
+bool bfs(ll lim) {
+ dist.assign(ssize(adj), -1);
+ dist[s] = 0;
+ queue<int> q({s});
+ while (!q.empty() && dist[t] < 0) {
+ int v = q.front(); q.pop();
+ for (Edge& e : adj[v]) {
+ if (dist[e.to] < 0 && e.c - e.f >= lim) {
+ dist[e.to] = dist[v] + 1;
+ q.push(e.to);
+ }}}
+ return dist[t] >= 0;
+}
+
+ll dfs(int v, ll flow) {
+ if (v == t || flow == 0) return flow;
+ for (; pt[v] < ssize(adj[v]); pt[v]++) {
+ Edge& e = adj[v][pt[v]];
+ if (dist[e.to] != dist[v] + 1) continue;
+ ll cur = dfs(e.to, min(e.c - e.f, flow));
+ if (cur > 0) {
+ e.f += cur;
+ adj[e.to][e.rev].f -= cur;
+ return cur;
+ }}
+ return 0;
+}
+
+ll maxFlow(int source, int target) {
+ s = source, t = target;
+ ll flow = 0;
+ // lim = 1 may be faster if capacities are small
+ for (ll lim = (1LL << 62); lim >= 1; lim /= 2) {
+ while (bfs(lim)) {
+ pt.assign(ssize(adj), 0);
+ ll cur;
+ do {
+ cur = dfs(s, lim);
+ flow += cur;
+ } while (cur > 0);
+ }}
+ return flow;
+}