Skip to content

Instantly share code, notes, and snippets.

@Darkyenus
Created December 15, 2020 21:26
Show Gist options
  • Save Darkyenus/29eda1b0b575203727ded37798e460c7 to your computer and use it in GitHub Desktop.
Save Darkyenus/29eda1b0b575203727ded37798e460c7 to your computer and use it in GitHub Desktop.
Implementation of Dinic's network flow algorithm
/*
Optimization/adaptation of
https://github.com/williamfiset/Algorithms/blob/master/src/main/java/com/williamfiset/algorithms/graphtheory/networkflow/Dinics.java
MIT License
Copyright (c) 2017 William Fiset
Copyright (c) 2020 Jan Polák
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
import com.badlogic.gdx.utils.Array;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;
import static java.lang.Math.min;
/**
* Implementation of Dinic's network flow algorithm. The algorithm works by first constructing a
* level graph using a BFS and then finding augmenting paths on the level graph using multiple DFSs.
*
* <p>Time Complexity: O(EV²)
*
* @author William Fiset, william.alexandre.fiset@gmail.com
* @author Jan Polák (low-level optimization)
*/
public final class Dinitz {
// To avoid overflow, set infinity to a value less than Long.MAX_VALUE;
protected static final int INF = Integer.MAX_VALUE / 2;
private final Array<Edge>[] graph;
private final int nodeCount;
private final int sourceNode;
private final int sinkNode;
/**
* Creates an instance of a flow network solver. Use the {@link #addEdge} method to add edges to
* the graph.
*
* @param nodeCount - The number of nodes in the graph including source and sink nodes.
* @param source - The index of the source node, 0 <= s < n
* @param sink - The index of the sink node, 0 <= t < n, t != s
*/
public Dinitz(int nodeCount, int source, int sink) {
this.nodeCount = nodeCount;
this.sourceNode = source;
this.sinkNode = sink;
//noinspection unchecked
graph = new Array[nodeCount];
for (int i = 0; i < nodeCount; i++) graph[i] = new Array<>(false, 32, Edge.class);
}
/**
* Solve the max-flow problem.
* @return the maximum flow
*/
public int solve() {
// next[i] indicates the next unused edge index in the adjacency list for node i. This is part
// of the Shimon Even and Alon Itai optimization of pruning deads ends as part of the DFS phase.
final int[] next = new int[nodeCount];
final int[] level = new int[nodeCount];
int maxFlow = 0;
while (bfs(level)) {
Arrays.fill(next, 0);
// Find max flow by adding all augmenting path flows.
for (int f = dfs(level, sourceNode, next, INF); f != 0; f = dfs(level, sourceNode, next, INF)) {
maxFlow += f;
}
}
return maxFlow;
}
// Do a BFS from source to sink and compute the depth/level of each node
// which is the minimum number of edges from that node to the source.
private boolean bfs(int[] level) {
Arrays.fill(level, -1);
level[sourceNode] = 0;
Deque<Integer> q = new ArrayDeque<>(nodeCount);
q.offer(sourceNode);
while (!q.isEmpty()) {
int node = q.poll();
for (Edge edge : graph[node]) {
int cap = edge.remainingCapacity();
if (cap > 0 && level[edge.to] == -1) {
level[edge.to] = level[node] + 1;
q.offer(edge.to);
}
}
}
return level[sinkNode] != -1;
}
private int dfs(int[] level, int at, int[] next, int flow) {
if (at == sinkNode) return flow;
final int numEdges = graph[at].size;
for (; next[at] < numEdges; next[at]++) {
Edge edge = graph[at].get(next[at]);
int cap = edge.remainingCapacity();
if (cap > 0 && level[edge.to] == level[at] + 1) {
int bottleNeck = dfs(level, edge.to, next, min(flow, cap));
if (bottleNeck > 0) {
edge.augment(bottleNeck);
return bottleNeck;
}
}
}
return 0;
}
/**
* Adds a directed edge (and residual edge) to the flow graph.
*
* @param from The index of the node the directed edge starts at.
* @param to The index of the node the directed edge ends at.
* @param capacity The capacity of the edge.
*/
public void addEdge(int from, int to, int capacity) {
assert capacity >= 0 : "Capacity must be non-negative";
Edge e1 = new Edge(to, capacity);
Edge e2 = new Edge(from, 0);
e1.residual = e2;
e2.residual = e1;
graph[from].add(e1);
graph[to].add(e2);
}
private static final class Edge {
final int to;
Edge residual;
int flow;
final int capacity;
private Edge(int to, int capacity) {
this.to = to;
this.capacity = capacity;
}
public int remainingCapacity() {
return capacity - flow;
}
public void augment(int bottleNeck) {
flow += bottleNeck;
residual.flow -= bottleNeck;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment