use alloc::vec::Vec;
use core::cmp::Ordering;
use search_core::{Cost, ExactArith, ExactNumber};
use crate::cost::{add, weakly_dominates};
pub type TreeEdge<C, const N: usize> = (usize, usize, [C; N]);
pub type Tree<C, const N: usize> = (Vec<usize>, [C; N]);
#[must_use]
pub fn pareto_spanning_trees<C: Cost, const N: usize>(
nodes: usize,
edges: &[TreeEdge<C, N>],
) -> Vec<Tree<C, N>> {
let mut front = Vec::new();
search(nodes, edges, &mut front, &|_| true);
sorted(front)
}
#[must_use]
pub fn two_phase_spanning_trees<C: Cost + ExactArith>(
nodes: usize,
edges: &[TreeEdge<C, 2>],
) -> Vec<Tree<C, 2>> {
let supported = supported_spanning_trees(nodes, edges);
let mut all = supported.clone();
for pair in supported.windows(2) {
let (a, b) = (pair[0].1, pair[1].1);
let mut front = pair.to_vec();
search(nodes, edges, &mut front, &|lb: &[C; 2]| {
lb[0] < b[0] && lb[1] < a[1]
});
all.extend(front.into_iter().filter(|t| t.1[0] > a[0] && t.1[0] < b[0]));
}
sorted(all)
}
#[must_use]
pub fn supported_spanning_trees<C: Cost + ExactArith>(
nodes: usize,
edges: &[TreeEdge<C, 2>],
) -> Vec<Tree<C, 2>> {
let lex = |a: &[C; 2], b: &[C; 2]| a.cmp(b);
let Some(left) = kruskal(nodes, edges, |x, y| lex(&x.2, &y.2)) else {
return Vec::new();
};
let right = kruskal(nodes, edges, |x, y| {
lex(&[x.2[1], x.2[0]], &[y.2[1], y.2[0]])
})
.expect("connected");
if left.1 == right.1 {
return alloc::vec![left];
}
let value =
|w: &[C::Exact; 2], c: &[C; 2]| w[0].clone() * c[0].exact() + w[1].clone() * c[1].exact();
let mut found = alloc::vec![left];
let mut pending = alloc::vec![right];
while let Some(b) = pending.pop() {
let a = found.last().expect("starts with the left end").1;
let w = [
a[1].exact().abs_diff(&b.1[1].exact()),
b.1[0].exact().abs_diff(&a[0].exact()),
];
let p = kruskal(nodes, edges, |x, y| {
value(&w, &x.2).cmp(&value(&w, &y.2)).then(lex(&x.2, &y.2))
})
.expect("connected");
if value(&w, &p.1) < value(&w, &a) {
pending.push(b);
pending.push(p);
} else {
found.push(b);
}
}
found
}
fn kruskal<C: Cost, const N: usize>(
nodes: usize,
edges: &[TreeEdge<C, N>],
order: impl Fn(&TreeEdge<C, N>, &TreeEdge<C, N>) -> Ordering,
) -> Option<Tree<C, N>> {
let mut sorted: Vec<usize> = (0..edges.len()).collect();
sorted.sort_by(|&x, &y| order(&edges[x], &edges[y]).then(x.cmp(&y)));
let mut sets = Sets::new(nodes);
let mut tree = Vec::new();
let mut cost = [C::ZERO; N];
for e in sorted {
if sets.union(edges[e].0, edges[e].1) {
tree.push(e);
cost = add(cost, edges[e].2);
}
}
(tree.len() + 1 >= nodes).then(|| {
tree.sort_unstable();
(tree, cost)
})
}
fn search<C: Cost, const N: usize>(
nodes: usize,
edges: &[TreeEdge<C, N>],
front: &mut Vec<Tree<C, N>>,
inside: &dyn Fn(&[C; N]) -> bool,
) {
let mut chosen = Vec::new();
descend(
nodes,
edges,
0,
Sets::new(nodes),
&mut chosen,
[C::ZERO; N],
front,
inside,
);
}
#[expect(clippy::too_many_arguments, reason = "the branch-and-bound state")]
fn descend<C: Cost, const N: usize>(
nodes: usize,
edges: &[TreeEdge<C, N>],
k: usize,
sets: Sets,
chosen: &mut Vec<usize>,
cost: [C; N],
front: &mut Vec<Tree<C, N>>,
inside: &dyn Fn(&[C; N]) -> bool,
) {
if chosen.len() + 1 >= nodes {
if !front.iter().any(|t| weakly_dominates(&t.1, &cost)) {
front.retain(|t| !weakly_dominates(&cost, &t.1));
front.push((chosen.clone(), cost));
}
return;
}
let Some(bound) = lower_bound(nodes, edges, k, &sets, cost) else {
return;
};
if !inside(&bound) || front.iter().any(|t| weakly_dominates(&t.1, &bound)) {
return;
}
let (u, v, w) = edges[k];
let mut with = sets.clone();
if with.union(u, v) {
chosen.push(k);
descend(
nodes,
edges,
k + 1,
with,
chosen,
add(cost, w),
front,
inside,
);
chosen.pop();
}
descend(nodes, edges, k + 1, sets, chosen, cost, front, inside);
}
fn lower_bound<C: Cost, const N: usize>(
nodes: usize,
edges: &[TreeEdge<C, N>],
k: usize,
sets: &Sets,
cost: [C; N],
) -> Option<[C; N]> {
let mut bound = cost;
for i in 0..N {
let mut rest: Vec<usize> = (k..edges.len()).collect();
rest.sort_by_key(|&e| edges[e].2[i]);
let mut s = sets.clone();
for e in rest {
if s.union(edges[e].0, edges[e].1) {
bound[i] = bound[i] + edges[e].2[i];
}
}
if s.components(nodes) > 1 {
return None;
}
}
Some(bound)
}
fn sorted<C: Cost, const N: usize>(mut trees: Vec<Tree<C, N>>) -> Vec<Tree<C, N>> {
trees.sort_by_key(|t| t.1);
trees.dedup_by_key(|t| t.1);
trees
}
#[derive(Debug, Clone)]
struct Sets(Vec<usize>);
impl Sets {
fn new(n: usize) -> Self {
Self((0..n).collect())
}
fn find(&self, mut x: usize) -> usize {
while self.0[x] != x {
x = self.0[x];
}
x
}
fn union(&mut self, a: usize, b: usize) -> bool {
let (ra, rb) = (self.find(a), self.find(b));
if ra == rb {
return false;
}
self.0[ra] = rb;
true
}
fn components(&self, n: usize) -> usize {
(0..n).filter(|&x| self.find(x) == x).count()
}
}