|
| 1 | +#include <iostream> |
| 2 | +#include<climits> |
| 3 | +using namespace std; |
| 4 | + |
| 5 | +int query(int *tree,int ss,int se,int qs,int qe,int index){ |
| 6 | + ///Complete Overlap |
| 7 | + if(ss>=qs && se<=qe){ |
| 8 | + return tree[index]; |
| 9 | + } |
| 10 | + |
| 11 | + //No Overlap |
| 12 | + if(qe<ss || qs>se){ |
| 13 | + return INT_MAX; |
| 14 | + } |
| 15 | + |
| 16 | + //Partial Overlap - Call both sides and update the current ans |
| 17 | + int mid = (ss+se)/2; |
| 18 | + int leftAns = query(tree,ss,mid,qs,qe,2*index); |
| 19 | + int rightAns = query(tree,mid+1,se,qs,qe,2*index+1); |
| 20 | + return min(leftAns,rightAns); |
| 21 | + |
| 22 | +} |
| 23 | + |
| 24 | + |
| 25 | +void buildTree(int *a,int s,int e,int *tree,int index){ |
| 26 | + |
| 27 | + if(s==e){ |
| 28 | + tree[index] = a[s]; |
| 29 | + return ; |
| 30 | + } |
| 31 | + |
| 32 | + //Rec case |
| 33 | + int mid = (s+e)/2; |
| 34 | + buildTree(a,s,mid,tree,2*index); |
| 35 | + buildTree(a,mid+1,e,tree,2*index+1); |
| 36 | + tree[index] = min(tree[2*index],tree[2*index+1]); |
| 37 | + |
| 38 | + return; |
| 39 | +} |
| 40 | + |
| 41 | +int main() { |
| 42 | + |
| 43 | + int a[] = {1,3,2,-5,6,4}; |
| 44 | + int n = sizeof(a)/sizeof(int); |
| 45 | + |
| 46 | + int *tree = new int[4*n+1]; |
| 47 | + |
| 48 | + buildTree(a,0,n-1,tree,1); |
| 49 | + |
| 50 | + //Let print the tree |
| 51 | + for(int i=1;i<=13;i++){ |
| 52 | + // cout<<tree[i]<<" "; |
| 53 | + } |
| 54 | + |
| 55 | + int l,r; |
| 56 | + cin>>l>>r; |
| 57 | + cout<< query(tree,0,n-1,l,r,1); |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | + return 0; |
| 62 | +} |
0 commit comments