//
// 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;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTZWdtZW50IFRyZWUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjIvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxtYXRoLmg+CiNpbmNsdWRlIDxjbGltaXRzPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE4gPSA2OwppbnQgc2VnWzIqTi0xXTsKCgovL1RoaXMgbWV0aG9kIGJ1aWxkIG91ciBzZWdtZW50I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