File tree Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Expand file tree Collapse file tree 2 files changed +60
-0
lines changed Original file line number Diff line number Diff line change 1+ #ifndef __FENWICK_H__
2+ #define __FENWICK_H__
3+
4+ #include < vector>
5+
6+ #define LSONE (x ) (x & (-x))
7+
8+ class Fenwick
9+ {
10+ private:
11+ std::vector<int > fen;
12+ public:
13+ Fenwick () {}
14+
15+ // We don't use the index 0
16+ Fenwick (int n)
17+ {
18+ fen.assign (n + 1 , 0 );
19+ }
20+
21+ // RSQ 1..a
22+ int rsq (int a)
23+ {
24+ int ans = 0 ;
25+ for (; a; a -= LSONE (a))
26+ ans += fen[a];
27+ return ans;
28+ }
29+
30+ // RSQ a..b
31+ inline int rsq (int a, int b)
32+ {
33+ return rsq (b) - (a == 1 ? 0 : rsq (a - 1 ));
34+ }
35+
36+ // Update the value of the k-th element by x
37+ void update (int k, int x)
38+ {
39+ for (; k < (int )fen.size (); k += LSONE (k))
40+ fen[k] += x;
41+ }
42+ };
43+
44+ #endif
Original file line number Diff line number Diff line change 1+ #include < cstdio>
2+ #include " fenwick_tree.h"
3+
4+ int main ()
5+ {
6+ Fenwick ft (5 );
7+
8+ ft.update (2 , 1 );
9+ ft.update (4 , 10 );
10+
11+ printf (" %d\n " , ft.rsq (1 ));
12+
13+ ft.update (1 , 5 );
14+ printf (" %d\n " , ft.rsq (1 ));
15+ return 0 ;
16+ }
You can’t perform that action at this time.
0 commit comments