forked from MukulCode/CodingClubIndia
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsegment_tree.cpp
More file actions
62 lines (44 loc) · 1.17 KB
/
segment_tree.cpp
File metadata and controls
62 lines (44 loc) · 1.17 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
#include <iostream>
#include<climits>
using namespace std;
int query(int *tree,int ss,int se,int qs,int qe,int index){
///Complete Overlap
if(ss>=qs && se<=qe){
return tree[index];
}
//No Overlap
if(qe<ss || qs>se){
return INT_MAX;
}
//Partial Overlap - Call both sides and update the current ans
int mid = (ss+se)/2;
int leftAns = query(tree,ss,mid,qs,qe,2*index);
int rightAns = query(tree,mid+1,se,qs,qe,2*index+1);
return min(leftAns,rightAns);
}
void buildTree(int *a,int s,int e,int *tree,int index){
if(s==e){
tree[index] = a[s];
return ;
}
//Rec case
int mid = (s+e)/2;
buildTree(a,s,mid,tree,2*index);
buildTree(a,mid+1,e,tree,2*index+1);
tree[index] = min(tree[2*index],tree[2*index+1]);
return;
}
int main() {
int a[] = {1,3,2,-5,6,4};
int n = sizeof(a)/sizeof(int);
int *tree = new int[4*n+1];
buildTree(a,0,n-1,tree,1);
//Let print the tree
for(int i=1;i<=13;i++){
// cout<<tree[i]<<" ";
}
int l,r;
cin>>l>>r;
cout<< query(tree,0,n-1,l,r,1);
return 0;
}