Fenwick tree (aka Binary Indexed Tree)

Theory

Implementation in C++

#include <bits/stdc++.h>

using namespace std;

class FenwickTree {
    private:
        vector<int> tree;
        int size;

        int leastOneBit(int idx) {
            return idx & -idx;
        }
    public:
        FenwickTree(int n) {
            size = n + 1;
            tree.resize(size);
        }

        int read(int idx) {
            int sum = 0;
            while (idx > 0) {
                sum += tree[idx];
                idx -= leastOneBit(idx);
            }
            return sum;
        }

        void update(int idx, int val) {
            while (idx < size) {
                tree[idx] += val;
                idx += leastOneBit(idx);
            }
        }
};

Practice


by

Tags: