use alloc::collections::BTreeSet;
use alloc::vec::Vec;
use search_core::Cost;
use crate::cost::add;
use crate::graph::Graph;
#[derive(Debug, Clone)]
pub struct KnapsackGraph<C, const N: usize, const M: usize> {
items: Vec<([C; M], [C; N])>,
capacity: [C; M],
}
impl<C: Cost, const N: usize, const M: usize> KnapsackGraph<C, N, M> {
#[must_use]
pub const fn new(items: Vec<([C; M], [C; N])>, capacity: [C; M]) -> Self {
Self { items, capacity }
}
#[must_use]
pub const fn start(&self) -> (usize, [C; M], bool) {
(0, [C::ZERO; M], false)
}
#[must_use]
pub fn is_goal(&self, state: &(usize, [C; M], bool)) -> bool {
state.0 == self.items.len()
}
#[must_use]
pub fn taken(&self, path: &[(usize, [C; M], bool)]) -> Vec<usize> {
path.iter().filter(|s| s.2).map(|s| s.0 - 1).collect()
}
}
impl<C: Cost, const N: usize, const M: usize> Graph for KnapsackGraph<C, N, M> {
type State = (usize, [C; M], bool);
type Weight = [C; N];
fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, [C; N])>) {
let (i, used, _) = *state;
let Some(&(weights, values)) = self.items.get(i) else {
return;
};
out.push(((i + 1, used, false), values));
let after = add(used, weights);
if (0..M).all(|r| after[r] <= self.capacity[r]) {
out.push(((i + 1, after, true), [C::ZERO; N]));
}
}
}
pub struct LabelCount<'a, G, F> {
graph: &'a G,
slot: usize,
label: F,
}
impl<'a, G, F> LabelCount<'a, G, F> {
pub const fn new(graph: &'a G, slot: usize, label: F) -> Self {
Self { graph, slot, label }
}
pub const fn start<S, L>(&self, start: S) -> (S, BTreeSet<L>) {
(start, BTreeSet::new())
}
}
impl<G, F, L, C, const N: usize> Graph for LabelCount<'_, G, F>
where
G: Graph<Weight = [C; N]>,
F: Fn(&G::State, &G::State, &[C; N]) -> L,
L: Clone + Ord,
C: Cost + From<u8>,
{
type State = (G::State, BTreeSet<L>);
type Weight = [C; N];
fn successors(&self, state: &Self::State, out: &mut Vec<(Self::State, [C; N])>) {
let (from, seen) = state;
let mut edges = Vec::new();
self.graph.successors(from, &mut edges);
for (to, mut weight) in edges {
let label = (self.label)(from, &to, &weight);
let mut labels = seen.clone();
let new = labels.insert(label);
weight[self.slot] = C::from(u8::from(new));
out.push(((to, labels), weight));
}
}
}