-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegmentTree.cpp
More file actions
66 lines (53 loc) · 1.4 KB
/
segmentTree.cpp
File metadata and controls
66 lines (53 loc) · 1.4 KB
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#include <bits/stdc++.h>
using namespace std;
struct SegTree {
public:
SegTree(int _n, vector<int>& arr) : n(_n) {
tree.resize(4 * n, 0);
build(0, n - 1, 0, arr);
}
long long query(int x, int y) {
return query(x, y, 0, n - 1, 0);
}
void update(int pos, int val) {
update(pos, val, 0, n - 1, 0);
}
private:
vector<long long> tree;
int n;
void build(int l, int r, int i, const vector<int>& arr) {
if (l == r) {
tree[i] = arr[l];
return;
}
int m = (l + r) >> 1;
build(l, m, 2 * i + 1, arr);
build(m + 1, r, 2 * i + 2, arr);
tree[i] = (tree[2 * i + 1] + tree[2 * i + 2]);
}
long long query(int x, int y, int l, int r, int i) {
if (r < x || l > y) return 0;
if (l >= x && r <= y) return tree[i];
int m = (l + r) >> 1;
return (
(
query(x, y, l, m, 2 * i + 1) +
query(x, y, m + 1, r, 2 * i + 2)
)
);
}
void update(int pos, int val, int l, int r, int i) {
if (l == r) {
tree[i] += val;
return;
}
int m = (l + r) >> 1;
if (pos <= m)
update(pos, val, l, m, i * 2 + 1);
else
update(pos, val, m + 1, r, 2 * i + 2);
tree[i] = (tree[2 * i + 1] + tree[2 * i + 2]);
}
};
int main(){
}