guest@cp-base:~/home/range-queries$
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 ii has children 2i2i and 2i+12i+1.

Operations

  • build(v) — construct from array in O(n)O(n)

  • update(i, val) — point update in O(logn)O(\log n)

  • query(l, r) — range query in O(logn)O(\log n)
  • Customization

  • Change combine() and IDENTITY to switch operations

  • Sum: combine = a + b, IDENTITY = 0

  • Min: combine = min(a, b), IDENTITY = INF

  • Max: combine = max(a, b), IDENTITY = -INF

  • XOR: combine = a ^ b, IDENTITY = 0
  • When to Use

  • Point updates + range queries

  • Online queries (unlike prefix sums, handles updates)

  • Building block for more advanced structures (lazy, persistent, beats)
  • Complexity

  • Build — O(n)O(n)

  • Update / Query — O(logn)O(\log n)

  • Space — O(4n)O(4n)