Passing Temple Queues using treaps

I have passed Temple Queues on SPOJ in 1370ms, but I’m curious if it can be optimized so much as to pass the same question on Codechef in less than 400ms.

SPOJ problem link: - Problem TEMPLEQ
My code link: SPOJ TEMPLE QUEUE 1370ms -
CodeChef problem link: Contest Page | CodeChef

I have already spent too much time optimizing but can’t get any more improvement than this. Please give optimization tips/tricks :slight_smile:

[I know the solution using BIT, I just really want to optimize my treap implementation as much as possible]