-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathsegment-tree.cpp
42 lines (34 loc) · 869 Bytes
/
segment-tree.cpp
1
2
3
4
5
6
7
8
9
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
41
42
ll n, st[4*N], a[N];
void build( int v, int tl, int tr) {
if (tl == tr)
st[v] = a[tl];
else{
int tm = (tl + tr) / 2;
build(v*2, tl, tm);
build(v*2+1, tm+1, tr);
st[v] = st[v*2] + st[v*2+1];
}
}
void update(int v, int tl, int tr, int pos, int new_val) {
if (tl == tr)
st[v] = new_val;
else{
int tm = (tl + tr) / 2;
if (pos <= tm)
update(v*2, tl, tm, pos, new_val);
else
update(v*2+1, tm+1, tr, pos, new_val);
st[v] = st[v*2] + st[v*2+1];
}
}
int sum(int v, int tl, int tr, int l, int r) {
if (l > r)
return 0;
if (l == tl && r == tr) {
return st[v];
}
int tm = (tl + tr) / 2;
int q1 = sum(v*2, tl, tm, l, min(r, tm));
int q2 = sum(v*2+1, tm+1, tr, max(l, tm+1), r);
return q1 + q2;
}