-
Notifications
You must be signed in to change notification settings - Fork 522
/
fenwick_tree.rs
46 lines (40 loc) · 907 Bytes
/
fenwick_tree.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use std::ops::AddAssign;
struct Fenwick<T> {
t: Vec<T>,
}
impl<T: AddAssign + Copy + From<i32>> Fenwick<T> {
fn new(n: usize) -> Self {
Fenwick {
t: vec![0.into(); n],
}
}
pub fn add(&mut self, mut i: usize, value: T) {
while i < self.t.len() {
self.t[i] += value;
i |= i + 1;
}
}
// sum[0..i]
pub fn sum(&self, mut i: i32) -> T {
let mut res: T = 0.into();
while i >= 0 {
res += self.t[i as usize];
i = (i & (i + 1)) - 1;
}
res
}
}
#[cfg(test)]
mod tests {
use crate::structures::fenwick_tree::Fenwick;
#[test]
fn basic_test() {
let mut t = Fenwick::<i32>::new(3);
t.add(0, 4);
t.add(1, 5);
t.add(2, 5);
t.add(2, 5);
assert_eq!(t.sum(0), 4);
assert_eq!(t.sum(2), 19);
}
}