Skip to content

Instantly share code, notes, and snippets.

@changhengliou
Created May 27, 2020 09:57
Show Gist options
  • Save changhengliou/04da5bcea184a15f1c49fce3f8a6f586 to your computer and use it in GitHub Desktop.
Save changhengliou/04da5bcea184a15f1c49fce3f8a6f586 to your computer and use it in GitHub Desktop.
FenwickTree.cc
#include <iostream>
#include <vector>
// 8
// / \ \
// 4 6 7
// / \ \
// 2 3 5
// /
// 1
class FenwickTree {
private:
vector<int> arr;
int lowbit(int x) { return x & (-x); }
public:
FenwickTree(int n) : arr(vector<int>(n + 1)) {}
int query(int i) {
int sum = 0;
while (i > 0) {
sum += arr[i];
i -= lowbit(i);
}
return sum;
}
void update(int i, int val) {
while (i < arr.size()) {
arr[i] += val;
i += lowbit(i);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment