-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSegment_Tree_2.cpp
59 lines (40 loc) · 1.02 KB
/
Segment_Tree_2.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
// Specifically for problems, related to LeetCode
int N;
vector<int> v, Tree;
void buildTree(int tidx, int lo, int hi){
if(lo==hi){
Tree[tidx] = v[hi];
return;
}
int mid = (lo+hi)/2;
buildTree(2*tidx+1, lo, mid);
buildTree(2*tidx+2, mid+1, hi);
Tree[tidx] = Tree[2*tidx+1] + Tree[2*tidx+2];
}
void updateTree(int tidx, int lo, int hi, int idx, int val){
if(lo==hi){
Tree[tidx] = val;
return;
}
int mid = (lo+hi)/2;
if(idx<=mid)
updateTree(2*tidx+1, lo, mid, idx, val);
else
updateTree(2*tidx+2, mid+1, hi, idx, val);
Tree[tidx] = Tree[2*tidx+1] + Tree[2*tidx+2];
}
int query(int tidx, int lo, int hi, int L, int R){
// The Range which we are currently in : [lo, hi]
// The Range of which we have to compute the answer : [L, R]
// Outside Range
if( R<lo || L>hi )
return 0;
// In Range
if( L<=lo && hi<=R )
return Tree[tidx];
// Partial Overlap
int mid = (lo+hi)/2;
int leftans = query(2*tidx+1, lo, mid, L, R);
int rightans = query(2*tidx+2, mid+1, hi, L, R);
return leftans + rightans;
}