Mark As Completed Discussion

Introduction to Fenwick Trees

Fenwick Trees, also known as Binary Indexed Trees (BIT), are a data structure that efficiently allows for querying and updating cumulative sums over a dynamic array or sequence.

The structure was proposed by Peter M. Fenwick in 1994 and is often used as a more efficient alternative to prefix sums or cumulative frequency tables.

A Fenwick Tree supports two main operations:

  • Update: Given an index idx and a value val, update the Fenwick Tree by adding val to the element at index idx.
  • Query: Given an index idx, calculate the sum of all the elements from index 1 to idx in the Fenwick Tree.

Fenwick Trees have a space complexity of O(n) and support both update and query operations in O(log n) time.

Here's an example of C++ code implementing a Fenwick Tree:

TEXT/X-C++SRC
1#include <iostream>
2using namespace std;
3
4int main() {
5  // Fenwick Tree implementation
6  int n;
7  cin >> n;
8
9  // Create an array to store the Fenwick Tree
10  int fenwick[n + 1];
11  for (int i = 0; i <= n; i++) {
12    fenwick[i] = 0;
13  }
14
15  // Update a value in the Fenwick Tree
16  int idx, val;
17  cin >> idx >> val;
18  while (idx <= n) {
19    fenwick[idx] += val;
20    idx += idx & -idx;
21  }
22
23  // Perform a query on the Fenwick Tree
24  int query;
25  cin >> query;
26  int sum = 0;
27  while (query > 0) {
28    sum += fenwick[query];
29    query -= query & -query;
30  }
31
32  // Output the result
33  cout << sum << endl;
34
35  return 0;
36}

In this example, we first initialize an array to store the Fenwick Tree (fenwick) and set all elements to 0. We then update a value in the Fenwick Tree by adding val to the element at index idx and updating the indices accordingly using bitwise operations. Finally, we perform a query on the Fenwick Tree by calculating the sum of all the elements from index 1 to query using bitwise operations as well. The result is outputted to the console.

Fenwick Trees are particularly useful when the number of updates is much smaller compared to the number of queries, making them a powerful tool for solving various algorithmic problems.

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment