use std::collections::HashMap;
use crate::stnu_gen::StnuSpec;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Reaction {
Instant,
NextTick,
}
type Key = (i64, Vec<Option<i64>>);
struct Game<'a> {
spec: &'a StnuSpec,
reaction: Reaction,
last_tick: i64,
memo: HashMap<Key, bool>,
}
pub fn is_dc(spec: &StnuSpec, reaction: Reaction) -> bool {
let n = spec.point_count();
let mut times = vec![None; n];
times[0] = Some(0);
let mut game = Game {
spec,
reaction,
last_tick: spec.horizon + spec.links.iter().map(|l| l.2).sum::<i64>() + 1,
memo: HashMap::new(),
};
!game.lost(-1, ×) && game.wins(0, times)
}
impl Game<'_> {
fn wins(&mut self, t: i64, times: Vec<Option<i64>>) -> bool {
if times.iter().all(Option::is_some) {
return true;
}
if t > self.last_tick {
return false;
}
let key = (t, times);
if let Some(&v) = self.memo.get(&key) {
return v;
}
let (t, times) = key;
let value = self.solve_tick(t, ×);
self.memo.insert((t, times), value);
value
}
fn solve_tick(&mut self, t: i64, times: &[Option<i64>]) -> bool {
let (optional, forced) = self.nature_options(t, times);
let agent = self.agent_options(times);
let natures = subsets(&optional);
match self.reaction {
Reaction::Instant => natures.iter().all(|n| {
subsets(&agent)
.iter()
.any(|a| self.play(t, times, &forced, n, a))
}),
Reaction::NextTick => subsets(&agent)
.iter()
.any(|a| natures.iter().all(|n| self.play(t, times, &forced, n, a))),
}
}
fn play(
&mut self,
t: i64,
times: &[Option<i64>],
forced: &[usize],
nature: &[usize],
agent: &[usize],
) -> bool {
let mut next = times.to_vec();
for &p in forced.iter().chain(nature).chain(agent) {
next[p] = Some(t);
}
self.after_moves(t, next)
}
fn after_moves(&mut self, t: i64, times: Vec<Option<i64>>) -> bool {
if self.lost(t, ×) {
return false;
}
self.wins(t + 1, times)
}
fn nature_options(&self, t: i64, times: &[Option<i64>]) -> (Vec<usize>, Vec<usize>) {
let mut optional = Vec::new();
let mut forced = Vec::new();
for (i, &(act, lo, hi)) in self.spec.links.iter().enumerate() {
let c = self.spec.contingent(i);
let (Some(a), None) = (times[act], times[c]) else {
continue;
};
if t == a + hi {
forced.push(c);
} else if a + lo <= t && t < a + hi {
optional.push(c);
}
}
(optional, forced)
}
fn agent_options(&self, times: &[Option<i64>]) -> Vec<usize> {
(0..self.spec.n_exec)
.filter(|&p| times[p].is_none())
.collect()
}
fn lost(&self, t: i64, times: &[Option<i64>]) -> bool {
self.spec
.edges()
.any(|(u, v, w)| match (times[u], times[v]) {
(Some(tu), Some(tv)) => tv - tu > w,
(Some(tu), None) => tu + w <= t,
_ => false,
})
}
}
fn subsets(items: &[usize]) -> Vec<Vec<usize>> {
(0..1u32 << items.len())
.map(|mask| {
items
.iter()
.enumerate()
.filter(|(i, _)| mask & (1 << i) != 0)
.map(|(_, &p)| p)
.collect()
})
.collect()
}