Skip to main content

multiobjective_search/
spanning.rs

1//! Multi-objective minimum spanning trees: the exact Pareto set by branch
2//! and bound, and the two-phase method for two objectives.
3//!
4//! A problem the survey of Salzman et al. (arXiv 2510.25504, Section 4)
5//! lists among the uses of the multi-objective search toolbox (Hamacher and
6//! Ruhe 1994; Ramos et al. 1998 for the two-phase approach).
7
8use alloc::vec::Vec;
9use core::cmp::Ordering;
10
11use search_core::{Cost, ExactArith, ExactNumber};
12
13use crate::cost::{add, weakly_dominates};
14
15/// An undirected edge `(u, v, cost)` between nodes `0..nodes`.
16pub type TreeEdge<C, const N: usize> = (usize, usize, [C; N]);
17
18/// A spanning tree as its edge indices (ascending) and its cost.
19pub type Tree<C, const N: usize> = (Vec<usize>, [C; N]);
20
21/// The Pareto-optimal spanning trees of an undirected graph, one per
22/// non-dominated cost, sorted by cost; empty if the graph is disconnected.
23///
24/// Branch and bound over the edges in order: each edge is taken (if it
25/// joins two components) or left out (if the rest can still connect the
26/// graph). A partial tree is pruned when a known tree weakly dominates its
27/// lower bound, its cost plus, per objective, the cheapest completion
28/// (Kruskal on the remaining edges). Exact, and exponential in the worst
29/// case, as the number of Pareto-optimal trees can be.
30///
31/// # Examples
32///
33/// ```
34/// use multiobjective_search::pareto_spanning_trees;
35///
36/// // A triangle: any two edges span it.
37/// let edges = [(0, 1, [1_u32, 5]), (1, 2, [2, 2]), (0, 2, [5, 1])];
38/// let trees = pareto_spanning_trees(3, &edges);
39/// let costs: Vec<_> = trees.iter().map(|t| t.1).collect();
40/// assert_eq!(costs, [[3, 7], [6, 6], [7, 3]]);
41/// ```
42#[must_use]
43pub fn pareto_spanning_trees<C: Cost, const N: usize>(
44    nodes: usize,
45    edges: &[TreeEdge<C, N>],
46) -> Vec<Tree<C, N>> {
47    let mut front = Vec::new();
48    search(nodes, edges, &mut front, &|_| true);
49    sorted(front)
50}
51
52/// The two-phase method for bi-objective spanning trees (Ramos et al.
53/// 1998): phase 1 finds the extreme supported trees by dichotomic search
54/// with weighted-sum Kruskal (weights from neighbouring trees, compared
55/// exactly through [`ExactArith`], ties lexicographic); phase 2 finds the
56/// rest by branch and bound restricted to each triangle between
57/// neighbours. Same result as [`pareto_spanning_trees`].
58///
59/// # Examples
60///
61/// ```
62/// use multiobjective_search::{pareto_spanning_trees, two_phase_spanning_trees};
63///
64/// let edges = [(0, 1, [1_u32, 5]), (1, 2, [2, 2]), (0, 2, [5, 1]), (1, 3, [1, 1]), (2, 3, [3, 4])];
65/// assert_eq!(two_phase_spanning_trees(4, &edges), pareto_spanning_trees(4, &edges));
66/// ```
67#[must_use]
68pub fn two_phase_spanning_trees<C: Cost + ExactArith>(
69    nodes: usize,
70    edges: &[TreeEdge<C, 2>],
71) -> Vec<Tree<C, 2>> {
72    let supported = supported_spanning_trees(nodes, edges);
73    let mut all = supported.clone();
74    for pair in supported.windows(2) {
75        let (a, b) = (pair[0].1, pair[1].1);
76        let mut front = pair.to_vec();
77        search(nodes, edges, &mut front, &|lb: &[C; 2]| {
78            lb[0] < b[0] && lb[1] < a[1]
79        });
80        all.extend(front.into_iter().filter(|t| t.1[0] > a[0] && t.1[0] < b[0]));
81    }
82
83    sorted(all)
84}
85
86/// Phase 1 of [`two_phase_spanning_trees`]: the extreme supported trees,
87/// sorted by cost; empty if the graph is disconnected.
88///
89/// # Panics
90///
91/// Never: a graph connected in one edge order is connected in every.
92#[must_use]
93pub fn supported_spanning_trees<C: Cost + ExactArith>(
94    nodes: usize,
95    edges: &[TreeEdge<C, 2>],
96) -> Vec<Tree<C, 2>> {
97    let lex = |a: &[C; 2], b: &[C; 2]| a.cmp(b);
98    let Some(left) = kruskal(nodes, edges, |x, y| lex(&x.2, &y.2)) else {
99        return Vec::new();
100    };
101    let right = kruskal(nodes, edges, |x, y| {
102        lex(&[x.2[1], x.2[0]], &[y.2[1], y.2[0]])
103    })
104    .expect("connected");
105    if left.1 == right.1 {
106        return alloc::vec![left];
107    }
108
109    let value =
110        |w: &[C::Exact; 2], c: &[C; 2]| w[0].clone() * c[0].exact() + w[1].clone() * c[1].exact();
111    let mut found = alloc::vec![left];
112    let mut pending = alloc::vec![right];
113    while let Some(b) = pending.pop() {
114        let a = found.last().expect("starts with the left end").1;
115        let w = [
116            a[1].exact().abs_diff(&b.1[1].exact()),
117            b.1[0].exact().abs_diff(&a[0].exact()),
118        ];
119        let p = kruskal(nodes, edges, |x, y| {
120            value(&w, &x.2).cmp(&value(&w, &y.2)).then(lex(&x.2, &y.2))
121        })
122        .expect("connected");
123        if value(&w, &p.1) < value(&w, &a) {
124            pending.push(b);
125            pending.push(p);
126        } else {
127            found.push(b);
128        }
129    }
130
131    found
132}
133
134/// Kruskal with edges in `order`; `None` if the graph is disconnected.
135fn kruskal<C: Cost, const N: usize>(
136    nodes: usize,
137    edges: &[TreeEdge<C, N>],
138    order: impl Fn(&TreeEdge<C, N>, &TreeEdge<C, N>) -> Ordering,
139) -> Option<Tree<C, N>> {
140    let mut sorted: Vec<usize> = (0..edges.len()).collect();
141    sorted.sort_by(|&x, &y| order(&edges[x], &edges[y]).then(x.cmp(&y)));
142    let mut sets = Sets::new(nodes);
143    let mut tree = Vec::new();
144    let mut cost = [C::ZERO; N];
145    for e in sorted {
146        if sets.union(edges[e].0, edges[e].1) {
147            tree.push(e);
148            cost = add(cost, edges[e].2);
149        }
150    }
151
152    (tree.len() + 1 >= nodes).then(|| {
153        tree.sort_unstable();
154        (tree, cost)
155    })
156}
157
158/// Branch and bound into `front`, keeping only partial trees whose lower
159/// bound `inside` accepts.
160fn search<C: Cost, const N: usize>(
161    nodes: usize,
162    edges: &[TreeEdge<C, N>],
163    front: &mut Vec<Tree<C, N>>,
164    inside: &dyn Fn(&[C; N]) -> bool,
165) {
166    let mut chosen = Vec::new();
167    descend(
168        nodes,
169        edges,
170        0,
171        Sets::new(nodes),
172        &mut chosen,
173        [C::ZERO; N],
174        front,
175        inside,
176    );
177}
178
179/// One branching step at edge `k`.
180#[expect(clippy::too_many_arguments, reason = "the branch-and-bound state")]
181fn descend<C: Cost, const N: usize>(
182    nodes: usize,
183    edges: &[TreeEdge<C, N>],
184    k: usize,
185    sets: Sets,
186    chosen: &mut Vec<usize>,
187    cost: [C; N],
188    front: &mut Vec<Tree<C, N>>,
189    inside: &dyn Fn(&[C; N]) -> bool,
190) {
191    if chosen.len() + 1 >= nodes {
192        if !front.iter().any(|t| weakly_dominates(&t.1, &cost)) {
193            front.retain(|t| !weakly_dominates(&cost, &t.1));
194            front.push((chosen.clone(), cost));
195        }
196
197        return;
198    }
199
200    let Some(bound) = lower_bound(nodes, edges, k, &sets, cost) else {
201        return;
202    };
203    if !inside(&bound) || front.iter().any(|t| weakly_dominates(&t.1, &bound)) {
204        return;
205    }
206
207    let (u, v, w) = edges[k];
208    let mut with = sets.clone();
209    if with.union(u, v) {
210        chosen.push(k);
211        descend(
212            nodes,
213            edges,
214            k + 1,
215            with,
216            chosen,
217            add(cost, w),
218            front,
219            inside,
220        );
221        chosen.pop();
222    }
223
224    descend(nodes, edges, k + 1, sets, chosen, cost, front, inside);
225}
226
227/// `cost` plus, per objective, the cheapest way to finish the tree with
228/// edges `k..`; `None` if they cannot.
229fn lower_bound<C: Cost, const N: usize>(
230    nodes: usize,
231    edges: &[TreeEdge<C, N>],
232    k: usize,
233    sets: &Sets,
234    cost: [C; N],
235) -> Option<[C; N]> {
236    let mut bound = cost;
237    for i in 0..N {
238        let mut rest: Vec<usize> = (k..edges.len()).collect();
239        rest.sort_by_key(|&e| edges[e].2[i]);
240        let mut s = sets.clone();
241        for e in rest {
242            if s.union(edges[e].0, edges[e].1) {
243                bound[i] = bound[i] + edges[e].2[i];
244            }
245        }
246
247        if s.components(nodes) > 1 {
248            return None;
249        }
250    }
251
252    Some(bound)
253}
254
255/// Sorts trees by cost.
256fn sorted<C: Cost, const N: usize>(mut trees: Vec<Tree<C, N>>) -> Vec<Tree<C, N>> {
257    trees.sort_by_key(|t| t.1);
258    trees.dedup_by_key(|t| t.1);
259    trees
260}
261
262/// A union-find over nodes `0..n`.
263#[derive(Debug, Clone)]
264struct Sets(Vec<usize>);
265
266impl Sets {
267    /// `n` singletons.
268    fn new(n: usize) -> Self {
269        Self((0..n).collect())
270    }
271
272    /// The representative of `x`.
273    fn find(&self, mut x: usize) -> usize {
274        while self.0[x] != x {
275            x = self.0[x];
276        }
277
278        x
279    }
280
281    /// Joins the sets of `a` and `b`; `false` if already joined.
282    fn union(&mut self, a: usize, b: usize) -> bool {
283        let (ra, rb) = (self.find(a), self.find(b));
284        if ra == rb {
285            return false;
286        }
287
288        self.0[ra] = rb;
289        true
290    }
291
292    /// The number of sets among the first `n` nodes.
293    fn components(&self, n: usize) -> usize {
294        (0..n).filter(|&x| self.find(x) == x).count()
295    }
296}