Link to my submission: http://www.codechef.com/viewsolution/6436081
What did I do wrong ?
There are two mistakes in the solution. I have commented them in the solution. Check the solution here.