Hello.I am trying to solve following problem at SPOJ : http://www.spoj.com/problems/HORRIBLE/

I am getting TLE at the first test case.If someone can help me to optimize my approach it will be a great help.

My solution Link: http://ideone.com/Hjzd7A

Let me know if anything is unclear in my solution.Thanks.