Mark As Completed Discussion

Range Updates and Range Queries

In this section, we will discuss the concepts of range updates and range queries in Fenwick Trees.

Range Updates

Range updates allow us to update a range of values efficiently in a Fenwick Tree. To perform a range update, we traverse the Fenwick Tree using bitwise operations and update the values at each index within the given range.

Here's an example code snippet in C++ that demonstrates how to perform a range update on a Fenwick Tree:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4void rangeUpdate(int fenwick[], int index, int value) {
5  while (index <= n) {
6    fenwick[index] += value;
7    index += (index & -index);
8  }
9}
10
11int main() {
12  int n;
13  cin >> n;
14
15  int fenwick[n + 1];
16  for (int i = 0; i <= n; i++) {
17    fenwick[i] = 0;
18  }
19
20  int start, end, value;
21  cin >> start >> end >> value;
22
23  rangeUpdate(fenwick, start, value);
24  rangeUpdate(fenwick, end + 1, -value);
25
26  return 0;
27}
CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment