//
// 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];
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;
seg[si] = max((construct(arr, sb, mid, 2*si + 1)),
(construct(arr, mid+1, se, 2*si + 2)));
}
return seg[si];
}
int getMax(int sb, int se, int x, int y, int i) {
//Base case: Out of bound range
if (sb > y || se < x) {
return INT_MIN;
} else if (sb >= x && se <= y) {
return seg[i];
} else {
int mid = (sb+se)/2;
return max((getMax(sb, mid, x, y, 2*i + 1)),
(getMax(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 maximum value in arr[qs..qe]
cout<<"Maximum element in the range:"<<endl;
cout<<"x = 1, y = 5: "<<getMax(0, N-1, 1, 5, 0)<<endl;
cout<<"x = 0, y = 3: "<<getMax(0, N-1, 0, 3, 0)<<endl;
cout<<"x = 3, y = 5: "<<getMax(0, N-1, 3, 5, 0)<<endl;
cout<<"x = 0, y = 4: "<<getMax(0, N-1, 0, 4, 0)<<endl;
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTZWdtZW50IFRyZWUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjIvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxtYXRoLmg+CiNpbmNsdWRlIDxjbGltaXRzPgp1c2luZyBuYW1lc3BhY2Ugc3RkOwoKY29uc3QgaW50IE4gPSA2OwppbnQgc2VnWzIqTi0xXTsKCmludCBjb25zdHJ1Y3QgKGludCBhcnJbXSwgaW50IHNiLCBpbnQgc2UsIGludCBzaSkgewoKICAvL0Jhc2UgY2FzZSAob25seSAxIGVsZW1lbnQpCiAgaWYgKHNiID09I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