Skip to main content

lib_jsl_graph/
max_flow.rs

1//! Maximum flow and minimum cut: Edmonds-Karp and Dinic.
2//!
3//! See the book entry [Maximum flow and minimum cut](https://jwkunz.github.io/lib_jsl/book/graph/max-flow.html).
4
5use lib_jsl_core::ErrorsJSL;
6use std::collections::VecDeque;
7
8/// A flow network with residual arcs. Each added edge creates a forward arc with its capacity
9/// and a reverse arc of capacity zero, stored as consecutive indices `2k`, `2k + 1`.
10#[derive(Debug, Clone)]
11pub struct FlowNetwork {
12    head: Vec<Vec<usize>>,
13    to: Vec<usize>,
14    capacity: Vec<f64>,
15    flow: Vec<f64>,
16}
17
18/// The value of a maximum flow and the edge flows (in order of addition).
19#[derive(Debug, Clone, PartialEq)]
20pub struct MaxFlow {
21    pub value: f64,
22    pub edge_flows: Vec<f64>,
23    /// The source side of a minimum cut (vertices reachable from the source in the residual
24    /// graph); its capacity equals the flow value.
25    pub source_side: Vec<bool>,
26}
27
28const EPS: f64 = 1e-12;
29
30impl FlowNetwork {
31    pub fn new(n: usize) -> Self {
32        FlowNetwork { head: vec![Vec::new(); n], to: Vec::new(), capacity: Vec::new(), flow: Vec::new() }
33    }
34
35    /// Adds a directed edge `from → to` with a non-negative capacity; returns its index.
36    pub fn add_edge(&mut self, from: usize, to: usize, capacity: f64) -> Result<usize, ErrorsJSL> {
37        let n = self.head.len();
38        if from >= n || to >= n || capacity.is_nan() || capacity < 0.0 {
39            return Err(ErrorsJSL::InvalidInputRange("Need valid endpoints and a non-negative capacity."));
40        }
41        let index = self.to.len() / 2;
42        for (a, b, c) in [(from, to, capacity), (to, from, 0.0)] {
43            self.head[a].push(self.to.len());
44            self.to.push(b);
45            self.capacity.push(c);
46            self.flow.push(0.0);
47        }
48        Ok(index)
49    }
50
51    fn residual(&self, arc: usize) -> f64 {
52        self.capacity[arc] - self.flow[arc]
53    }
54
55    fn push(&mut self, arc: usize, amount: f64) {
56        self.flow[arc] += amount;
57        self.flow[arc ^ 1] -= amount;
58    }
59
60    fn check(&self, source: usize, sink: usize) -> Result<(), ErrorsJSL> {
61        if source >= self.head.len() || sink >= self.head.len() || source == sink {
62            return Err(ErrorsJSL::InvalidInputRange("Need distinct source and sink vertices."));
63        }
64        Ok(())
65    }
66
67    fn reset(&mut self) {
68        self.flow.iter_mut().for_each(|f| *f = 0.0);
69    }
70
71    fn result(&self, source: usize) -> MaxFlow {
72        let value = self.head[source].iter().map(|&a| self.flow[a]).sum();
73        let edge_flows = (0..self.to.len() / 2).map(|k| self.flow[2 * k]).collect();
74        let mut source_side = vec![false; self.head.len()];
75        let mut queue = VecDeque::from([source]);
76        source_side[source] = true;
77        while let Some(u) = queue.pop_front() {
78            for &a in &self.head[u] {
79                if self.residual(a) > EPS && !source_side[self.to[a]] {
80                    source_side[self.to[a]] = true;
81                    queue.push_back(self.to[a]);
82                }
83            }
84        }
85        MaxFlow { value, edge_flows, source_side }
86    }
87
88    /// Edmonds-Karp: augment along shortest (BFS) residual paths, `O(V E²)`.
89    pub fn edmonds_karp(&mut self, source: usize, sink: usize) -> Result<MaxFlow, ErrorsJSL> {
90        self.check(source, sink)?;
91        self.reset();
92        loop {
93            let mut parent_arc = vec![usize::MAX; self.head.len()];
94            let mut queue = VecDeque::from([source]);
95            let mut seen = vec![false; self.head.len()];
96            seen[source] = true;
97            while let Some(u) = queue.pop_front() {
98                for &a in &self.head[u] {
99                    let v = self.to[a];
100                    if !seen[v] && self.residual(a) > EPS {
101                        seen[v] = true;
102                        parent_arc[v] = a;
103                        queue.push_back(v);
104                    }
105                }
106            }
107            if !seen[sink] {
108                return Ok(self.result(source));
109            }
110            let mut bottleneck = f64::INFINITY;
111            let mut v = sink;
112            while v != source {
113                let a = parent_arc[v];
114                bottleneck = bottleneck.min(self.residual(a));
115                v = self.to[a ^ 1];
116            }
117            let mut v = sink;
118            while v != source {
119                let a = parent_arc[v];
120                self.push(a, bottleneck);
121                v = self.to[a ^ 1];
122            }
123        }
124    }
125
126    /// Dinic's algorithm: BFS level graphs and blocking flows by DFS with current-arc pointers,
127    /// `O(V² E)` in general and much faster in practice (`O(E √V)` on unit-capacity networks).
128    pub fn dinic(&mut self, source: usize, sink: usize) -> Result<MaxFlow, ErrorsJSL> {
129        self.check(source, sink)?;
130        self.reset();
131        let n = self.head.len();
132        loop {
133            let mut level = vec![usize::MAX; n];
134            level[source] = 0;
135            let mut queue = VecDeque::from([source]);
136            while let Some(u) = queue.pop_front() {
137                for &a in &self.head[u] {
138                    let v = self.to[a];
139                    if level[v] == usize::MAX && self.residual(a) > EPS {
140                        level[v] = level[u] + 1;
141                        queue.push_back(v);
142                    }
143                }
144            }
145            if level[sink] == usize::MAX {
146                return Ok(self.result(source));
147            }
148            // ANCHOR: dinic_phase
149            let mut current = vec![0usize; n];
150            // Iterative DFS for blocking flow.
151            loop {
152                let mut path: Vec<usize> = Vec::new();
153                let mut u = source;
154                loop {
155                    if u == sink {
156                        break;
157                    }
158                    let mut advanced = false;
159                    while current[u] < self.head[u].len() {
160                        let a = self.head[u][current[u]];
161                        let v = self.to[a];
162                        if self.residual(a) > EPS && level[v] == level[u] + 1 {
163                            path.push(a);
164                            u = v;
165                            advanced = true;
166                            break;
167                        }
168                        current[u] += 1;
169                    }
170                    if !advanced {
171                        // Dead end: retreat and skip the arc that led here.
172                        match path.pop() {
173                            Some(a) => {
174                                u = self.to[a ^ 1];
175                                current[u] += 1;
176                            }
177                            None => break,
178                        }
179                    }
180                }
181                if u != sink {
182                    break;
183                }
184                let bottleneck = path.iter().map(|&a| self.residual(a)).fold(f64::INFINITY, f64::min);
185                for &a in &path {
186                    self.push(a, bottleneck);
187                }
188            }
189            // ANCHOR_END: dinic_phase
190        }
191    }
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    fn clrs() -> FlowNetwork {
199        // The flow network of CLRS figure 26.1: maximum flow 23.
200        let mut net = FlowNetwork::new(6);
201        for (u, v, c) in [(0, 1, 16.0), (0, 2, 13.0), (1, 3, 12.0), (2, 1, 4.0), (2, 4, 14.0), (3, 2, 9.0), (3, 5, 20.0), (4, 3, 7.0), (4, 5, 4.0)] {
202            net.add_edge(u, v, c).unwrap();
203        }
204        net
205    }
206
207    #[test]
208    fn both_algorithms_find_the_textbook_maximum_and_its_cut() {
209        for use_dinic in [false, true] {
210            let mut net = clrs();
211            let flow = if use_dinic { net.dinic(0, 5) } else { net.edmonds_karp(0, 5) }.unwrap();
212            assert!((flow.value - 23.0).abs() < 1e-12, "dinic={use_dinic}: {}", flow.value);
213            // The cut capacity equals the flow (max-flow min-cut theorem).
214            let edges = [(0, 1, 16.0), (0, 2, 13.0), (1, 3, 12.0), (2, 1, 4.0), (2, 4, 14.0), (3, 2, 9.0), (3, 5, 20.0), (4, 3, 7.0), (4, 5, 4.0)];
215            let cut: f64 = edges.iter().filter(|&&(u, v, _)| flow.source_side[u] && !flow.source_side[v]).map(|e| e.2).sum();
216            assert!((cut - 23.0).abs() < 1e-12);
217            assert!(flow.edge_flows.iter().zip(&edges).all(|(f, e)| *f >= -1e-12 && *f <= e.2 + 1e-12));
218        }
219    }
220
221    #[test]
222    fn bipartite_matching_and_validation() {
223        // Unit capacities: maximum bipartite matching of 4 workers to 4 jobs is 3.
224        let mut net = FlowNetwork::new(10);
225        let (source, sink) = (8, 9);
226        for w in 0..4 {
227            net.add_edge(source, w, 1.0).unwrap();
228            net.add_edge(4 + w, sink, 1.0).unwrap();
229        }
230        for (w, j) in [(0, 0), (0, 1), (1, 0), (2, 1), (3, 2), (3, 3), (2, 0)] {
231            net.add_edge(w, 4 + j, 1.0).unwrap();
232        }
233        assert_eq!(net.clone().edmonds_karp(source, sink).unwrap().value, 3.0);
234        assert_eq!(net.dinic(source, sink).unwrap().value, 3.0);
235        assert!(FlowNetwork::new(2).add_edge(0, 1, -1.0).is_err() && FlowNetwork::new(2).dinic(1, 1).is_err());
236    }
237}