Updating a Fenwick Tree
To update the value of an element in a Fenwick Tree, we can use the update
method. This method takes two parameters: index
and value
. Starting from the given index
, we update the corresponding values in the tree by adding the value
. We continue updating until we reach the end of the tree or go out of bounds.
Here's an example of how to implement the update
method in C++:
1void update(int index, int value) {
2 while (index < tree.size()) {
3 tree[index] += value;
4 index += index & (-index);
5 }
6}
In the above code, we iterate through the tree starting from the given index
and update the values by adding the value
. We update the index
by adding the least significant bit (obtained by using the &
operator with the two's complement of the index
). This process continues until we reach the end of the tree or go out of bounds.
Let's create a Fenwick Tree with a size of 10 and perform an update operation at index 5 with a value of 3. Then, we'll perform a query operation at index 8 and print the result.
xxxxxxxxxx
}
using namespace std;
// Class for Fenwick Tree
class FenwickTree {
private:
vector<int> tree;
public:
// Constructor
FenwickTree(int size) {
tree.resize(size + 1, 0);
}
// Update method
void update(int index, int value) {
while (index < tree.size()) {
tree[index] += value;
index += index & (-index);
}
}
// Query method
int query(int index) {
int sum = 0;
while (index > 0) {
sum += tree[index];
index -= index & (-index);
}
return sum;