Help - INOI 1402

I am unable to fully solve this problem as my code fails on some test cases. My code :https://www.codechef.com/viewsolution/24472365