Why am I getting TIme limit exceeded in this code?

I am getting time limit exceeded in September cook off problem MVAL.
solution: https://www.codechef.com/viewsolution/38368325
I will be really thankful to any suggestions to correct it.

cause here N can be upto 10^5 and T is upto 2,000. you are sorting the list making it NlogN*test_cases which won’t work. Think of O(N) Solution

I sorted the ans vector in this case as well but it worked perfectly fine.
Thanks for the suggestion though .
solution :https://www.codechef.com/viewsolution/38368240