use alloc::vec::Vec;
use sas_plus::{OpId, State, Task};
use crate::{Heuristic, LmCut, Relaxation};
#[derive(Clone, Debug)]
pub struct AdditiveHMax {
h_max: LmCut<'static>,
part_costs: Vec<Vec<u64>>,
}
impl AdditiveHMax {
#[must_use]
pub fn new(task: &Task) -> Self {
let parts: Vec<usize> = task
.operators
.iter()
.map(|op| op.eff.iter().map(|e| e.fact.var).min().unwrap_or(0))
.collect();
Self::with_partition(task, &parts)
}
#[must_use]
pub fn with_partition(task: &Task, parts: &[usize]) -> Self {
assert_eq!(parts.len(), task.operators.len(), "one part per operator");
let h_max = LmCut::unsplit(Relaxation::new(task));
let mut used: Vec<usize> = parts.to_vec();
used.sort_unstable();
used.dedup();
let part_costs = used
.iter()
.map(|&part| {
(0..parts.len())
.map(|op: OpId| {
if parts[op] == part {
h_max.costs()[op]
} else {
0
}
})
.collect()
})
.collect();
Self { h_max, part_costs }
}
#[must_use]
pub fn value(&mut self, state: &State) -> Option<u64> {
if self.part_costs.is_empty() {
return self.h_max.h_max_under(state, &[]);
}
let mut total = 0_u64;
for costs in &self.part_costs {
total = total.saturating_add(self.h_max.h_max_under(state, costs)?);
}
Some(total)
}
}
impl Heuristic<State> for AdditiveHMax {
fn estimate(&mut self, state: &State) -> Option<u32> {
self.value(state)
.map(|v| u32::try_from(v).unwrap_or(u32::MAX))
}
}