Smart Phone problem

Why I am getting TLE for subtask 2? Please help me how to correct it.
Here is the link to my solution CodeChef: Practical coding for everyone

I think that you should use FAST IO.
I used std::sort and got 0.07 seconds on the hardest test.
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
It should help your timings.