spoj problem KGSS -segment tree

I solved this problem using segment tree. For querying the two maximum numbers in a range(i,j), I called the query() function twice with different ranges. I have checked for several test cases and it is giving the correct answer but its showing WA in the judge. Please tell me where I am doing wrong. Here is the source code and the link to the problem.

Link to the problem- http://www.spoj.com/problems/KGSS/
link to the implemented code- http://ideone.com/wvoF5a

Please tell me my mistake.Thanks!!

Your Update function has a problem . It assumes that the element being updated is already not the max element . For example consider the test-case :
N = 2
array such that array[1] = 2 and array[2] = 3
After building tree : mat[1] = 2 , mat[2] = 1 , mat[3] = 2
Now update array[2] to 1
Now mat[1] should become 1 but that is not the case with your update function due to the flaw I mentioned !

1 Like
//