File tree Expand file tree Collapse file tree 2 files changed +19
-7
lines changed
Expand file tree Collapse file tree 2 files changed +19
-7
lines changed Original file line number Diff line number Diff 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 ! {
Original file line number Diff line number Diff 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 {
You can’t perform that action at this time.
0 commit comments