Chef and Functions JUNE 2014 CHALLENGE ??

I USED SIMPLE APPROACH TO SOLVE THIS AND GET TIME LIMIT EXCEED.
PLEASE EXPLAIN ME SOLUTION OF THIS PROBLEM AND APPROACH TO SOLVE THIS PROBLEM,WHICH TYPE OF ALGORITHM SHOULD BE USED TO SOLVE THESE PROBLEM ??

you can look at this EDITORIAL for detailed explanation and algorithm used to solve the problem and you cam look at editorials for any contest problem you want but before looking at editorials i suggest you to try the problem as many times as you can because it will increase your thinking level in solving problem and optimizing levels. :stuck_out_tongue: