Can't remove SIGSEGV, help needed

The problem is SPOJ.com - Problem NDS and my solution is wXBtMk - Online C++ Compiler & Debugging Tool - Ideone.com , I can’t figure out why my code gives segmentation fault, please have and look and let me know my mistake. Thank You.

Something to consider, is the amount of stack memory
int ar[n+1],tree[4*(n+1)+1];
will use if N is the maximum allowed by the constraints.
Do you know how large the stack is on SPOJ?

yeah its 10^6, btw I found my mistake, it was in the function query, I have changed it, now it no more gives segmentation fault, rather it gives a wrong answer :cry: (