-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathbinary_indexed_tree.hpp
33 lines (30 loc) · 979 Bytes
/
binary_indexed_tree.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#pragma once
#include <algorithm>
#include <vector>
// CUT begin
// 0-indexed BIT (binary indexed tree / Fenwick tree) (i : [0, len))
template <class T> struct BIT {
int n;
std::vector<T> data;
BIT(int len = 0) : n(len), data(len) {}
void reset() { std::fill(data.begin(), data.end(), T(0)); }
void add(int pos, T v) { // a[pos] += v
pos++;
while (pos > 0 and pos <= n) data[pos - 1] += v, pos += pos & -pos;
}
T sum(int k) const { // a[0] + ... + a[k - 1]
T res = 0;
while (k > 0) res += data[k - 1], k -= k & -k;
return res;
}
T sum(int l, int r) const { return sum(r) - sum(l); } // a[l] + ... + a[r - 1]
template <class OStream> friend OStream &operator<<(OStream &os, const BIT &bit) {
T prv = 0;
os << '[';
for (int i = 1; i <= bit.n; i++) {
T now = bit.sum(i);
os << now - prv << ',', prv = now;
}
return os << ']';
}
};