Difference between revisions of "Binary-Indexed Tree"
Jump to navigation
Jump to search
(Created page with "<syntaxhighlight lang='cpp'> template <typename T> class BIT { private: T a[N + 10]; public: void add(int x, T d) { x++; while (x < N) { a...") |
|||
Line 3: | Line 3: | ||
class BIT { | class BIT { | ||
private: | private: | ||
− | T a[ | + | static const int MAXN = N + 100; |
+ | T a[MAXN]; | ||
public: | public: | ||
void add(int x, T d) { | void add(int x, T d) { | ||
x++; | x++; | ||
− | while (x < | + | while (x < MAXN) { |
a[x] += d; | a[x] += d; | ||
x += x & -x; | x += x & -x; |
Revision as of 14:42, 10 March 2018
template <typename T>
class BIT {
private:
static const int MAXN = N + 100;
T a[MAXN];
public:
void add(int x, T d) {
x++;
while (x < MAXN) {
a[x] += d;
x += x & -x;
}
}
T query(int x) {
x++; T ret = 0;
while (x) {
ret += a[x];
x -= x & -x;
}
return ret;
}
T query_interval(int a, int b) {
// closed interval
return query(b) - query(a - 1);
}
/***** The following should be used exclusively *****/
inline T query2(int x) {
// used to query some value (not some sum)
return query(x);
}
void add2(int a, int b, T d) {
add(a, d); add(b + 1, -d);
}
};