//! Knapsack table built by groups of equal weight (Section 4, eq. (update)). //! //! F(w), 0 <= w < len, is the largest total profit of a set of the items //! processed so far with total weight at most w. Profits are fixed-point //! integers (i64), so all comparisons, and hence SMAWK, are exact for the //! rounded instance. use crate::smawk; const NEG: i64 = i64::MIN / 4; pub enum Choices { None, U8(Vec), U16(Vec), U32(Vec), } impl Choices { #[inline] pub fn get(&self, i: usize) -> usize { match self { Choices::None => panic!("choices were not stored"), Choices::U8(v) => v[i] as usize, Choices::U16(v) => v[i] as usize, Choices::U32(v) => v[i] as usize, } } pub fn bytes(&self) -> usize { match self { Choices::None => 0, Choices::U8(v) => v.len(), Choices::U16(v) => 2 * v.len(), Choices::U32(v) => 4 * v.len(), } } } pub struct GroupRec { pub weight: usize, /// Item owners (global node ids), sorted by decreasing profit. pub owners: Vec, /// Table length right after this group. pub len_after: usize, pub choice: Choices, } pub struct Table { pub f: Vec, pub groups: Vec, /// Sum over groups of the updated table lengths (the work measure). pub work: u64, pub choice_bytes: usize, pub secs_direct: f64, pub secs_smawk: f64, pub work_smawk: u64, /// Sum over groups of g * (updated length): the cost of the plain band DP. pub work_naive: u64, } /// Largest group handled by the direct sweep instead of SMAWK (default 24; /// the environment variable KGRID_DIRECT_MAX overrides it, for experiments). fn direct_max() -> usize { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| std::env::var("KGRID_DIRECT_MAX").ok().and_then(|v| v.parse().ok()).unwrap_or(24)) } /// KGRID_ROWMAX=dc replaces SMAWK by divide-and-conquer row maxima (for experiments). fn use_dc() -> bool { static V: std::sync::OnceLock = std::sync::OnceLock::new(); *V.get_or_init(|| std::env::var("KGRID_ROWMAX").map(|v| v == "dc").unwrap_or(false)) } impl Table { /// `items[j]` lists (profit, owner) of the items of weight j. /// The table is truncated to budgets < `cap_len`. pub fn build(items: &mut [Vec<(i64, u32)>], cap_len: usize, keep_choices: bool) -> Table { let mut t = Table { f: vec![0], groups: vec![], work: 0, choice_bytes: 0, secs_direct: 0.0, secs_smawk: 0.0, work_smawk: 0, work_naive: 0 }; let cap_len = cap_len.max(1); let mut col: Vec = vec![]; let mut arg: Vec = vec![]; let mut pref: Vec = vec![]; let mut bbuf: Vec = vec![]; let mut abuf: Vec = vec![]; for j in 1..items.len() { if items[j].is_empty() { continue; } let grp = &mut items[j]; grp.sort_unstable_by(|a, b| b.0.cmp(&a.0).then(a.1.cmp(&b.1))); let old_len = t.f.len(); // Items beyond what fits into the capped table are useless. let gmax = (cap_len - 1) / j; let g = grp.len().min(gmax); if g == 0 { continue; } pref.clear(); pref.push(0); for i in 0..g { let v = pref[i] + grp[i].0; pref.push(v); } let new_len = (old_len + j * g).min(cap_len); let last = t.f[old_len - 1]; t.f.resize(new_len, last); let mut ch: Choices = if !keep_choices { Choices::None } else if g < 256 { Choices::U8(vec![0; new_len]) } else if g < 65536 { Choices::U16(vec![0; new_len]) } else { Choices::U32(vec![0; new_len]) }; let tg = std::time::Instant::now(); t.work_naive += (g * new_len) as u64; if g <= direct_max() { // In place, by blocks of length <= j from the top: a block // reads only entries below its start, which still hold old // values. The inner loops are branch-free and vectorize. let mut end = new_len; while end > 0 { let start = end.saturating_sub(j); let bl = end - start; bbuf.clear(); bbuf.extend_from_slice(&t.f[start..end]); abuf.clear(); abuf.resize(bl, 0); for c in 1..=g { let off = c * j; if end <= off { break; } let lo = start.max(off); let src = &t.f[lo - off..end - off]; let pc = pref[c]; let cc = c as u32; let bs = &mut bbuf[lo - start..]; let as_ = &mut abuf[lo - start..]; for ((b, a), &s) in bs.iter_mut().zip(as_.iter_mut()).zip(src.iter()) { let v = s + pc; let gt = v > *b; *b = if gt { v } else { *b }; *a = if gt { cc } else { *a }; } } t.f[start..end].copy_from_slice(&bbuf); match &mut ch { Choices::None => {} Choices::U8(v) => v[start..end].iter_mut().zip(&abuf).for_each(|(d, &s)| *d = s as u8), Choices::U16(v) => v[start..end].iter_mut().zip(&abuf).for_each(|(d, &s)| *d = s as u16), Choices::U32(v) => v[start..end].copy_from_slice(&abuf), } end = start; } t.work += new_len as u64; t.secs_direct += tg.elapsed().as_secs_f64(); t.choice_bytes += ch.bytes(); let owners: Vec = grp[..g].iter().map(|it| it.1).collect(); t.groups.push(GroupRec { weight: j, owners, len_after: new_len, choice: ch }); continue; } let nres = j.min(new_len); for rho in 0..nres { let n = (new_len - 1 - rho) / j + 1; col.clear(); col.extend((0..n).map(|x| t.f[rho + j * x])); if g <= 8 || n <= 16 { // direct scan of the band x in [y-g, y] for y in 0..n { let lo = y.saturating_sub(g); let mut best = col[y]; let mut bx = y; for x in lo..y { let v = col[x] + pref[y - x]; if v > best { best = v; bx = x; } } let pos = rho + j * y; t.f[pos] = best; set_choice(&mut ch, pos, y - bx); } } else { let colr = &col; let prefr = &pref; let look = |y: usize, x: usize| -> i64 { if x > y { NEG } else { colr[x] + prefr[(y - x).min(g)] } }; if use_dc() { smawk::row_maxima_dc(n, n, &look, &mut arg); } else { smawk::row_maxima(n, n, &look, &mut arg); } for y in 0..n { let mut x = arg[y] as usize; if y - x > g { // F nondecreasing: x = y-g is at least as good x = y - g; } let pos = rho + j * y; t.f[pos] = col[x] + pref[y - x]; set_choice(&mut ch, pos, y - x); } } } t.work += new_len as u64; t.work_smawk += new_len as u64; t.secs_smawk += tg.elapsed().as_secs_f64(); t.choice_bytes += ch.bytes(); let owners: Vec = grp[..g].iter().map(|it| it.1).collect(); t.groups.push(GroupRec { weight: j, owners, len_after: new_len, choice: ch }); } t } #[inline] pub fn value(&self, w: i64) -> i64 { if w < 0 { return NEG; } let i = (w as usize).min(self.f.len() - 1); self.f[i] } /// Recover the chosen items for budget w: calls `take(owner)` once per item. pub fn traceback(&self, w: i64, mut take: impl FnMut(u32)) { assert!(w >= 0); let mut w = w as usize; for gr in self.groups.iter().rev() { let wi = w.min(gr.len_after - 1); let c = gr.choice.get(wi); for &o in &gr.owners[..c] { take(o); } w = wi - c * gr.weight; } } } #[inline] fn set_choice(ch: &mut Choices, pos: usize, c: usize) { match ch { Choices::None => {} Choices::U8(v) => v[pos] = c as u8, Choices::U16(v) => v[pos] = c as u16, Choices::U32(v) => v[pos] = c as u32, } } #[cfg(test)] mod tests { use super::*; #[test] fn grouped_table_matches_plain_01_knapsack() { let mut seed = 7u64; let mut rnd = || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); seed >> 33 }; for _ in 0..300 { let nitems = 1 + (rnd() % 120) as usize; let maxw = 1 + (rnd() % 4) as usize; let mut items: Vec> = vec![vec![]; maxw + 1]; let mut flat = vec![]; for i in 0..nitems { let w = 1 + (rnd() % maxw as u64) as usize; let p = (rnd() % 50) as i64; items[w].push((p, i as u32)); flat.push((w, p)); } let total: usize = flat.iter().map(|x| x.0).sum(); let cap = 1 + (rnd() % (total as u64 + 3)) as usize; let t = Table::build(&mut items, cap, true); // plain 0/1 knapsack let mut best = vec![0i64; cap]; for &(w, p) in &flat { for b in (w..cap).rev() { best[b] = best[b].max(best[b - w] + p); } } for b in 0..cap { assert_eq!(t.value(b as i64), best[b]); let mut wsum = 0usize; let mut psum = 0i64; t.traceback(b as i64, |o| { wsum += flat[o as usize].0; psum += flat[o as usize].1; }); assert!(wsum <= b); assert_eq!(psum, best[b]); } } } } /// Memory-bounded reconstruction: the set of items of total weight <= w /// with maximum profit, found by splitting the weight groups in halves /// (Hirschberg-style). Tables without choices are built for both halves, /// the best split of the budget is chosen, and each half is solved /// recursively; a part whose choice tables fit in `budget_bytes` is solved /// directly. Calls `take(owner)` once per selected item. pub fn reconstruct(items: &[Vec<(i64, u32)>], w: i64, budget_bytes: usize, take: &mut dyn FnMut(u32)) { let js: Vec = (1..items.len()).filter(|&j| !items[j].is_empty()).collect(); rec_reconstruct(items, &js, w.max(0) as usize, budget_bytes, take); } fn sub_items(items: &[Vec<(i64, u32)>], js: &[usize]) -> Vec> { let mut v: Vec> = vec![vec![]; js.last().map_or(1, |&j| j + 1)]; for &j in js { v[j] = items[j].clone(); } v } fn rec_reconstruct(items: &[Vec<(i64, u32)>], js: &[usize], w: usize, budget: usize, take: &mut dyn FnMut(u32)) { if js.is_empty() || w == 0 { return; } let est = js.len() * (w + 1) * 2; if js.len() == 1 || est <= budget { let mut sub = sub_items(items, js); let t = Table::build(&mut sub, w + 1, true); t.traceback(w as i64, |o| take(o)); return; } let (l, r) = js.split_at(js.len() / 2); let tl = Table::build(&mut sub_items(items, l), w + 1, false); let tr = Table::build(&mut sub_items(items, r), w + 1, false); let mut best = i64::MIN; let mut w1 = 0usize; for a in 0..=w { let v = tl.value(a as i64) + tr.value((w - a) as i64); if v > best { best = v; w1 = a; } } drop(tl); drop(tr); rec_reconstruct(items, l, w1, budget, take); rec_reconstruct(items, r, w - w1, budget, take); } #[cfg(test)] mod recon_tests { use super::*; #[test] fn reconstruct_matches_full_table() { let mut seed = 99u64; let mut rnd = || { seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); seed >> 33 }; for _ in 0..200 { let maxw = 1 + (rnd() % 12) as usize; let mut items: Vec> = vec![vec![]; maxw + 1]; let mut flat = vec![]; for i in 0..(1 + rnd() % 30) { let wt = 1 + (rnd() % maxw as u64) as usize; let p = (rnd() % 40) as i64; items[wt].push((p, i as u32)); flat.push((wt, p)); } let total: usize = flat.iter().map(|x| x.0).sum(); let w = (rnd() % (total as u64 + 2)) as i64; let full = Table::build(&mut items.clone(), (w + 1) as usize, false); let (mut ws, mut ps) = (0usize, 0i64); reconstruct(&items, w, 1, &mut |o| { ws += flat[o as usize].0; ps += flat[o as usize].1; }); assert!(ws as i64 <= w); assert_eq!(ps, full.value(w)); } } }