I wanted to code segment tree in c++ and wrote code query operation through recursion but it's slow and giving TLE. So, can Someone suggest and explain to code the following through iteration ,will be a great help.Thanks in advance.
following code computes gcd over a range
int getgcd(vector<int> T, int ss,int se, int L, int R, int index)
{
if (L <= ss && R >= se)
return T[index];
if (se < L || ss > R)
return 0;
int mid = ((ss+se)>>1);
return __gcd(getgcd(T, ss, mid, L, R, index<<1),getgcd(T, mid+1, se, L, R, (index<<1)+1));
}
Here ,
T-segment Tree
ss-segment Start
se-segment end
index-current node of segment tree
L-Lower query bound
R-upper uery bound
You pass a vector by value. It is copied every time you call this function. So the time complexity of your solution is O(n * log n) per query, not O(log n). Passing a vector by reference should fix it.