ja / en
Overview

SegmentTree

2024/07/29
2 min read

Purpose

For operators and arrays satisfying commutativity and associativity and having an identity element, it quickly computes the operation result of a continuous sub-range.
例: Addition of real numbers forms an Abelian group, so it satisfies the above properties. Specifically:

  • Commutativity: a+b=b+aa + b = b + a
  • Associativity: (a+b)+c=a+(b+c)(a+b)+c = a+(b+c)
  • Existence of identity element: a+0=aa + 0 = a

Since it satisfies these, it can be loaded onto a Segment Tree to quickly compute the sum of continuous sub-ranges.
Similar data structure: LazySegmentTree

Time Complexity

Initialization: O(n)O(n) Query: log(n)\log(n)

Usage

Declaration

SegmentTree<class> seg(array_length, lambda_for_binary_operation, identity_element);

Initialization

seg.set(i,x);

assigns x to the i-th element.
After array construction,

seg.build();

builds the segment tree.

Update

After construction,

seg.update(i,x)

updates the i-th element to x and rebuilds.

Query

seg.query(a,b)

returns the evaluated binary operation over the half-open interval [a,b)\left[ a,b \right).

Implementation

template <class T>
class SegmentTree {
public:
int n;
vector<T> s;
const function<T(T, T)> f;
const T m;
SegmentTree(int _n, const function<T(T, T)> &_f, const T &_m) : f(_f), m(_m) {
n = 1;
while (n < _n)
n <<= 1;
s.assign(2 * n, _m);
}
void set(int k, const T &x) {
s[k + n] = x;
}
void build() {
for (int k = n - 1; k > 0; k--)
s[k] = f(s[2 * k + 0], s[2 * k + 1]);
}
void update(int k, const T &x) {
k += n;
s[k] = x;
while (k >>= 1)
s[k] = f(s[2 * k + 0], s[2 * k + 1]);
}
T query(int a, int b) {
T L = m, R = m;
for (a += n, b += n; a < b; a >>= 1, b >>= 1) {
if (a & 1)
L = f(L, s[a++]);
if (b & 1)
R = f(s[--b], R);
}
return f(L, R);
}
T operator[](const int &k) const {
return s[k + n];
}
};

Verify

//TODO

Example

To quickly compute the sum of a continuous interval:

~build~
SegmentTree<int> seg(n, [](int a, int b){ return a+b; }, 0);

you just need to provide a lambda like this.