//
// main.cpp
// Segment Tree
//
// Created by Himanshu on 22/08/21.
//
#include <iostream>
#include <math.h>
using namespace std;
const int N = 6;
int seg[2*N-1];
int construct (int arr[], int sb, int se, int si) {
if (sb == se) {
seg[si] = arr[sb];
} else {
int mid = (sb + se)/2;
seg[si] = construct(arr, sb, mid, 2*si + 1) +
construct(arr, mid+1, se, 2*si + 2);
}
return seg[si];
}
int getSum(int sb, int se, int x, int y, int i) {
if (sb > y || se < x) {
return 0;
} else if (sb >= x && se <= y) {
return seg[i];
} else {
int mid = (sb+se)/2;
return getSum(sb, mid, x, y, 2*i + 1) + getSum(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);
cout<<endl;
// Print minimum value in arr[qs..qe]
cout<<"Sum in the range:"<<endl;
cout<<"x = 0, y = 2: "<<getSum(0, N-1, 0, 2, 0)<<endl;
cout<<"x = 3, y = 4: "<<getSum(0, N-1, 3, 4, 0)<<endl;
cout<<"x = 2, y = 5: "<<getSum(0, N-1, 2, 5, 0)<<endl;
cout<<"x = 3, y = 5: "<<getSum(0, N-1, 3, 5, 0)<<endl;
cout<<"x = 0, y = 5: "<<getSum(0, N-1, 0, 5, 0)<<endl;
return 0;
}
Ly8KLy8gIG1haW4uY3BwCi8vICBTZWdtZW50IFRyZWUKLy8KLy8gIENyZWF0ZWQgYnkgSGltYW5zaHUgb24gMjIvMDgvMjEuCi8vCgojaW5jbHVkZSA8aW9zdHJlYW0+CiNpbmNsdWRlIDxtYXRoLmg+CnVzaW5nIG5hbWVzcGFjZSBzdGQ7Cgpjb25zdCBpbnQgTiA9IDY7CmludCBzZWdbMipOLTFdOwoKaW50IGNvbnN0cnVjdCAoaW50IGFycltdLCBpbnQgc2IsIGludCBzZSwgaW50IHNpKSB7CiAgICBpZiAoc2IgPT0gc2UpIHsKICAgICAgICBzZWdbc2ldID0gYXJyW3NiXTsKICAgIH0gZWxzZSB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