File tree Expand file tree Collapse file tree 2 files changed +81
-3
lines changed Expand file tree Collapse file tree 2 files changed +81
-3
lines changed Original file line number Diff line number Diff line change 1+ /*******************************************************************************
2+ * Fenwick Tree
3+ *
4+ * Data structure providing prefix sums and modify the table in O(log n) - n is the size o the table.
5+ *
6+ * In this algorithm we use two functions:
7+ * - RSQ - This function calculates the range sum query in O(log n)
8+ * - Update - This function adjusts the values in the given range in O(log n)
9+ *
10+ * https://en.wikipedia.org/wiki/Fenwick_tree
11+ *
12+ * @author Gabriel Duarte (gabriellagoa10@yahoo.com.br)
13+ * @github Gabriel123Duarte
14+ *
15+ ******************************************************************************/
16+
17+ #ifndef __FENWICK_H__
18+ #define __FENWICK_H__
19+
20+ #include <vector>
21+
22+ #define LSONE(x) (x & (-x))
23+
24+ class Fenwick
25+ {
26+ private:
27+ // Vector representing the table
28+ std::vector<int> fen;
29+ public:
30+ Fenwick() {}
31+
32+ // We don't use the index 0, because it is the base case
33+ Fenwick(int n)
34+ {
35+ fen.assign(n + 1, 0);
36+ }
37+
38+ // Calculate the
39+ int rsq(int a)
40+ {
41+ int ans = 0;
42+ for(; a; a -= LSONE(a))
43+ ans += fen[a];
44+ return ans;
45+ }
46+
47+ // RSQ a..b
48+ inline int rsq(int a, int b)
49+ {
50+ return rsq(b) - (a == 1 ? 0 : rsq(a - 1));
51+ }
52+
53+ // Update the value of the k-th element by x
54+ void update(int k, int x)
55+ {
56+ for(; k < (int)fen.size(); k += LSONE(k))
57+ fen[k] += x;
58+ }
59+ };
60+
61+ #endif
Original file line number Diff line number Diff line change 1+ /* ******************************************************************************
2+ * Fenwick Tree
3+ *
4+ * Data structure providing prefix sums and modify the table in O(log n) - n is the size o the table.
5+ *
6+ * In this algorithm we use two functions:
7+ * - RSQ - This function calculates the range sum query in O(log n)
8+ * - Update - This function adjusts the values in the given range in O(log n)
9+ *
10+ * https://en.wikipedia.org/wiki/Fenwick_tree
11+ *
12+ * @author Gabriel Duarte (gabriellagoa10@yahoo.com.br)
13+ * @github Gabriel123Duarte
14+ *
15+ ******************************************************************************/
16+
117#ifndef __FENWICK_H__
218#define __FENWICK_H__
319
824class Fenwick
925{
1026private:
27+ // Vector representing the table
1128std::vector<int > fen;
1229public:
1330Fenwick () {}
1431
15- // We don't use the index 0
32+ // We don't use the index 0, because it is the base case
1633Fenwick (int n)
1734{
1835fen.assign (n + 1 , 0 );
1936}
2037
21- // RSQ 1..a
38+ // Calculate the
2239int rsq (int a)
2340{
2441int ans = 0 ;
@@ -41,4 +58,4 @@ class Fenwick
4158}
4259};
4360
44- #endif
61+ #endif
You can’t perform that action at this time.
0 commit comments