i have devoted my whole day in solving this but getting NZEC error .i checked for so many testcases Plz check it at below link
Mysolution :- http://ideone.com/kfeqgc CodeChef: Practical coding for everyone
Problem link:-D1 Problem - CodeChef
I just implemented the editorial of this question.