struct BIT<T> {
dat: Vec<T>,
}
impl<T: Clone + Default + std::ops::AddAssign + std::ops::Sub<Output = T>> BIT<T> {
fn new(n: usize) -> Self {
Self {
dat: vec![T::default(); n + 1],
}
}
// 0-based
fn add(&mut self, mut i: usize, x: T) {
i += 1; // convert to 1-based
while i < self.dat.len() {
self.dat[i] += x.clone();
i += i & (!i + 1); // i & (-i)
}
}
// 0..=i, 0-based
fn pref(&self, mut i: usize) -> T {
let mut res = T::default();
i += 1; // convert to 1-based
while i > 0 {
res += self.dat[i].clone();
i -= i & (!i + 1);
}
res
}
// l..r, 0-based
fn sum(&self, mut l: usize, mut r: usize) -> T {
if r == 0 {
T::default()
} else if l >= 1 {
self.pref(r - 1) - self.pref(l - 1)
} else {
self.pref(r - 1)
}
}
}
ABC231F