Advertisement
Guest User

segment tree

a guest
Jan 19th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.21 KB | None | 0 0
  1. /*
  2. Please note that it's Function problem i.e.
  3. you need to write your solution in the form of Function(s) only.
  4. Driver Code to call/invoke your function would be added by GfG's Online Judge.*/
  5.  
  6.  
  7. /* The functions which
  8. builds the segment tree */
  9. int *constructST(int arr[],int n)
  10. {
  11.   //Your code here
  12.   int st[4*n]; //size
  13.   for(int i=0;i<4*n;i++){
  14.       st[i]=5000;
  15.   }
  16.   buildSegmentTree(st,arr,0,n,0);
  17.   return st;
  18.  }
  19. /* The functions returns the
  20.  min element in the range
  21.  from a and b */
  22. int RMQ(int st[] , int n, int a, int b)
  23. {
  24. //Your code here
  25. query(st,0,n,a,b);
  26.    
  27. }
  28.  
  29. }
  30. void buildSegmentTree(int st[],int arr[],int low ,int high,int pos){
  31.     if(low==high){
  32.         st[pos]=arr[low];
  33.         return;
  34.     }
  35.     int mid =(low+high)/2;
  36.     int left=buildSegmentTree(st,arr,low,mid,2*pos+1);
  37.     int right=buildSegmentTree(sr,arr,mid+1,high,2*pos+2);
  38.     st[pos]=min(left,right);
  39. }
  40.  
  41. int  query(int st[],int low , int high ,int a,int b){
  42.     if(low<=a && high >=b){
  43.         return st[low/2];
  44.     }else if (high <a || low >b ){      
  45.         return 5000;
  46.    
  47.     }else{
  48.         int mid =(low+high)/2;
  49.         return min(query(st,low,mid,a,b),query(st,mid+1,high,a,b));
  50.     }
  51.    
  52.    
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement