//
//  main.cpp
//  Segment Tree
//
//  Created by Himanshu on 22/08/21.
//

#include <iostream>
#include <math.h>
#include <climits>
using namespace std;

const int N = 6;
int seg[2*N-1];


//This method build our segment tree ie. the array seg
int construct (int arr[], int sb, int se, int si) {

  //Base case (only 1 element)
  if (sb == se) {
    seg[si] = arr[sb];
  } else {
    int mid = (sb+se)/2;   //Dividing given range in two equal halves

    seg[si] = min((construct(arr, sb, mid, 2*si + 1)), 
                           (construct(arr, mid+1, se, 2*si + 2)));
  }

  return seg[si];
}

int getMin(int sb, int se, int x, int y, int i) {

 //Base case: Out of bound range
 if (sb > y || se < x) {
   return INT_MAX;
 } else if (sb >= x && se <= y) {
   return seg[i]; //Node in permissible range, send the value of internal node (i). 
 } else {
   int mid = (sb+se)/2;
   return min((getMin(sb, mid, x, y, 2*i + 1)),     // Checking children nodes [(2*i+1), (2*i+2)]
              (getMin(mid+1, se, x, y, 2*i + 2)));
 }

}


int main() {
    int arr[] = {1, 3, 2, 7, 9, 11};
    
    // Constructing segment tree (preprocessing)
    construct(arr, 0, N-1, 0);

    // Print minimum value in arr[qs..qe]
    cout<<"Minimum element in the range:"<<endl;
    cout<<"x = 1, y = 5: "<<getMin(0, N-1, 1, 5, 0)<<endl;
    cout<<"x = 0, y = 3: "<<getMin(0, N-1, 0, 3, 0)<<endl;
    cout<<"x = 3, y = 5: "<<getMin(0, N-1, 3, 5, 0)<<endl;
    cout<<"x = 0, y = 4: "<<getMin(0, N-1, 0, 4, 0)<<endl;
    
    return 0;
}
