Marquee777
Marquee777

Reputation: 53

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

Upvotes: 0

Views: 1736

Answers (2)

Rameshwar Bhaskaran
Rameshwar Bhaskaran

Reputation: 345

I fear the (accepted) answer has missed out on a very important point here. The problem is here with the algorithm used in the code itself. The code says the answer for the node is the max of its children's values. But it is very much possible that the maximum subarray lies partially in BOTH children. For example

-1 -2 3 4 5 6 -5 -10 (n=8)

The code will output 11 while the answer is 18.

You will need to look into this case also to beat WA. (I am answering this because the accepted answer is not entirely right and doesn't answer this question correctly.)

Upvotes: 1

daftcoder
daftcoder

Reputation: 435

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.

Upvotes: 0

Related Questions