templates/segment-tree.cpp
compilable
$cat templates/segment-tree
Segment Tree
Classic segment tree with point update and range query for any associative operation.
#segment-tree#range-query#point-update
Log in to track progress, save custom versions, and organize into collections.Log In
$cat source_code/
cpp
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const int MAXN = 2e5 + 5;
ll tree[4 * MAXN];
ll IDENTITY = 0;
int n;
ll combine(ll a, ll b) { return a + b; }
void build(ll a[], int idx, int lx, int rx) {
if (lx == rx) { tree[idx] = a[lx]; return; }
int mid = (lx + rx) / 2;
build(a, 2 * idx, lx, mid);
build(a, 2 * idx + 1, mid + 1, rx);
tree[idx] = combine(tree[2 * idx], tree[2 * idx + 1]);
}
void build(ll a[]) { build(a, 1, 1, n); }
void update(int pos, ll val, int idx, int lx, int rx) {
if (lx == rx) { tree[idx] = val; return; }
int mid = (lx + rx) / 2;
if (pos <= mid) update(pos, val, 2 * idx, lx, mid);
else update(pos, val, 2 * idx + 1, mid + 1, rx);
tree[idx] = combine(tree[2 * idx], tree[2 * idx + 1]);
}
void update(int pos, ll val) { update(pos, val, 1, 1, n); }
ll query(int l, int r, int idx, int lx, int rx) {
if (lx > r || rx < l) return IDENTITY;
if (lx >= l && rx <= r) return tree[idx];
int mid = (lx + rx) / 2;
return combine(query(l, r, 2 * idx, lx, mid),
query(l, r, 2 * idx + 1, mid + 1, rx));
}
ll query(int l, int r) { return query(l, r, 1, 1, n); }40 linesutf-8
$cat explanation_notes.md
notes_viewer --renderedmarkdown (math enabled)
Segment Tree
Binary tree where each node stores the result of an associative operation over a contiguous range. Node has children and .
Operations
build(v) — construct from array in update(i, val) — point update in query(l, r) — range query in Customization
combine() and IDENTITY to switch operationscombine = a + b, IDENTITY = 0combine = min(a, b), IDENTITY = INFcombine = max(a, b), IDENTITY = -INFcombine = a ^ b, IDENTITY = 0