#[inline]
pub fn lowbit(t: usize) -> usize {
debug_assert!(t >= 1);
t & t.wrapping_neg()
}
#[derive(Debug, Clone)]
pub enum CompressedFenwick {
Empty,
Singleton {
point: Vec<usize>,
value: f64,
},
Leaf1D {
coords: Vec<usize>,
bit: Vec<f64>,
},
Branch {
coords: Vec<usize>,
children: Vec<Option<CompressedFenwick>>,
},
}
impl CompressedFenwick {
pub fn build(points: &[Vec<usize>], k: usize) -> Self {
assert!(k >= 1, "CompressedFenwick dimension k must be >= 1");
if points.is_empty() {
return Self::Empty;
}
let mut unique: Vec<&[usize]> = points.iter().map(Vec::as_slice).collect();
unique.sort_unstable();
unique.dedup();
Self::build_from_unique(&unique, k)
}
fn build_from_unique(unique: &[&[usize]], k: usize) -> Self {
if unique.is_empty() {
return Self::Empty;
}
if unique.len() == 1 {
return Self::Singleton {
point: unique[0].to_vec(),
value: 0.0,
};
}
let mut coords: Vec<usize> = Vec::with_capacity(unique.len());
for p in unique {
let x1 = p[0];
if coords.last().copied() != Some(x1) {
coords.push(x1);
}
}
let m = coords.len();
if k == 1 {
return Self::Leaf1D {
coords,
bit: vec![0.0; m + 1],
};
}
let mut buckets: Vec<Vec<&[usize]>> = vec![Vec::new(); m + 1];
for p in unique {
let a = coords
.binary_search(&p[0])
.expect("point coordinate must exist in coords")
+ 1;
let tail = &p[1..];
let mut q = a;
while q <= m {
buckets[q].push(tail);
q += lowbit(q);
}
}
let mut children: Vec<Option<CompressedFenwick>> = Vec::with_capacity(m + 1);
children.push(None); for bucket in buckets.iter_mut().skip(1) {
if bucket.is_empty() {
children.push(None);
} else {
bucket.sort_unstable();
bucket.dedup();
children.push(Some(Self::build_from_unique(bucket, k - 1)));
}
}
Self::Branch { coords, children }
}
pub fn reset(&mut self) {
match self {
Self::Empty => {}
Self::Singleton { value, .. } => {
*value = 0.0;
}
Self::Leaf1D { bit, .. } => {
bit.fill(0.0);
}
Self::Branch { children, .. } => {
for child in children.iter_mut().flatten() {
child.reset();
}
}
}
}
pub fn update(&mut self, point: &[usize], val: f64) {
match self {
Self::Empty => unreachable!("update called on empty CompressedFenwick"),
Self::Singleton { point: pt, value } => {
debug_assert_eq!(pt.as_slice(), point);
*value += val;
}
Self::Leaf1D { coords, bit } => {
let a = coords
.binary_search(&point[0])
.expect("update coordinate not in compressed tree")
+ 1;
let m = coords.len();
let mut q = a;
while q <= m {
bit[q] += val;
q += lowbit(q);
}
}
Self::Branch { coords, children } => {
let a = coords
.binary_search(&point[0])
.expect("update coordinate not in compressed tree")
+ 1;
let m = coords.len();
let tail = &point[1..];
let mut q = a;
while q <= m {
if let Some(child) = children[q].as_mut() {
child.update(tail, val);
}
q += lowbit(q);
}
}
}
}
pub fn query(&self, bound: &[usize]) -> f64 {
match self {
Self::Empty => 0.0,
Self::Singleton { point, value } => {
if point.iter().zip(bound.iter()).all(|(&p, &b)| p <= b) {
*value
} else {
0.0
}
}
Self::Leaf1D { coords, bit } => {
let a = coords.partition_point(|&c| c <= bound[0]);
if a == 0 {
return 0.0;
}
let mut ans = 0.0;
let mut q = a;
while q > 0 {
ans += bit[q];
q -= lowbit(q);
}
ans
}
Self::Branch { coords, children } => {
let a = coords.partition_point(|&c| c <= bound[0]);
if a == 0 {
return 0.0;
}
let tail_bound = &bound[1..];
let mut ans = 0.0;
let mut q = a;
while q > 0 {
if let Some(child) = children[q].as_ref() {
ans += child.query(tail_bound);
}
q -= lowbit(q);
}
ans
}
}
}
}
#[derive(Debug, Clone)]
pub enum MultiChannelFenwick {
Empty,
Singleton {
point: Vec<usize>,
values: Vec<f64>,
},
Leaf1D {
coords: Vec<usize>,
channels: usize,
bit: Vec<f64>,
},
Branch {
coords: Vec<usize>,
children: Vec<Option<MultiChannelFenwick>>,
},
}
impl MultiChannelFenwick {
pub fn build(points: &[Vec<usize>], k: usize, channels: usize) -> Self {
assert!(k >= 1, "MultiChannelFenwick dimension k must be >= 1");
assert!(channels >= 1, "MultiChannelFenwick channels must be >= 1");
if points.is_empty() {
return Self::Empty;
}
let mut unique: Vec<&[usize]> = points.iter().map(Vec::as_slice).collect();
unique.sort_unstable();
unique.dedup();
Self::build_from_unique(&unique, k, channels)
}
fn build_from_unique(unique: &[&[usize]], k: usize, channels: usize) -> Self {
if unique.is_empty() {
return Self::Empty;
}
if unique.len() == 1 {
return Self::Singleton {
point: unique[0].to_vec(),
values: vec![0.0; channels],
};
}
let mut coords: Vec<usize> = Vec::with_capacity(unique.len());
for p in unique {
let x1 = p[0];
if coords.last().copied() != Some(x1) {
coords.push(x1);
}
}
let m = coords.len();
if k == 1 {
return Self::Leaf1D {
coords,
channels,
bit: vec![0.0; (m + 1) * channels],
};
}
let mut buckets: Vec<Vec<&[usize]>> = vec![Vec::new(); m + 1];
for p in unique {
let a = coords
.binary_search(&p[0])
.expect("point coordinate must exist in coords")
+ 1;
let tail = &p[1..];
let mut q = a;
while q <= m {
buckets[q].push(tail);
q += lowbit(q);
}
}
let mut children: Vec<Option<MultiChannelFenwick>> = Vec::with_capacity(m + 1);
children.push(None);
for bucket in buckets.iter_mut().skip(1) {
if bucket.is_empty() {
children.push(None);
} else {
bucket.sort_unstable();
bucket.dedup();
children.push(Some(Self::build_from_unique(bucket, k - 1, channels)));
}
}
Self::Branch { coords, children }
}
pub fn reset(&mut self) {
match self {
Self::Empty => {}
Self::Singleton { values, .. } => values.fill(0.0),
Self::Leaf1D { bit, .. } => bit.fill(0.0),
Self::Branch { children, .. } => {
for child in children.iter_mut().flatten() {
child.reset();
}
}
}
}
pub fn update(&mut self, point: &[usize], vals: &[f64]) {
match self {
Self::Empty => unreachable!("update called on empty MultiChannelFenwick"),
Self::Singleton { point: pt, values } => {
debug_assert_eq!(pt.as_slice(), point);
for (dst, &v) in values.iter_mut().zip(vals.iter()) {
*dst += v;
}
}
Self::Leaf1D {
coords,
channels,
bit,
} => {
let c = *channels;
let a = coords
.binary_search(&point[0])
.expect("update coordinate not in compressed tree")
+ 1;
let m = coords.len();
let mut q = a;
while q <= m {
let base = q * c;
let slot = &mut bit[base..base + c];
for (dst, &v) in slot.iter_mut().zip(vals.iter()) {
*dst += v;
}
q += lowbit(q);
}
}
Self::Branch { coords, children } => {
let a = coords
.binary_search(&point[0])
.expect("update coordinate not in compressed tree")
+ 1;
let m = coords.len();
let tail = &point[1..];
let mut q = a;
while q <= m {
if let Some(child) = children[q].as_mut() {
child.update(tail, vals);
}
q += lowbit(q);
}
}
}
}
pub fn query_add(&self, bound: &[usize], out: &mut [f64]) {
match self {
Self::Empty => {}
Self::Singleton { point, values } => {
if point.iter().zip(bound.iter()).all(|(&p, &b)| p <= b) {
for (dst, &v) in out.iter_mut().zip(values.iter()) {
*dst += v;
}
}
}
Self::Leaf1D {
coords,
channels,
bit,
} => {
let a = coords.partition_point(|&c| c <= bound[0]);
if a == 0 {
return;
}
let c = *channels;
let mut q = a;
while q > 0 {
let base = q * c;
let slot = &bit[base..base + c];
for (dst, &v) in out.iter_mut().zip(slot.iter()) {
*dst += v;
}
q -= lowbit(q);
}
}
Self::Branch { coords, children } => {
let a = coords.partition_point(|&c| c <= bound[0]);
if a == 0 {
return;
}
let tail_bound = &bound[1..];
let mut q = a;
while q > 0 {
if let Some(child) = children[q].as_ref() {
child.query_add(tail_bound, out);
}
q -= lowbit(q);
}
}
}
}
}