Search code examples
c++segment-tree

SPOJ GSS1 WA - Segment tree


I am trying to solve SPOJ problem GSS1 (Can you answer these queries I) using segment tree. I am using 'init' method to initialise a tree and 'query' method to get maximum in a range [i,j].

Limits |A[i]| <= 15707 and 1<=N (Number of elements)<=50000.

int A[50500], tree[100500];

void init(int n, int b, int e) // n=1, b=lower, e=end
{
    if(b == e)
    {
        tree[n] = A[b];
        return;
    }
    init(2 * n, b, (b + e) / 2);
    init(2 * n + 1, ((b + e) / 2) + 1, e);

    tree[n] = (tree[2 * n] > tree[2 * n + 1]) ? tree[2 * n] : tree[2 * n + 1];
}

int query(int n, int b, int e, int i, int j) // n=1, b=lower, e=end, [i,j]=range
{
    if(i>e || j<b) 
        return -20000;
    if(b>=i && e<=j)  
        return tree[n];

    int p1 = query(2 * n, b, (b + e) / 2, i, j);
    int p2 = query(2 * n + 1, ((b + e) / 2) + 1, e, i, j);

    return (p1 > p2) ? p1 : p2;
}

Program is giving Wrong Answer.I debbuged code for most of the cases (negative numbers, odd/even N) but I am unable to figure out what is wrong with algorithm.

If anyone can point me in right direction, I would be grateful.

Thanks


Solution

  • Edit: it seems your implementation is also correct, I'm just having another. And we both misread the problem statement.


    I guess you call your query function with params

    query( 1, 0, n-1, x-1, y-1 );
    

    I believe that it's wrong to handle with segment tree in such way when your n is not a pow of 2.
    I'm offering you to

    1. enlarge tree array to 131072 elements (2^17) and A to 65536 (2^16);
    2. found the smallest k such is not smaller than n and is a pow of 2;
    3. initialize elements from n (0-based) to k-1 with -20000;
    4. make n equal to k;
    5. make sure you call init(1,0,n-1);

    Hope that'll help you to beat WA.