Solution for SPOJ problem TOANDFRO.