TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
fenwick_tree.cpp
Go to the documentation of this file.
1
20#include <cassert>
21#include <iostream>
22#include <vector>
23
28namespace range_queries {
33 size_t n = 0;
34 std::vector<int> bit{};
35
41 inline int offset(int x) { return (x & (-x)); }
42 public:
49 template <typename T>
50 explicit fenwick_tree(const std::vector<T>& arr) : n(arr.size()) {
51 bit.assign(n + 1, 0);
52 for (int i = 0; i < n; ++i) {
53 update(i, arr[i]);
54 }
55 }
56
63 template <typename T>
64 explicit fenwick_tree(T x) : n(x) { bit.assign(n + 1, 0); }
65
74 template <typename T>
75 void update(T id, T val) {
76 id++;
77 while (id <= n) {
78 bit[id] += val;
79 id += offset(id);
80 }
81 }
82
89 template <typename T>
90 int sum(T id) {
91 id++;
92 T res = 0;
93 while (id > 0) {
94 res += bit[id];
95 id -= offset(id);
96 }
97 return res;
98 }
99
106 int sum_range(int l, int r) { return sum(r) - sum(l - 1); }
107};
108} // namespace range_queries
109
114static void tests() {
115 std::vector<int> arr = {1, 2, 3, 4, 5};
116 range_queries::fenwick_tree fenwick_tree(arr);
117
118 assert(fenwick_tree.sum_range(0, 0) == 1);
119 assert(fenwick_tree.sum_range(0, 1) == 3);
120 assert(fenwick_tree.sum_range(0, 2) == 6);
121 assert(fenwick_tree.sum_range(0, 3) == 10);
122 assert(fenwick_tree.sum_range(0, 4) == 15);
123
124 fenwick_tree.update(0, 6);
125 std::cout << "All tests have successfully passed!\n";
126}
127
132int main() {
133 tests(); // run self-test implementations
134 return 0;
135}
The class that initializes the Fenwick Tree.
int sum_range(int l, int r)
Returns the prefix sum in range from L to R.
void update(T id, T val)
Updates the value of an element in original array and accordingly updates the values in BIT array.
int sum(T id)
Returns the sum of elements in range from 0 to ID.
fenwick_tree(const std::vector< T > &arr)
Class Constructor.
int offset(int x)
Returns the highest power of two which is not more than x.
fenwick_tree(T x)
Class Constructor.
std::vector< int > bit
Array that represents Binary Indexed Tree.
size_t n
No. of elements present in input array.
static void tests()
Self-test implementations.
int main()
Main function.
for std::vector