0

I am having this segment tree implementation to find maximum element in range :

int TREE[10000000]={0};
int arr[100000];
int RMQ(int ss, int se, int qs, int qe, int index)
{
if (qs <= ss && qe >= se)
    return TREE[index];
if (se < qs || ss > qe)
    return INT_MIN;
int mid=ss+(se-ss)/2;
return max(RMQ(ss, mid, qs, qe, 2*index+1),(mid+1, se, qs,qe, 2*index+2));
}

int constructTree(int ss,int se,int si)
{
if (ss == se)
{
    TREE[si] = arr[ss];
    return arr[ss];
}
int mid=ss+(se-ss)/2;
TREE[si]= max(constructTree(ss,mid,si*2+1),constructTree(mid+1, se,si*2+2));
return TREE[si];
}

And in main I am doing something like this :

int N,M;
cin>>N>>M;
for(int i=0;i<N;i++){
    cin>>arr[i];
}
constructTree(0,N-1,0);
while(M--){
    int L,R;
    cin>>L>>R;
    cout<<RMQ(0,N-1,L-1,R-1,0)<<endl;
}

But its giving wrong results. Like for input N=5 and M=1 and array be [3,1,3,2,1] for query L=1,R=1 it gives 8. Please help to find bug.

I am not able to find whats wrong with my code :(

mat7
  • 297
  • 3
  • 11

1 Answers1

0

The worst thing about that code has got to be your names. They make no sense, please learn to give proper names to your entities. It will help you debug and also decrease the chances of introducing bugs. You should also improve your indentation.

These will also make people more likely to answer your questions in the future, because it will be easier for them to understand the code you're posting.

int TREE[10000000]={0};
int arr[100000];

If your array can only have 100 000 elements, there is no need for your segment tree to hold 10 000 000. I'm surprised your program doesn't crash, that's almost 40 MB.

If you have n elements and you don't want to worry about checking for out of range indexes, you can declare your tree of size 2^k >= 2*n-1 In your case this would be 2^18 = 262 144.

Other than that, this looks wrong:

if (qs <= ss && qe >= se)

It should be, if I got your cryptic notation right:

if (qs >= ss && se <= qe)

The next condition:

if (se < qs || ss > qe)

Looks correct.

IVlad
  • 43,099
  • 13
  • 111
  • 179