Created
May 27, 2020 09:57
-
-
Save changhengliou/04da5bcea184a15f1c49fce3f8a6f586 to your computer and use it in GitHub Desktop.
FenwickTree.cc
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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