TLE in WICP003 but custom test inputs working

Hi,

I am new to CP so this might seem trivial. I participated in [WICP2002 and I am getting TLE in the problem WICP003. I tried testing on upper range of the inputs to see if they are causing the problem but I could not duplicate the error. I think the judge is expecting my algorithm to be more efficient but I have no clue how to do that. My solution: https://ideone.com/GuoXHU

Any tips/ directions will surely help.

PS: The submission for this problem are now closed in the contest. But I would really like to have the direction so that it can help me improve my coding skills.