Last active
April 4, 2018 16:49
-
-
Save aqzlpm11/928ba0f0e799826cbdb676bd63588c89 to your computer and use it in GitHub Desktop.
ACM algorithms
This file contains hidden or 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
/////////////////////////////////////////////////////// | |
// Binary Indexed Tree 树状数组 | |
/////////////////////////////////////////////////////// | |
#include <cassert> | |
template<typename T, int N> class BIT { | |
public: | |
T c[N]; | |
void init() { memset(c, 0, sizeof(c)); } | |
int lowbit(int x) { return x & (-x); } | |
void add(int i, int x) { | |
while(i < N) { | |
c[i] += x; | |
i += lowbit(i); | |
} | |
} | |
T query(int x) { | |
assert(x<N); | |
T sum=0; | |
while(x > 0) { | |
sum += c[x]; | |
x -= lowbit(x); | |
} | |
return sum; | |
} | |
}; | |
// Usage: | |
// BIT<int, N> bitree; | |
// bitree.init(); | |
// bitree.add(2, 3); | |
// bitree.query(3); | |
/////////////////////////////////////////////////////// |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment