This documentation is automatically generated by online-judge-tools/verification-helper
#include "segmenttree/binary_indexed_tree.hpp"
BIT の実装.テンプレート引数として渡すクラス $S$ は加算について結合法則を満たし,また逆元が取れる必要がある.
BIT<S> bit(n)
: コンストラクタ.長さ $n$ の数列 $A$ を $A_0 = \dots = A_{n - 1} = S()$ で初期化.計算量は $O(n)$.sum(l, r)
: $A_l + \dots + A_{r - 1}$ を計算.計算量は $O(\log n)$.sum(k)
: sum(0, k)
と同じ.計算量は $O(\log n)$.add(x, v)
: $A_x$ に $v$ を加算.計算量は $O(\log n)$.BIT<int> bit(N);
bit.add(2, 5);
bit.sum(1, 6);
#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 << ']';
}
};
#line 2 "segmenttree/binary_indexed_tree.hpp"
#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 << ']';
}
};