SPOJ.com - Problem TOANDFRO

my solution to this problem is passing manual testing on ideone but is giving WA on spoj.
my sol: 8T5byj - Online C++0x Compiler & Debugging Tool - Ideone.com
can anyone help me in debugging it.