Skip to main content

constraint_search/all_different/
graph.rs

1//! The variable–value graph of an all-different constraint: a maximum matching, and the
2//! edges no maximum matching can use.
3//!
4//! An edge `(x, v)` is in some maximum matching exactly when it is in the matching found, lies
5//! on an alternating cycle, or lies on an even alternating path that starts at a free value
6//! (Berge). With matched edges pointing from variable to value and the others from value to
7//! variable, the cycles are the strongly connected components and the paths are what a free
8//! value reaches.
9//!
10//! All buffers live in [`MatchingScratch`] and keep their capacity between runs, so a run
11//! allocates only while the buffers are still growing. Adjacency is stored flat (compressed
12//! rows: `start[node]..start[node + 1]` indexes the neighbours).
13
14use alloc::vec::Vec;
15
16use crate::{Domain, Domains, Var};
17
18/// Marks an unmatched variable or value, and an unvisited node.
19const NONE: usize = usize::MAX;
20
21/// Working memory of [`AllDifferent`](crate::AllDifferent), reused across propagation calls.
22///
23/// Graph nodes `0..n` are the variables, nodes `n..n + m` the values.
24#[derive(Debug, Default)]
25pub struct MatchingScratch {
26    /// The values of the union of the domains, sorted ascending.
27    values: Vec<u32>,
28    /// `edges[edge_start[x]..edge_start[x + 1]]` are the value indices in variable `x`'s
29    /// domain. One longer than the number of variables.
30    edge_start: Vec<usize>,
31    /// The value indices of all variables' domains, back to back.
32    edges: Vec<usize>,
33    /// For each variable, the value index it is matched to, or [`NONE`].
34    var_match: Vec<usize>,
35    /// For each value index, the variable it is matched to, or [`NONE`].
36    value_match: Vec<usize>,
37    /// Values visited by the current augmenting-path search.
38    seen: Vec<bool>,
39    /// `successors[successor_start[u]..successor_start[u + 1]]` are the nodes `u` points to.
40    successor_start: Vec<usize>,
41    /// The directed edges' targets, grouped by source node.
42    successors: Vec<usize>,
43    /// The next free slot per source node while filling [`MatchingScratch::successors`].
44    cursor: Vec<usize>,
45    /// Nodes reachable from a free value.
46    reached: Vec<bool>,
47    /// The depth-first stack of the reachability search.
48    stack: Vec<usize>,
49    /// Strongly connected components.
50    tarjan: Tarjan,
51    /// `(variable position, value)` pairs that no maximum matching uses.
52    unsupported: Vec<(usize, u32)>,
53}
54
55impl MatchingScratch {
56    /// Builds the graph of `vars` over their current domains.
57    pub(super) fn build<D: Domain>(&mut self, domains: &Domains<D>, vars: &[Var]) {
58        let union = domains.union_of(vars);
59        self.values.clear();
60        self.values.extend(union.values());
61
62        self.edge_start.clear();
63        self.edges.clear();
64        for &var in vars {
65            self.edge_start.push(self.edges.len());
66            for value in domains[var].values() {
67                let index = self.values.binary_search(&value);
68                self.edges.push(index.expect("value is in the union"));
69            }
70        }
71
72        self.edge_start.push(self.edges.len());
73        reset(&mut self.var_match, vars.len(), NONE);
74        reset(&mut self.value_match, self.values.len(), NONE);
75    }
76
77    /// The number of variables in the graph.
78    fn vars(&self) -> usize {
79        self.edge_start.len() - 1
80    }
81
82    /// The value indices in the domain of variable `var`.
83    fn edges_of(&self, var: usize) -> core::ops::Range<usize> {
84        self.edge_start[var]..self.edge_start[var + 1]
85    }
86
87    /// Matches every variable to a distinct value; returns `false` if that is impossible.
88    pub(super) fn match_all(&mut self) -> bool {
89        if self.values.len() < self.vars() {
90            return false;
91        }
92
93        reset(&mut self.seen, self.values.len(), false);
94        (0..self.vars()).all(|var| {
95            self.seen.fill(false);
96            self.augment(var)
97        })
98    }
99
100    /// Finds an augmenting path from the unmatched `var`, skipping the values already seen.
101    ///
102    /// Recursion depth is at most the number of variables.
103    fn augment(&mut self, var: usize) -> bool {
104        for position in self.edges_of(var) {
105            let value = self.edges[position];
106            if self.seen[value] {
107                continue;
108            }
109
110            self.seen[value] = true;
111            let owner = self.value_match[value];
112            if owner == NONE || self.augment(owner) {
113                self.var_match[var] = value;
114                self.value_match[value] = var;
115                return true;
116            }
117        }
118
119        false
120    }
121
122    /// The `(variable position, value)` pairs that no maximum matching uses, after
123    /// [`MatchingScratch::match_all`] succeeded.
124    pub(super) fn unsupported(&mut self) -> &[(usize, u32)] {
125        self.build_successors();
126        self.reach_from_free();
127        self.tarjan.run(&self.successor_start, &self.successors);
128
129        let vars = self.vars();
130        self.unsupported.clear();
131        for var in 0..vars {
132            for position in self.edges_of(var) {
133                let value = self.edges[position];
134                let node = vars + value;
135                let component = &self.tarjan.component;
136                let used = self.var_match[var] == value
137                    || component[var] == component[node]
138                    || self.reached[node];
139                if !used {
140                    self.unsupported.push((var, self.values[value]));
141                }
142            }
143        }
144
145        &self.unsupported
146    }
147
148    /// The directed graph: matched edges from variable to value, the others reversed.
149    fn build_successors(&mut self) {
150        let vars = self.vars();
151        let nodes = vars + self.values.len();
152        reset(&mut self.successor_start, nodes + 1, 0);
153        for var in 0..vars {
154            for position in self.edges_of(var) {
155                let (from, _) = self.direct(var, self.edges[position]);
156                self.successor_start[from + 1] += 1;
157            }
158        }
159
160        for node in 1..=nodes {
161            self.successor_start[node] += self.successor_start[node - 1];
162        }
163
164        reset(&mut self.successors, self.successor_start[nodes], 0);
165        self.cursor.clear();
166        self.cursor
167            .extend_from_slice(&self.successor_start[..nodes]);
168        for var in 0..vars {
169            for position in self.edges_of(var) {
170                let (from, to) = self.direct(var, self.edges[position]);
171                self.successors[self.cursor[from]] = to;
172                self.cursor[from] += 1;
173            }
174        }
175    }
176
177    /// The direction of the edge between `var` and value index `value`, as `(from, to)` nodes.
178    fn direct(&self, var: usize, value: usize) -> (usize, usize) {
179        let node = self.vars() + value;
180        if self.var_match[var] == value {
181            (var, node)
182        } else {
183            (node, var)
184        }
185    }
186
187    /// Marks every node reachable from a value that no variable is matched to.
188    fn reach_from_free(&mut self) {
189        let vars = self.vars();
190        reset(&mut self.reached, self.successor_start.len() - 1, false);
191        self.stack.clear();
192        for value in 0..self.values.len() {
193            if self.value_match[value] == NONE {
194                self.stack.push(vars + value);
195            }
196        }
197
198        while let Some(node) = self.stack.pop() {
199            if self.reached[node] {
200                continue;
201            }
202
203            self.reached[node] = true;
204            let next = &self.successors[self.successor_start[node]..self.successor_start[node + 1]];
205            self.stack
206                .extend(next.iter().filter(|&&next| !self.reached[next]));
207        }
208    }
209}
210
211/// Empties `buffer` and refills it with `len` copies of `value`, keeping its capacity.
212fn reset<T: Copy>(buffer: &mut Vec<T>, len: usize, value: T) {
213    buffer.clear();
214    buffer.resize(len, value);
215}
216
217/// The working state of Tarjan's strongly connected components algorithm, iterative.
218#[derive(Debug, Default)]
219struct Tarjan {
220    /// The visiting order of each node; [`NONE`] while unvisited.
221    index: Vec<usize>,
222    /// The smallest visiting order reachable from each node through its subtree.
223    low: Vec<usize>,
224    /// `true` while the node is on [`Tarjan::stack`].
225    on_stack: Vec<bool>,
226    /// Visited nodes not yet assigned a component.
227    stack: Vec<usize>,
228    /// The simulated call stack: a node and the position of its next successor.
229    calls: Vec<(usize, usize)>,
230    /// The component of each node.
231    component: Vec<usize>,
232    /// The visiting order the next node gets.
233    next_index: usize,
234    /// The number the next component gets.
235    next_component: usize,
236}
237
238impl Tarjan {
239    /// Computes the component of every node of the graph given in compressed rows.
240    fn run(&mut self, start: &[usize], successors: &[usize]) {
241        let nodes = start.len() - 1;
242        reset(&mut self.index, nodes, NONE);
243        reset(&mut self.low, nodes, 0);
244        reset(&mut self.on_stack, nodes, false);
245        reset(&mut self.component, nodes, NONE);
246        self.stack.clear();
247        self.next_index = 0;
248        self.next_component = 0;
249
250        for root in 0..nodes {
251            if self.index[root] == NONE {
252                self.visit_from(root, start, successors);
253            }
254        }
255    }
256
257    /// Visits every unvisited node reachable from `root`, depth first without recursion.
258    fn visit_from(&mut self, root: usize, start: &[usize], successors: &[usize]) {
259        self.calls.clear();
260        self.calls.push((root, start[root]));
261        self.enter(root);
262
263        while let Some(&(node, position)) = self.calls.last() {
264            if position < start[node + 1] {
265                let next = successors[position];
266                let top = self.calls.len() - 1;
267                self.calls[top].1 += 1;
268                if self.index[next] == NONE {
269                    self.enter(next);
270                    self.calls.push((next, start[next]));
271                } else if self.on_stack[next] {
272                    self.low[node] = self.low[node].min(self.index[next]);
273                }
274
275                continue;
276            }
277
278            self.calls.pop();
279            if let Some(&(parent, _)) = self.calls.last() {
280                self.low[parent] = self.low[parent].min(self.low[node]);
281            }
282
283            if self.low[node] == self.index[node] {
284                self.close_component(node);
285            }
286        }
287    }
288
289    /// Gives `node` its visiting order and puts it on the stack.
290    fn enter(&mut self, node: usize) {
291        self.index[node] = self.next_index;
292        self.low[node] = self.next_index;
293        self.next_index += 1;
294        self.stack.push(node);
295        self.on_stack[node] = true;
296    }
297
298    /// Pops the component whose root is `root` off the stack.
299    fn close_component(&mut self, root: usize) {
300        while let Some(node) = self.stack.pop() {
301            self.on_stack[node] = false;
302            self.component[node] = self.next_component;
303            if node == root {
304                break;
305            }
306        }
307
308        self.next_component += 1;
309    }
310}