SPOJ.com - Problem TOANDFRO


my solution to this problem is passing manual testing on ideone but is giving WA on spoj.
my sol: https://ideone.com/8T5byj
can anyone help me in debugging it.