How can I optimize this code so that I'll not get time exceeded comment?

I solved problem Is this a Long Challenge , Problem Code ICM2004. While submitting the code I’m getting time exceeded comment. Help me optimizing the code.
My code is here.
https://www.codechef.com/viewsolution/29799834