-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsegtree.cpp
More file actions
31 lines (27 loc) · 726 Bytes
/
segtree.cpp
File metadata and controls
31 lines (27 loc) · 726 Bytes
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
const int N = 2e5;
int t[2 * N];
int n;
// change the neutral element and the query function depending on the problem
const int neutral = 0;
inline int f(int x, int y) { return x + y; }
// the tree is 0-indexed
void build()
{
for (int i = 0; i < n; i++) cin >> t[i + n];
for (int i = n - 1; i > 0; i--) t[i] = f(t[i << 1], t[i << 1 | 1]);
}
void update(int p, int value)
{
for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = f(t[p], t[p ^ 1]);
}
// query the range [l, r], l and r are inclusive
int query(int l, int r)
{
int ans = neutral;
for (l += n, r += n + 1; l < r; l >>= 1, r >>= 1)
{
if (l & 1) ans = f(ans, t[l++]);
if (r & 1) ans = f(ans, t[--r]);
}
return ans;
}