Skip to content

Commit c409fe6

Browse files
authored
add linear build (#48)
* add linear build * format * add docs --------- Co-authored-by: Luke Videckis <lukevideckis@gmail.com>
1 parent 5a3efb5 commit c409fe6

File tree

2 files changed

+19
-7
lines changed

2 files changed

+19
-7
lines changed

examples/data_structures/fenwick_yosupo.rs

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,10 @@ fn main() {
77
input! {
88
n: usize,
99
q: usize,
10+
a: [u64; n],
1011
}
1112

12-
let mut fenwick = Fenwick::<u64>::new(n);
13-
for i in 0..n {
14-
input! {
15-
x: u64,
16-
}
17-
fenwick.add(i, x);
18-
}
13+
let mut fenwick = Fenwick::<u64>::build_on_array(&a);
1914

2015
for _ in 0..q {
2116
input! {

src/data_structures/fenwick.rs

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,23 @@ impl<T: Clone + Default + std::ops::AddAssign<T>> Fenwick<T> {
2626
}
2727
}
2828

29+
/// Creates a Fenwick Tree on a given array
30+
///
31+
/// # Complexity
32+
/// - Time: O(n)
33+
/// - Space: O(n)
34+
pub fn build_on_array(a: &[T]) -> Self {
35+
let mut ary = a.to_vec();
36+
for i in 0..a.len() {
37+
let j = i | (i + 1);
38+
if j < a.len() {
39+
let tmp = ary[i].clone();
40+
ary[j] += tmp;
41+
}
42+
}
43+
Fenwick { ary }
44+
}
45+
2946
fn accum(&self, mut idx: usize) -> T {
3047
let mut sum = T::default();
3148
while idx > 0 {

0 commit comments

Comments
 (0)