This documentation is automatically generated by online-judge-tools/verification-helper
#include "DataStructure/fenwick_tree.hpp"
Fenwick Tree は区間の要素の総和を $\text{O}(\log N)$ で求めることができるデータ構造である.
実装は AtCoder Library のパクリ。
関数名など | 機能 | 計算量 |
---|---|---|
fenwick_tree<T>(int N) |
宣言. $N$ 個の要素をもつ配列を作る.初期値は0.T は + と - が定義されている構造体を載せることができる。 |
$\text{O}(N)$ |
void add(int p, T x) |
$a[p] += x$ を行う. $0 \leq p < N$ | $\text{O}(\log N)$ |
T sum(int l, int r) |
$a[l] + a[l - 1] + \cdots + a[r - 1]$ を返す。 $0 \leq l \leq r < N$ | $\text{O}(\log N)$ |
template <class T> struct fenwick_tree {
using U = T;
public:
fenwick_tree() : _n(0) {}
fenwick_tree(int n) : _n(n), data(n) {}
void add(int p, T x) {
assert(0 <= p && p < _n);
p++;
while (p <= _n) {
data[p - 1] += U(x);
p += p & -p;
}
}
T sum(int l, int r) {
assert(0 <= l && l <= r && r <= _n);
return sum(r) - sum(l);
}
private:
int _n;
std::vector<U> data;
U sum(int r) {
U s = 0;
while (r > 0) {
s += data[r - 1];
r -= r & -r;
}
return s;
}
};
#line 1 "DataStructure/fenwick_tree.hpp"
template <class T> struct fenwick_tree {
using U = T;
public:
fenwick_tree() : _n(0) {}
fenwick_tree(int n) : _n(n), data(n) {}
void add(int p, T x) {
assert(0 <= p && p < _n);
p++;
while (p <= _n) {
data[p - 1] += U(x);
p += p & -p;
}
}
T sum(int l, int r) {
assert(0 <= l && l <= r && r <= _n);
return sum(r) - sum(l);
}
private:
int _n;
std::vector<U> data;
U sum(int r) {
U s = 0;
while (r > 0) {
s += data[r - 1];
r -= r & -r;
}
return s;
}
};