Logic review

Mr Pr in a Dilemma Problem Code: ICM2008 problem link:ICM2008 Problem - CodeChef

my submission link: CodeChef: Practical coding for everyone
My test case runs fine but after submission of my code , code show an error? Is my logic is rightor wrong?