I wrote a logic and it didnt work.So I copied a similar logic from the submitted answer and it worked. Pretty strange.See the previous submissions for this questions in Codechef for my actual code.