1use alloc::vec::Vec;
9use core::cmp::Ordering;
10
11use search_core::{Cost, ExactArith, ExactNumber};
12
13use crate::cost::{add, weakly_dominates};
14
15pub type TreeEdge<C, const N: usize> = (usize, usize, [C; N]);
17
18pub type Tree<C, const N: usize> = (Vec<usize>, [C; N]);
20
21#[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#[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#[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
134fn 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
158fn 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#[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
227fn 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
255fn 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#[derive(Debug, Clone)]
264struct Sets(Vec<usize>);
265
266impl Sets {
267 fn new(n: usize) -> Self {
269 Self((0..n).collect())
270 }
271
272 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 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 fn components(&self, n: usize) -> usize {
294 (0..n).filter(|&x| self.find(x) == x).count()
295 }
296}