-
Notifications
You must be signed in to change notification settings - Fork 41
/
Copy pathSparseSegmentTree.cc
67 lines (53 loc) · 1.23 KB
/
SparseSegmentTree.cc
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
#include <bits/stdc++.h>
using namespace std;
struct sparseSegmentTree{
struct node{
node *left, *right;
int cnt;
node(){
cnt = 0, left = NULL, right = NULL;
}
void updateNode(){
cnt = ((left == NULL)? 0 : left->cnt) + ((right == NULL)? 0 : right->cnt);
}
};
node *ROOT;
int L, R; // interval is closed from both sides i.e. [L,R]
sparseSegmentTree(int l, int r){
L = l, R = r;
ROOT = new node();
}
// point update
void update(int id, int val, int l, int r, node *cur){
if(l == r){
cur->cnt += val;
return;
}
int mid = (l + r) >> 1;
if(id <= mid){
if(cur->left == NULL) cur->left = new node();
update(id, val, l, mid, cur->left);
}
else{
if(cur->right == NULL) cur->right = new node();
update(id, val, mid+1, r, cur->right);
}
cur->updateNode();
}
// range query
int query(int x, int y, int l, int r, node *cur){
if(y < l or x > r or cur == NULL) return 0;
if(x <= l and r <= y) return cur->cnt;
int mid = (l + r) >> 1;
return query(x, y, l, mid, cur->left) + query(x, y, mid+1, r, cur->right);
}
void update(int id, int val){
update(id, val, L, R, ROOT);
}
int query(int x, int y){
return query(x, y, L, R, ROOT);
}
};
int main(){
return 0;
}