../ Algorithm Templates
-rw-r--r--aguang2.2 KiB2 min read

Fenwick Tree

A fenwick tree or binary indexed tree is a kind of data structure used to maintain the preffix sums of an ordered list of numbers.

cluster_subs C8 sum[8] = 33 C4 sum[4] = 19 C8->C4 C6 sum[6] = 7 C8->C6 C7 sum[7] = 4 C8->C7 A8 a[8] = 3 C8->A8 C2 sum[2] = 9 C4->C2 C3 sum[3] = 7 C4->C3 A4 a[4] = 3 C4->A4 C5 sum[5] = 2 C6->C5 A6 a[6] = 5 C6->A6 A7 a[7] = 4 C7->A7 C1 sum[1] = 9 C2->C1 A2 a[2] = 0 C2->A2 A3 a[3] = 7 C3->A3 A5 a[5] = 2 C5->A5 A1 a[1] = 9 C1->A1

The main concept of fenwick tree is LowbitLowbit function, which is the number of which all bits are assgined to zero without the last 11 in the given number's binary representation. Each node SumkSum_k in fenwick tree holds the sum of ∑i−lowbit(i)+1kAi\sum_{i - lowbit(i) + 1}^{k} A_i

In most programming languages, lowbitlowbit can be implemented like this:

c++
int lowbit(int x) {

  return x & (-x);
}

Implementation

c++
class bit {

  public:

    int *sum, size;

    bit(int size) {

      this->size = size;
      this->sum = new int[size + 1];

      for (int i = 0; i <= size; i++) {

        this->sum[i] = 0;
      }
    }

    void add(int pos, int value) {

      while (pos <= this->size) {

        sum[pos] += value;
        pos += (pos & (-pos));
      }
    }

    int query(int pos) {

      int result = 0;

      while (pos > 0) {

        result += sum[pos];
        pos -= (pos & (-pos));
      }

      return result;
    }
};

COMMAND INTERFACE

↑ ↓ navigate · Enter execute · Esc exit · try “whoami”

Loading filesystem…

:help aguang.xyz

A personal website disguised as an operating system.

Ctrl / Cmd + K
Command palette + full-text search
Tab / Shift + Tab
Move between links and controls
Enter
Open a focused link or search result
↑ / ↓ in search
Navigate search results
In a directory filter
Enter/Done or ↓ focuses a result; Esc clears the filter
Esc
Clear a search or close a window