Skip to content

Add FenwickTree #7

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 8, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/fenwicktree.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// Reference: https://en.wikipedia.org/wiki/Fenwick_tree
pub struct FenwickTree<T> {
n: usize,
ary: Vec<T>,
e: T,
}

impl<T: Clone + std::ops::AddAssign<T>> FenwickTree<T> {
pub fn new(n: usize, e: T) -> Self {
FenwickTree {
n: n,
ary: vec![e.clone(); n],
e: e,
}
}
pub fn accum(&self, mut idx: usize) -> T {
let mut sum = self.e.clone();
while idx > 0 {
sum += self.ary[idx - 1].clone();
idx &= idx - 1;
}
sum
}
/// performs data[idx] += val;
pub fn add<U: Clone>(&mut self, mut idx: usize, val: U)
where
T: std::ops::AddAssign<U>,
{
let n = self.n;
idx += 1;
while idx <= n {
self.ary[idx - 1] += val.clone();
idx += idx & idx.wrapping_neg();
}
}
/// Returns data[l] + ... + data[r - 1].
pub fn sum(&self, l: usize, r: usize) -> T
where
T: std::ops::Sub<Output = T>,
{
self.accum(r) - self.accum(l)
}
}

#[cfg(test)]
mod tests {
use super::*;

#[test]
fn fenwick_tree_works() {
let mut bit = FenwickTree::new(5, 0i64);
// [1, 2, 3, 4, 5]
for i in 0..5 {
bit.add(i, i as i64 + 1);
}
assert_eq!(bit.sum(0, 5), 15);
assert_eq!(bit.sum(0, 4), 10);
assert_eq!(bit.sum(1, 3), 5);
}
}
2 changes: 2 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,5 @@ mod scc;
mod segtree;
mod string;
mod twosat;

pub use fenwicktree::FenwickTree;