-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsegment-tree.cpp
67 lines (57 loc) · 1.71 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
class SegmentTree {
public:
int sz;
vector <int> tree;
SegmentTree(vector <int> &nums) {
sz = nums.size();
tree.resize(4 * (int)nums.size(), 0);
build(1, 0, (int)nums.size() - 1, nums);
}
void build(int node, int b, int e, vector <int> &nums) {
if (b > e) return;
if (b == e) {
tree[node] = nums[b];
return;
}
int l = node << 1, r = l | 1, m = (b + e) >> 1;
build(l, b, m, nums);
build(r, m + 1, e, nums);
tree[node] = tree[l] + tree[r];
}
int query(int node, int b, int e, int i, int j) {
if (i > e || j < b || b > e) return 0;
if (i <= b && j >= e) return tree[node];
int l = node << 1, r = l | 1, m = (b + e) >> 1;
return query(l, b, m, i, j) + query(r, m + 1, e, i, j);
}
int query(int left, int right) {
return query(1, 0, sz - 1, left, right);
}
void update(int node, int b, int e, int pos, int val) {
if (b > e || pos > e || pos < b) return;
if (b == e && b == pos) {
tree[node] = val;
return;
}
int l = node << 1, r = l | 1, m = (b + e) >> 1;
update(l, b, m, pos, val);
update(r, m + 1, e, pos, val);
tree[node] = tree[l] + tree[r];
}
void update(int index, int val) {
update(1, 0, sz - 1, index, val);
}
};
class NumArray {
public:
SegmentTree *tree;
NumArray(vector<int>& nums) {
tree = new SegmentTree(nums);
}
void update(int index, int val) {
tree -> update(index, val);
}
int sumRange(int left, int right) {
return tree -> query(left, right);
}
};