Skip to main content

multiobjective_search/
disjoint.rs

1//! Disjoint and dissimilar paths on graphs with edge identities.
2//!
3//! Suurballe 1974 and Suurballe and Tarjan 1984 (the shortest pair of
4//! disjoint paths, the form Bhandari 1999 popularized), the bicriteria
5//! disjoint pairs of Clímaco and Pascoal 2009 and the dissimilar paths of
6//! Moghanni, Pascoal and Godinho 2022, as surveyed by Craveirinha et al.,
7//! Algorithms 17(6):222, 2024, Section 2.2.3(g).
8
9mod pairs;
10
11use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
12use alloc::vec::Vec;
13use core::cmp::{Ordering, Reverse};
14
15use search_core::{Cost, ExactArith, ExactNumber, WideMul};
16
17use crate::graph::{EdgeGraph, Graph};
18
19pub use pairs::{SharedPair, disjoint_pair_front, maximally_disjoint_pairs};
20
21/// A disjoint pair with its total cost.
22pub type CostedPair<S, E, C> = (PathPair<S, E>, C);
23
24/// A path as its states, its edges and its cost.
25pub type RankedPath<S, E, C> = (Vec<S>, Vec<E>, C);
26
27/// Which elements two paths must not share.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29pub enum Disjointness {
30    /// No common edge.
31    Edges,
32    /// No common state other than the two ends.
33    States,
34}
35
36/// Two disjoint paths between the same ends.
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct PathPair<S, E> {
39    /// The states of the first path, start and target included.
40    pub first: Vec<S>,
41    /// The states of the second path.
42    pub second: Vec<S>,
43    /// The edges of the first path, in order.
44    pub first_edges: Vec<E>,
45    /// The edges of the second path, in order.
46    pub second_edges: Vec<E>,
47}
48
49/// The pair of disjoint paths from `start` to `target` with the smallest
50/// total scalar cost `cost(weight)`, by Suurballe's algorithm; `None` if
51/// no two such paths exist.
52///
53/// A first Dijkstra gives distances `d` and a shortest path `P1`. Every
54/// other edge gets the reduced cost `d(u) + c - d(v) >= 0`, and the edges
55/// of `P1` are replaced by zero-cost reversed copies; a second Dijkstra on
56/// that residual graph gives `P2`. Dropping the edges `P2` crosses
57/// backwards from `P1 ∪ P2` leaves the cheapest pair. For
58/// [`Disjointness::States`] every state but the ends is split into an
59/// entry and an exit joined by one edge, which makes state-disjoint pairs
60/// edge-disjoint. Zero-cost cycles left in the union are cut.
61///
62/// Requirements, not checked at run time: non-negative costs and a finite
63/// reachable graph.
64///
65/// # Examples
66///
67/// ```
68/// use multiobjective_search::{Disjointness, EdgeGraph, Graph, disjoint_pair};
69///
70/// /// The trap graph: the shortest path 0-1-2-3 blocks any disjoint second.
71/// struct Trap;
72///
73/// const EDGES: [(u8, u8, u32); 5] = [(0, 1, 1), (1, 2, 1), (2, 3, 1), (0, 2, 2), (1, 3, 2)];
74///
75/// impl Graph for Trap {
76///     type State = u8;
77///     type Weight = u32;
78///
79///     fn successors(&self, state: &u8, out: &mut Vec<(u8, u32)>) {
80///         out.extend(EDGES.iter().filter(|e| e.0 == *state).map(|e| (e.1, e.2)));
81///     }
82/// }
83///
84/// impl EdgeGraph for Trap {
85///     type Edge = usize;
86///
87///     fn edges(&self, state: &u8, out: &mut Vec<(usize, u8, u32)>) {
88///         out.extend(EDGES.iter().enumerate().filter(|(_, e)| e.0 == *state).map(|(i, e)| (i, e.1, e.2)));
89///     }
90/// }
91///
92/// let (pair, total) = disjoint_pair(&Trap, 0, 3, |w: &u32| *w, Disjointness::Edges).unwrap();
93/// assert_eq!(total, 6);
94/// assert_eq!((pair.first, pair.second), (vec![0, 1, 3], vec![0, 2, 3]));
95/// ```
96pub fn disjoint_pair<G, C, F>(
97    graph: &G,
98    start: G::State,
99    target: G::State,
100    cost: F,
101    kind: Disjointness,
102) -> Option<CostedPair<G::State, G::Edge, C>>
103where
104    G: EdgeGraph,
105    C: Cost + WideMul,
106    F: Fn(&G::Weight) -> C,
107{
108    suurballe(graph, start, target, |w| Plain(cost(w)), kind).map(|(pair, total)| (pair, total.0))
109}
110
111/// [`disjoint_pair`] over any [`Scalar`] cost.
112fn suurballe<G, T, F>(
113    graph: &G,
114    start: G::State,
115    target: G::State,
116    cost: F,
117    kind: Disjointness,
118) -> Option<CostedPair<G::State, G::Edge, T>>
119where
120    G: EdgeGraph,
121    T: Scalar,
122    F: Fn(&G::Weight) -> T,
123{
124    match kind {
125        Disjointness::Edges => {
126            let net = Network::explore(graph, start, |w| cost(w));
127            net.suurballe(&target)
128        }
129        Disjointness::States => {
130            let split = Split {
131                graph,
132                start: start.clone(),
133                target: target.clone(),
134            };
135            let cost = |w: &Option<G::Weight>| w.as_ref().map_or_else(T::zero, &cost);
136            let net = Network::explore(&split, (start, true), cost);
137            let (pair, total) = net.suurballe(&(target, false))?;
138            Some((unsplit(&pair), total))
139        }
140    }
141}
142
143/// The scalar costs Suurballe's algorithm sums and compares: a zero, a sum
144/// and the distance `|a - b|` for the reduced costs.
145trait Scalar: Clone + Ord {
146    /// Zero.
147    fn zero() -> Self;
148
149    /// `self + other`.
150    #[must_use]
151    fn plus(&self, other: &Self) -> Self;
152
153    /// `|self - other|`.
154    #[must_use]
155    fn distance(&self, other: &Self) -> Self;
156}
157
158/// A [`Cost`] as a [`Scalar`].
159#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
160struct Plain<C>(C);
161
162impl<C: Cost + WideMul> Scalar for Plain<C> {
163    fn zero() -> Self {
164        Self(C::ZERO)
165    }
166
167    fn plus(&self, other: &Self) -> Self {
168        Self(self.0 + other.0)
169    }
170
171    fn distance(&self, other: &Self) -> Self {
172        Self(self.0.abs_diff(other.0))
173    }
174}
175
176/// An [`ExactNumber`] as a [`Scalar`].
177#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
178struct Exact<T>(T);
179
180impl<T: ExactNumber> Scalar for Exact<T> {
181    fn zero() -> Self {
182        Self(T::zero())
183    }
184
185    fn plus(&self, other: &Self) -> Self {
186        Self(self.0.clone() + other.0.clone())
187    }
188
189    fn distance(&self, other: &Self) -> Self {
190        Self(self.0.abs_diff(&other.0))
191    }
192}
193
194/// The explicit reachable graph, with dense state indices (the start is 0).
195struct Network<S, E, C> {
196    /// States by index.
197    states: Vec<S>,
198    /// Index by state.
199    index: BTreeMap<S, usize>,
200    /// Edges `(identity, from, to, cost)`.
201    arcs: Vec<(E, usize, usize, C)>,
202    /// Outgoing edge indices per state.
203    out: Vec<Vec<usize>>,
204}
205
206/// An edge of the residual graph: an original edge, or one of `P1`
207/// reversed.
208#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
209enum Step {
210    /// Along edge `.0`.
211    Forward(usize),
212    /// Against edge `.0`.
213    Backward(usize),
214}
215
216impl<S: Clone + Ord, E: Clone, C: Scalar> Network<S, E, C> {
217    /// Explores everything reachable from `start`.
218    fn explore<G: EdgeGraph<State = S, Edge = E>>(
219        graph: &G,
220        start: S,
221        cost: impl Fn(&G::Weight) -> C,
222    ) -> Self {
223        let mut net = Self {
224            states: Vec::new(),
225            index: BTreeMap::new(),
226            arcs: Vec::new(),
227            out: Vec::new(),
228        };
229        net.add(start);
230        let mut buffer = Vec::new();
231        let mut i = 0;
232
233        while i < net.states.len() {
234            graph.edges(&net.states[i].clone(), &mut buffer);
235            for (edge, to, weight) in buffer.drain(..) {
236                let j = net.add(to);
237                if j != i {
238                    net.out[i].push(net.arcs.len());
239                    net.arcs.push((edge, i, j, cost(&weight)));
240                }
241            }
242
243            i += 1;
244        }
245
246        net
247    }
248
249    /// The index of `state`, added if new.
250    fn add(&mut self, state: S) -> usize {
251        if let Some(&i) = self.index.get(&state) {
252            return i;
253        }
254
255        self.index.insert(state.clone(), self.states.len());
256        self.states.push(state);
257        self.out.push(Vec::new());
258        self.states.len() - 1
259    }
260
261    /// Dijkstra from state 0 over `steps(u)`, each `(step, to, cost)`.
262    fn dijkstra(
263        &self,
264        steps: impl Fn(usize) -> Vec<(Step, usize, C)>,
265    ) -> (Vec<Option<C>>, Vec<Option<Step>>) {
266        let n = self.states.len();
267        let (mut dist, mut parent) = (alloc::vec![None; n], alloc::vec![None; n]);
268        let mut done = alloc::vec![false; n];
269        let mut heap = BinaryHeap::from([Reverse((C::zero(), 0_usize, None::<Step>))]);
270
271        while let Some(Reverse((d, u, via))) = heap.pop() {
272            if done[u] {
273                continue;
274            }
275
276            done[u] = true;
277            dist[u] = Some(d.clone());
278            parent[u] = via;
279            for (step, v, c) in steps(u) {
280                if !done[v] {
281                    heap.push(Reverse((d.plus(&c), v, Some(step))));
282                }
283            }
284        }
285
286        (dist, parent)
287    }
288
289    /// The tail of a residual step.
290    fn tail(&self, step: Step) -> usize {
291        match step {
292            Step::Forward(a) => self.arcs[a].1,
293            Step::Backward(a) => self.arcs[a].2,
294        }
295    }
296
297    /// The steps from state 0 to `to` along `parent`.
298    fn trace(&self, parent: &[Option<Step>], to: usize) -> Vec<Step> {
299        let mut steps = Vec::new();
300        let mut at = to;
301        while let Some(step) = parent[at] {
302            steps.push(step);
303            at = self.tail(step);
304        }
305
306        steps.reverse();
307        steps
308    }
309
310    /// Suurballe's algorithm from state 0 to `target`.
311    fn suurballe(&self, target: &S) -> Option<(PathPair<S, E>, C)> {
312        let t = *self.index.get(target)?;
313        let (dist, parent) = self.dijkstra(|u| self.original_steps(u));
314        dist[t].as_ref()?;
315        if t == 0 {
316            return None;
317        }
318
319        let first: Vec<usize> = self
320            .trace(&parent, t)
321            .into_iter()
322            .map(|s| match s {
323                Step::Forward(a) | Step::Backward(a) => a,
324            })
325            .collect();
326        let on_first: BTreeSet<usize> = first.iter().copied().collect();
327
328        // Incoming P1 edges per head, to add their reversals.
329        let mut reversed: Vec<Vec<usize>> = alloc::vec![Vec::new(); self.states.len()];
330        for &a in &first {
331            reversed[self.arcs[a].2].push(a);
332        }
333
334        let (dist2, parent2) =
335            self.dijkstra(|u| self.residual_steps(u, &dist, &on_first, &reversed));
336        dist2[t].as_ref()?;
337
338        let used = Self::flow_union(on_first, self.trace(&parent2, t));
339
340        Some(self.pair_from_flow(&used, t))
341    }
342
343    /// The steps along the original edges out of `u`, at their costs.
344    fn original_steps(&self, u: usize) -> Vec<(Step, usize, C)> {
345        self.out[u]
346            .iter()
347            .map(|&a| (Step::Forward(a), self.arcs[a].2, self.arcs[a].3.clone()))
348            .collect()
349    }
350
351    /// The residual steps out of `u` after the first path: original edges
352    /// off that path at their reduced cost against `dist`, plus the first
353    /// path's edges into `u` (`reversed[u]`) backwards at zero cost.
354    fn residual_steps(
355        &self,
356        u: usize,
357        dist: &[Option<C>],
358        on_first: &BTreeSet<usize>,
359        reversed: &[Vec<usize>],
360    ) -> Vec<(Step, usize, C)> {
361        let mut steps: Vec<(Step, usize, C)> = self.out[u]
362            .iter()
363            .filter(|a| !on_first.contains(a))
364            .map(|&a| {
365                let (_, from, to, c) = &self.arcs[a];
366                let (from, to) = (*from, *to);
367                let reduced = dist[from]
368                    .as_ref()
369                    .expect("reachable")
370                    .plus(c)
371                    .distance(dist[to].as_ref().expect("reachable"));
372                (Step::Forward(a), to, reduced)
373            })
374            .collect();
375        steps.extend(
376            reversed[u]
377                .iter()
378                .map(|&a| (Step::Backward(a), self.arcs[a].1, C::zero())),
379        );
380
381        steps
382    }
383
384    /// The edges of the two-unit flow: the first path's edges `on_first`,
385    /// plus the second path's forward steps, minus the edges it cancels.
386    fn flow_union(mut on_first: BTreeSet<usize>, second: Vec<Step>) -> BTreeSet<usize> {
387        for step in second {
388            match step {
389                Step::Forward(a) => on_first.insert(a),
390                Step::Backward(a) => on_first.remove(&a),
391            };
392        }
393
394        on_first
395    }
396
397    /// Splits the two-unit flow `used` from state 0 to `t` into two
398    /// edge-disjoint paths, the lexicographically smaller first, with their
399    /// total cost.
400    fn pair_from_flow(&self, used: &BTreeSet<usize>, t: usize) -> (PathPair<S, E>, C) {
401        let mut remaining: Vec<Vec<usize>> = alloc::vec![Vec::new(); self.states.len()];
402        for &a in used {
403            remaining[self.arcs[a].1].push(a);
404        }
405
406        let one = self.walk(&mut remaining, t);
407        let two = self.walk(&mut remaining, t);
408        let total = one
409            .iter()
410            .chain(&two)
411            .fold(C::zero(), |sum, &a| sum.plus(&self.arcs[a].3));
412        let states = |arcs: &[usize]| {
413            core::iter::once(self.states[0].clone())
414                .chain(arcs.iter().map(|&a| self.states[self.arcs[a].2].clone()))
415                .collect()
416        };
417        let edges = |arcs: &[usize]| arcs.iter().map(|&a| self.arcs[a].0.clone()).collect();
418
419        let mut pair = PathPair {
420            first: states(&one),
421            second: states(&two),
422            first_edges: edges(&one),
423            second_edges: edges(&two),
424        };
425        if pair.second < pair.first {
426            core::mem::swap(&mut pair.first, &mut pair.second);
427            core::mem::swap(&mut pair.first_edges, &mut pair.second_edges);
428        }
429
430        (pair, total)
431    }
432
433    /// Follows unused edges of `remaining` from state 0 to `t`, cutting any
434    /// cycle it closes; returns the edges.
435    fn walk(&self, remaining: &mut [Vec<usize>], t: usize) -> Vec<usize> {
436        let mut arcs = Vec::new();
437        let mut position = BTreeMap::from([(0_usize, 0_usize)]);
438        let mut at = 0;
439
440        while at != t {
441            let a = remaining[at]
442                .pop()
443                .expect("the union is a flow of two units");
444            at = self.arcs[a].2;
445            arcs.push(a);
446            if let Some(&p) = position.get(&at) {
447                // A cycle: drop it.
448                for dropped in arcs.drain(p..) {
449                    position.remove(&self.arcs[dropped].2);
450                }
451                position.insert(at, p);
452            } else {
453                position.insert(at, arcs.len());
454            }
455        }
456
457        arcs
458    }
459}
460
461/// `G` with every state but the ends split into an entry `(s, false)` and an
462/// exit `(s, true)`, joined by an edge of no weight.
463struct Split<'a, G: Graph> {
464    /// The underlying graph.
465    graph: &'a G,
466    /// The start, which only has an exit.
467    start: G::State,
468    /// The target, which only has an entry.
469    target: G::State,
470}
471
472/// An edge of [`Split`]: an original edge, or a state's inner edge.
473#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
474enum SplitEdge<E, S> {
475    /// An original edge, from an exit to an entry.
476    Edge(E),
477    /// From the entry to the exit of a state.
478    Inner(S),
479}
480
481impl<G: EdgeGraph> Graph for Split<'_, G> {
482    type State = (G::State, bool);
483    type Weight = Option<G::Weight>;
484
485    fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, Self::Weight)>) {
486        let mut edges = Vec::new();
487        self.edges(state, &mut edges);
488        out.extend(edges.into_iter().map(|(_, s, w)| (s, w)));
489    }
490}
491
492impl<G: EdgeGraph> EdgeGraph for Split<'_, G> {
493    type Edge = SplitEdge<G::Edge, G::State>;
494
495    fn edges(&self, state: &Self::State, out: &mut Vec<(Self::Edge, Self::State, Self::Weight)>) {
496        let (s, exit) = state;
497        if !exit {
498            if *s != self.target {
499                out.push((SplitEdge::Inner(s.clone()), (s.clone(), true), None));
500            }
501
502            return;
503        }
504
505        let mut edges = Vec::new();
506        self.graph.edges(s, &mut edges);
507        for (e, to, w) in edges {
508            if to != self.start {
509                out.push((SplitEdge::Edge(e), (to, false), Some(w)));
510            }
511        }
512    }
513}
514
515/// Maps a pair on [`Split`] back to the original graph.
516fn unsplit<S: Clone + PartialEq + Ord, E: Clone>(
517    pair: &PathPair<(S, bool), SplitEdge<E, S>>,
518) -> PathPair<S, E> {
519    let states = |path: &[(S, bool)]| {
520        let mut out: Vec<S> = Vec::new();
521        for (s, _) in path {
522            if out.last() != Some(s) {
523                out.push(s.clone());
524            }
525        }
526
527        out
528    };
529    let edges = |edges: &[SplitEdge<E, S>]| {
530        edges
531            .iter()
532            .filter_map(|e| match e {
533                SplitEdge::Edge(e) => Some(e.clone()),
534                SplitEdge::Inner(_) => None,
535            })
536            .collect::<Vec<_>>()
537    };
538
539    let mut out = PathPair {
540        first: states(&pair.first),
541        second: states(&pair.second),
542        first_edges: edges(&pair.first_edges),
543        second_edges: edges(&pair.second_edges),
544    };
545    if out.second < out.first {
546        core::mem::swap(&mut out.first, &mut out.second);
547        core::mem::swap(&mut out.first_edges, &mut out.second_edges);
548    }
549
550    out
551}
552
553/// The disjoint pairs whose total cost vectors are the vertices of the
554/// convex hull of the bi-objective front of disjoint pairs: the extreme
555/// supported pairs, sorted by total cost.
556///
557/// The bicriteria disjoint path pair problem (Clímaco and Pascoal 2009)
558/// asks for the pairs whose summed costs `(c1, c2)` are non-dominated.
559/// This finds its extreme supported points by dichotomic search, each step
560/// one [`disjoint_pair`] run on the weighted sum `w1 · c1 + w2 · c2`
561/// (lexicographic ends by large weights), summed exactly through
562/// [`ExactArith`]. The non-supported
563/// pairs between them are not searched; finding them needs a ranking of
564/// pairs, which this crate does not implement.
565///
566/// Requirements as for [`disjoint_pair`].
567///
568/// # Panics
569///
570/// Panics if a run that must succeed (a pair is known to exist) fails,
571/// which only a graph whose edges change between calls can cause.
572///
573/// # Examples
574///
575/// ```
576/// use multiobjective_search::{Disjointness, EdgeGraph, Graph, supported_disjoint_pairs};
577///
578/// /// Three parallel routes from 0 to 1.
579/// struct Routes;
580///
581/// const EDGES: [[u32; 2]; 3] = [[1, 9], [5, 5], [9, 1]];
582///
583/// impl Graph for Routes {
584///     type State = u8;
585///     type Weight = [u32; 2];
586///
587///     fn successors(&self, state: &u8, out: &mut Vec<(u8, [u32; 2])>) {
588///         if *state == 0 {
589///             out.extend(EDGES.iter().map(|&w| (1, w)));
590///         }
591///     }
592/// }
593///
594/// impl EdgeGraph for Routes {
595///     type Edge = usize;
596///
597///     fn edges(&self, state: &u8, out: &mut Vec<(usize, u8, [u32; 2])>) {
598///         if *state == 0 {
599///             out.extend(EDGES.iter().enumerate().map(|(i, &w)| (i, 1, w)));
600///         }
601///     }
602/// }
603///
604/// let pairs = supported_disjoint_pairs(&Routes, &0, &1, Disjointness::Edges);
605/// let costs: Vec<_> = pairs.iter().map(|(_, c)| *c).collect();
606/// // (10, 10) lies on the segment between the two: supported, not extreme.
607/// assert_eq!(costs, [[6, 14], [14, 6]]);
608/// ```
609pub fn supported_disjoint_pairs<G, C>(
610    graph: &G,
611    start: &G::State,
612    target: &G::State,
613    kind: Disjointness,
614) -> Vec<CostedPair<G::State, G::Edge, [C; 2]>>
615where
616    G: EdgeGraph<Weight = [C; 2]>,
617    C: Cost + ExactArith,
618{
619    let exact = |c: [C; 2]| [c[0].exact(), c[1].exact()];
620    let value = |w: &[C::Exact; 2], c: [C; 2]| {
621        let [c0, c1] = exact(c);
622        w[0].clone() * c0 + w[1].clone() * c1
623    };
624    let solve = |w: [C::Exact; 2]| {
625        let cost = |c: &[C; 2]| Exact(value(&w, *c));
626        suurballe(graph, start.clone(), target.clone(), cost, kind).map(|(pair, _)| {
627            let total = pair_cost(graph, &pair);
628            (pair, total)
629        })
630    };
631
632    // One more than any pair's total in the other objective, so that the
633    // weighted sums order lexicographically.
634    let [sum0, sum1] = reachable_sums(graph, start);
635    let one = C::Exact::one;
636    let Some(left) = solve([sum1.clone() + sum1 + one(), one()]) else {
637        return Vec::new();
638    };
639    let right = solve([one(), sum0.clone() + sum0 + one()]).expect("a pair exists");
640    if left.1 == right.1 {
641        return alloc::vec![left];
642    }
643
644    let mut found = alloc::vec![left];
645    let mut pending = alloc::vec![right];
646    while let Some(b) = pending.pop() {
647        let a = found.last().expect("starts with the left end").1;
648        let (ea, eb) = (exact(a), exact(b.1));
649        let w = [ea[1].abs_diff(&eb[1]), eb[0].abs_diff(&ea[0])];
650        let p = solve(w.clone()).expect("a pair exists");
651        if value(&w, p.1) < value(&w, a) {
652            pending.push(b);
653            pending.push(p);
654        } else {
655            found.push(b);
656        }
657    }
658
659    found
660}
661
662/// The sums over all reachable edges of each objective, exactly.
663fn reachable_sums<G, C>(graph: &G, start: &G::State) -> [C::Exact; 2]
664where
665    G: EdgeGraph<Weight = [C; 2]>,
666    C: Cost + ExactArith,
667{
668    let mut seen = BTreeSet::from([start.clone()]);
669    let mut stack = alloc::vec![start.clone()];
670    let mut sums = [C::Exact::zero(), C::Exact::zero()];
671    let mut edges = Vec::new();
672
673    while let Some(state) = stack.pop() {
674        graph.edges(&state, &mut edges);
675        for (_, to, w) in edges.drain(..) {
676            sums = [
677                sums[0].clone() + w[0].exact(),
678                sums[1].clone() + w[1].exact(),
679            ];
680            if seen.insert(to.clone()) {
681                stack.push(to);
682            }
683        }
684    }
685
686    sums
687}
688
689/// The summed weights of both paths of `pair`.
690fn pair_cost<G, C>(graph: &G, pair: &PathPair<G::State, G::Edge>) -> [C; 2]
691where
692    G: EdgeGraph<Weight = [C; 2]>,
693    C: Cost,
694{
695    let mut total = [C::ZERO; 2];
696    for (path, edges) in [
697        (&pair.first, &pair.first_edges),
698        (&pair.second, &pair.second_edges),
699    ] {
700        let mut buffer = Vec::new();
701        for (state, edge) in path.iter().zip(edges) {
702            graph.edges(state, &mut buffer);
703            let w = buffer
704                .iter()
705                .find(|(e, _, _)| e == edge)
706                .expect("the edge leaves its state")
707                .2;
708            total = [total[0] + w[0], total[1] + w[1]];
709            buffer.clear();
710        }
711    }
712
713    total
714}
715
716/// Up to `k` loopless paths from `start` to a goal in order of the scalar
717/// `cost(weight)`, each sharing at most `max_shared` edges with every
718/// earlier one: the greedy k-shortest dissimilar paths.
719///
720/// Paths are ranked best-first by `(cost, edge sequence)`, so equal costs
721/// are taken in a fixed order, and a path is kept when it is dissimilar
722/// enough from all kept ones (in the spirit of Moghanni et al. 2022, who
723/// trade cost against dissimilarity). Each result is `(states, edges,
724/// cost)`. Exponential in the worst case, like every ranking.
725///
726/// Requirements: non-negative costs; goals end paths.
727///
728/// # Panics
729///
730/// Never: partial paths are never empty.
731///
732/// # Examples
733///
734/// ```
735/// use multiobjective_search::{EdgeGraph, Graph, dissimilar_paths};
736///
737/// /// 0 → 1 by two edges, then 1 → 2 by two edges.
738/// struct Ladder;
739///
740/// const EDGES: [(u8, u8, u32); 4] = [(0, 1, 1), (0, 1, 2), (1, 2, 1), (1, 2, 2)];
741///
742/// impl Graph for Ladder {
743///     type State = u8;
744///     type Weight = u32;
745///
746///     fn successors(&self, state: &u8, out: &mut Vec<(u8, u32)>) {
747///         out.extend(EDGES.iter().filter(|e| e.0 == *state).map(|e| (e.1, e.2)));
748///     }
749/// }
750///
751/// impl EdgeGraph for Ladder {
752///     type Edge = usize;
753///
754///     fn edges(&self, state: &u8, out: &mut Vec<(usize, u8, u32)>) {
755///         out.extend(EDGES.iter().enumerate().filter(|(_, e)| e.0 == *state).map(|(i, e)| (i, e.1, e.2)));
756///     }
757/// }
758///
759/// // Fully disjoint: the cheapest path, then the one sharing nothing.
760/// let paths = dissimilar_paths(&Ladder, 0, |s| *s == 2, |w: &u32| *w, 3, 0);
761/// let costs: Vec<_> = paths.iter().map(|p| p.2).collect();
762/// assert_eq!(costs, [2, 4]);
763/// ```
764pub fn dissimilar_paths<G, C, P, F>(
765    graph: &G,
766    start: G::State,
767    is_goal: P,
768    cost: F,
769    k: usize,
770    max_shared: usize,
771) -> Vec<RankedPath<G::State, G::Edge, C>>
772where
773    G: EdgeGraph,
774    C: Cost,
775    P: Fn(&G::State) -> bool,
776    F: Fn(&G::Weight) -> C,
777{
778    let mut kept: Vec<RankedPath<G::State, G::Edge, C>> = Vec::new();
779    let mut open = BinaryHeap::new();
780    open.push(Reverse(Partial {
781        cost: C::ZERO,
782        edges: Vec::new(),
783        states: alloc::vec![start],
784    }));
785    let mut buffer = Vec::new();
786
787    while let Some(Reverse(partial)) = open.pop() {
788        if kept.len() >= k {
789            break;
790        }
791
792        let here = partial.states.last().expect("never empty").clone();
793        if is_goal(&here) {
794            let similar = kept.iter().any(|(_, edges, _)| {
795                partial.edges.iter().filter(|e| edges.contains(e)).count() > max_shared
796            });
797            if !similar {
798                kept.push((partial.states, partial.edges, partial.cost));
799            }
800
801            continue;
802        }
803
804        graph.edges(&here, &mut buffer);
805        for (edge, to, weight) in buffer.drain(..) {
806            if partial.states.contains(&to) {
807                continue;
808            }
809
810            let mut next = Partial {
811                cost: partial.cost + cost(&weight),
812                edges: partial.edges.clone(),
813                states: partial.states.clone(),
814            };
815            next.edges.push(edge);
816            next.states.push(to);
817            open.push(Reverse(next));
818        }
819    }
820
821    kept
822}
823
824/// A loopless partial path, ordered by cost and then edge sequence.
825struct Partial<S, E, C> {
826    /// Cost so far.
827    cost: C,
828    /// Edges so far.
829    edges: Vec<E>,
830    /// States so far; never empty.
831    states: Vec<S>,
832}
833
834impl<S, E: Ord, C: Ord> PartialEq for Partial<S, E, C> {
835    fn eq(&self, other: &Self) -> bool {
836        self.cmp(other) == Ordering::Equal
837    }
838}
839
840impl<S, E: Ord, C: Ord> Eq for Partial<S, E, C> {}
841
842impl<S, E: Ord, C: Ord> PartialOrd for Partial<S, E, C> {
843    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
844        Some(self.cmp(other))
845    }
846}
847
848impl<S, E: Ord, C: Ord> Ord for Partial<S, E, C> {
849    fn cmp(&self, other: &Self) -> Ordering {
850        (&self.cost, &self.edges).cmp(&(&other.cost, &other.edges))
851    }
852}