mod pairs;
use alloc::collections::{BTreeMap, BTreeSet, BinaryHeap};
use alloc::vec::Vec;
use core::cmp::{Ordering, Reverse};
use search_core::{Cost, ExactArith, ExactNumber, WideMul};
use crate::graph::{EdgeGraph, Graph};
pub use pairs::{SharedPair, disjoint_pair_front, maximally_disjoint_pairs};
pub type CostedPair<S, E, C> = (PathPair<S, E>, C);
pub type RankedPath<S, E, C> = (Vec<S>, Vec<E>, C);
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Disjointness {
Edges,
States,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PathPair<S, E> {
pub first: Vec<S>,
pub second: Vec<S>,
pub first_edges: Vec<E>,
pub second_edges: Vec<E>,
}
pub fn disjoint_pair<G, C, F>(
graph: &G,
start: G::State,
target: G::State,
cost: F,
kind: Disjointness,
) -> Option<CostedPair<G::State, G::Edge, C>>
where
G: EdgeGraph,
C: Cost + WideMul,
F: Fn(&G::Weight) -> C,
{
suurballe(graph, start, target, |w| Plain(cost(w)), kind).map(|(pair, total)| (pair, total.0))
}
fn suurballe<G, T, F>(
graph: &G,
start: G::State,
target: G::State,
cost: F,
kind: Disjointness,
) -> Option<CostedPair<G::State, G::Edge, T>>
where
G: EdgeGraph,
T: Scalar,
F: Fn(&G::Weight) -> T,
{
match kind {
Disjointness::Edges => {
let net = Network::explore(graph, start, |w| cost(w));
net.suurballe(&target)
}
Disjointness::States => {
let split = Split {
graph,
start: start.clone(),
target: target.clone(),
};
let cost = |w: &Option<G::Weight>| w.as_ref().map_or_else(T::zero, &cost);
let net = Network::explore(&split, (start, true), cost);
let (pair, total) = net.suurballe(&(target, false))?;
Some((unsplit(&pair), total))
}
}
}
trait Scalar: Clone + Ord {
fn zero() -> Self;
#[must_use]
fn plus(&self, other: &Self) -> Self;
#[must_use]
fn distance(&self, other: &Self) -> Self;
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
struct Plain<C>(C);
impl<C: Cost + WideMul> Scalar for Plain<C> {
fn zero() -> Self {
Self(C::ZERO)
}
fn plus(&self, other: &Self) -> Self {
Self(self.0 + other.0)
}
fn distance(&self, other: &Self) -> Self {
Self(self.0.abs_diff(other.0))
}
}
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
struct Exact<T>(T);
impl<T: ExactNumber> Scalar for Exact<T> {
fn zero() -> Self {
Self(T::zero())
}
fn plus(&self, other: &Self) -> Self {
Self(self.0.clone() + other.0.clone())
}
fn distance(&self, other: &Self) -> Self {
Self(self.0.abs_diff(&other.0))
}
}
struct Network<S, E, C> {
states: Vec<S>,
index: BTreeMap<S, usize>,
arcs: Vec<(E, usize, usize, C)>,
out: Vec<Vec<usize>>,
}
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
enum Step {
Forward(usize),
Backward(usize),
}
impl<S: Clone + Ord, E: Clone, C: Scalar> Network<S, E, C> {
fn explore<G: EdgeGraph<State = S, Edge = E>>(
graph: &G,
start: S,
cost: impl Fn(&G::Weight) -> C,
) -> Self {
let mut net = Self {
states: Vec::new(),
index: BTreeMap::new(),
arcs: Vec::new(),
out: Vec::new(),
};
net.add(start);
let mut buffer = Vec::new();
let mut i = 0;
while i < net.states.len() {
graph.edges(&net.states[i].clone(), &mut buffer);
for (edge, to, weight) in buffer.drain(..) {
let j = net.add(to);
if j != i {
net.out[i].push(net.arcs.len());
net.arcs.push((edge, i, j, cost(&weight)));
}
}
i += 1;
}
net
}
fn add(&mut self, state: S) -> usize {
if let Some(&i) = self.index.get(&state) {
return i;
}
self.index.insert(state.clone(), self.states.len());
self.states.push(state);
self.out.push(Vec::new());
self.states.len() - 1
}
fn dijkstra(
&self,
steps: impl Fn(usize) -> Vec<(Step, usize, C)>,
) -> (Vec<Option<C>>, Vec<Option<Step>>) {
let n = self.states.len();
let (mut dist, mut parent) = (alloc::vec![None; n], alloc::vec![None; n]);
let mut done = alloc::vec![false; n];
let mut heap = BinaryHeap::from([Reverse((C::zero(), 0_usize, None::<Step>))]);
while let Some(Reverse((d, u, via))) = heap.pop() {
if done[u] {
continue;
}
done[u] = true;
dist[u] = Some(d.clone());
parent[u] = via;
for (step, v, c) in steps(u) {
if !done[v] {
heap.push(Reverse((d.plus(&c), v, Some(step))));
}
}
}
(dist, parent)
}
fn tail(&self, step: Step) -> usize {
match step {
Step::Forward(a) => self.arcs[a].1,
Step::Backward(a) => self.arcs[a].2,
}
}
fn trace(&self, parent: &[Option<Step>], to: usize) -> Vec<Step> {
let mut steps = Vec::new();
let mut at = to;
while let Some(step) = parent[at] {
steps.push(step);
at = self.tail(step);
}
steps.reverse();
steps
}
fn suurballe(&self, target: &S) -> Option<(PathPair<S, E>, C)> {
let t = *self.index.get(target)?;
let (dist, parent) = self.dijkstra(|u| self.original_steps(u));
dist[t].as_ref()?;
if t == 0 {
return None;
}
let first: Vec<usize> = self
.trace(&parent, t)
.into_iter()
.map(|s| match s {
Step::Forward(a) | Step::Backward(a) => a,
})
.collect();
let on_first: BTreeSet<usize> = first.iter().copied().collect();
let mut reversed: Vec<Vec<usize>> = alloc::vec![Vec::new(); self.states.len()];
for &a in &first {
reversed[self.arcs[a].2].push(a);
}
let (dist2, parent2) =
self.dijkstra(|u| self.residual_steps(u, &dist, &on_first, &reversed));
dist2[t].as_ref()?;
let used = Self::flow_union(on_first, self.trace(&parent2, t));
Some(self.pair_from_flow(&used, t))
}
fn original_steps(&self, u: usize) -> Vec<(Step, usize, C)> {
self.out[u]
.iter()
.map(|&a| (Step::Forward(a), self.arcs[a].2, self.arcs[a].3.clone()))
.collect()
}
fn residual_steps(
&self,
u: usize,
dist: &[Option<C>],
on_first: &BTreeSet<usize>,
reversed: &[Vec<usize>],
) -> Vec<(Step, usize, C)> {
let mut steps: Vec<(Step, usize, C)> = self.out[u]
.iter()
.filter(|a| !on_first.contains(a))
.map(|&a| {
let (_, from, to, c) = &self.arcs[a];
let (from, to) = (*from, *to);
let reduced = dist[from]
.as_ref()
.expect("reachable")
.plus(c)
.distance(dist[to].as_ref().expect("reachable"));
(Step::Forward(a), to, reduced)
})
.collect();
steps.extend(
reversed[u]
.iter()
.map(|&a| (Step::Backward(a), self.arcs[a].1, C::zero())),
);
steps
}
fn flow_union(mut on_first: BTreeSet<usize>, second: Vec<Step>) -> BTreeSet<usize> {
for step in second {
match step {
Step::Forward(a) => on_first.insert(a),
Step::Backward(a) => on_first.remove(&a),
};
}
on_first
}
fn pair_from_flow(&self, used: &BTreeSet<usize>, t: usize) -> (PathPair<S, E>, C) {
let mut remaining: Vec<Vec<usize>> = alloc::vec![Vec::new(); self.states.len()];
for &a in used {
remaining[self.arcs[a].1].push(a);
}
let one = self.walk(&mut remaining, t);
let two = self.walk(&mut remaining, t);
let total = one
.iter()
.chain(&two)
.fold(C::zero(), |sum, &a| sum.plus(&self.arcs[a].3));
let states = |arcs: &[usize]| {
core::iter::once(self.states[0].clone())
.chain(arcs.iter().map(|&a| self.states[self.arcs[a].2].clone()))
.collect()
};
let edges = |arcs: &[usize]| arcs.iter().map(|&a| self.arcs[a].0.clone()).collect();
let mut pair = PathPair {
first: states(&one),
second: states(&two),
first_edges: edges(&one),
second_edges: edges(&two),
};
if pair.second < pair.first {
core::mem::swap(&mut pair.first, &mut pair.second);
core::mem::swap(&mut pair.first_edges, &mut pair.second_edges);
}
(pair, total)
}
fn walk(&self, remaining: &mut [Vec<usize>], t: usize) -> Vec<usize> {
let mut arcs = Vec::new();
let mut position = BTreeMap::from([(0_usize, 0_usize)]);
let mut at = 0;
while at != t {
let a = remaining[at]
.pop()
.expect("the union is a flow of two units");
at = self.arcs[a].2;
arcs.push(a);
if let Some(&p) = position.get(&at) {
for dropped in arcs.drain(p..) {
position.remove(&self.arcs[dropped].2);
}
position.insert(at, p);
} else {
position.insert(at, arcs.len());
}
}
arcs
}
}
struct Split<'a, G: Graph> {
graph: &'a G,
start: G::State,
target: G::State,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum SplitEdge<E, S> {
Edge(E),
Inner(S),
}
impl<G: EdgeGraph> Graph for Split<'_, G> {
type State = (G::State, bool);
type Weight = Option<G::Weight>;
fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, Self::Weight)>) {
let mut edges = Vec::new();
self.edges(state, &mut edges);
out.extend(edges.into_iter().map(|(_, s, w)| (s, w)));
}
}
impl<G: EdgeGraph> EdgeGraph for Split<'_, G> {
type Edge = SplitEdge<G::Edge, G::State>;
fn edges(&self, state: &Self::State, out: &mut Vec<(Self::Edge, Self::State, Self::Weight)>) {
let (s, exit) = state;
if !exit {
if *s != self.target {
out.push((SplitEdge::Inner(s.clone()), (s.clone(), true), None));
}
return;
}
let mut edges = Vec::new();
self.graph.edges(s, &mut edges);
for (e, to, w) in edges {
if to != self.start {
out.push((SplitEdge::Edge(e), (to, false), Some(w)));
}
}
}
}
fn unsplit<S: Clone + PartialEq + Ord, E: Clone>(
pair: &PathPair<(S, bool), SplitEdge<E, S>>,
) -> PathPair<S, E> {
let states = |path: &[(S, bool)]| {
let mut out: Vec<S> = Vec::new();
for (s, _) in path {
if out.last() != Some(s) {
out.push(s.clone());
}
}
out
};
let edges = |edges: &[SplitEdge<E, S>]| {
edges
.iter()
.filter_map(|e| match e {
SplitEdge::Edge(e) => Some(e.clone()),
SplitEdge::Inner(_) => None,
})
.collect::<Vec<_>>()
};
let mut out = PathPair {
first: states(&pair.first),
second: states(&pair.second),
first_edges: edges(&pair.first_edges),
second_edges: edges(&pair.second_edges),
};
if out.second < out.first {
core::mem::swap(&mut out.first, &mut out.second);
core::mem::swap(&mut out.first_edges, &mut out.second_edges);
}
out
}
pub fn supported_disjoint_pairs<G, C>(
graph: &G,
start: &G::State,
target: &G::State,
kind: Disjointness,
) -> Vec<CostedPair<G::State, G::Edge, [C; 2]>>
where
G: EdgeGraph<Weight = [C; 2]>,
C: Cost + ExactArith,
{
let exact = |c: [C; 2]| [c[0].exact(), c[1].exact()];
let value = |w: &[C::Exact; 2], c: [C; 2]| {
let [c0, c1] = exact(c);
w[0].clone() * c0 + w[1].clone() * c1
};
let solve = |w: [C::Exact; 2]| {
let cost = |c: &[C; 2]| Exact(value(&w, *c));
suurballe(graph, start.clone(), target.clone(), cost, kind).map(|(pair, _)| {
let total = pair_cost(graph, &pair);
(pair, total)
})
};
let [sum0, sum1] = reachable_sums(graph, start);
let one = C::Exact::one;
let Some(left) = solve([sum1.clone() + sum1 + one(), one()]) else {
return Vec::new();
};
let right = solve([one(), sum0.clone() + sum0 + one()]).expect("a pair exists");
if left.1 == right.1 {
return alloc::vec![left];
}
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 (ea, eb) = (exact(a), exact(b.1));
let w = [ea[1].abs_diff(&eb[1]), eb[0].abs_diff(&ea[0])];
let p = solve(w.clone()).expect("a pair exists");
if value(&w, p.1) < value(&w, a) {
pending.push(b);
pending.push(p);
} else {
found.push(b);
}
}
found
}
fn reachable_sums<G, C>(graph: &G, start: &G::State) -> [C::Exact; 2]
where
G: EdgeGraph<Weight = [C; 2]>,
C: Cost + ExactArith,
{
let mut seen = BTreeSet::from([start.clone()]);
let mut stack = alloc::vec![start.clone()];
let mut sums = [C::Exact::zero(), C::Exact::zero()];
let mut edges = Vec::new();
while let Some(state) = stack.pop() {
graph.edges(&state, &mut edges);
for (_, to, w) in edges.drain(..) {
sums = [
sums[0].clone() + w[0].exact(),
sums[1].clone() + w[1].exact(),
];
if seen.insert(to.clone()) {
stack.push(to);
}
}
}
sums
}
fn pair_cost<G, C>(graph: &G, pair: &PathPair<G::State, G::Edge>) -> [C; 2]
where
G: EdgeGraph<Weight = [C; 2]>,
C: Cost,
{
let mut total = [C::ZERO; 2];
for (path, edges) in [
(&pair.first, &pair.first_edges),
(&pair.second, &pair.second_edges),
] {
let mut buffer = Vec::new();
for (state, edge) in path.iter().zip(edges) {
graph.edges(state, &mut buffer);
let w = buffer
.iter()
.find(|(e, _, _)| e == edge)
.expect("the edge leaves its state")
.2;
total = [total[0] + w[0], total[1] + w[1]];
buffer.clear();
}
}
total
}
pub fn dissimilar_paths<G, C, P, F>(
graph: &G,
start: G::State,
is_goal: P,
cost: F,
k: usize,
max_shared: usize,
) -> Vec<RankedPath<G::State, G::Edge, C>>
where
G: EdgeGraph,
C: Cost,
P: Fn(&G::State) -> bool,
F: Fn(&G::Weight) -> C,
{
let mut kept: Vec<RankedPath<G::State, G::Edge, C>> = Vec::new();
let mut open = BinaryHeap::new();
open.push(Reverse(Partial {
cost: C::ZERO,
edges: Vec::new(),
states: alloc::vec![start],
}));
let mut buffer = Vec::new();
while let Some(Reverse(partial)) = open.pop() {
if kept.len() >= k {
break;
}
let here = partial.states.last().expect("never empty").clone();
if is_goal(&here) {
let similar = kept.iter().any(|(_, edges, _)| {
partial.edges.iter().filter(|e| edges.contains(e)).count() > max_shared
});
if !similar {
kept.push((partial.states, partial.edges, partial.cost));
}
continue;
}
graph.edges(&here, &mut buffer);
for (edge, to, weight) in buffer.drain(..) {
if partial.states.contains(&to) {
continue;
}
let mut next = Partial {
cost: partial.cost + cost(&weight),
edges: partial.edges.clone(),
states: partial.states.clone(),
};
next.edges.push(edge);
next.states.push(to);
open.push(Reverse(next));
}
}
kept
}
struct Partial<S, E, C> {
cost: C,
edges: Vec<E>,
states: Vec<S>,
}
impl<S, E: Ord, C: Ord> PartialEq for Partial<S, E, C> {
fn eq(&self, other: &Self) -> bool {
self.cmp(other) == Ordering::Equal
}
}
impl<S, E: Ord, C: Ord> Eq for Partial<S, E, C> {}
impl<S, E: Ord, C: Ord> PartialOrd for Partial<S, E, C> {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl<S, E: Ord, C: Ord> Ord for Partial<S, E, C> {
fn cmp(&self, other: &Self) -> Ordering {
(&self.cost, &self.edges).cmp(&(&other.cost, &other.edges))
}
}