Can someone help me understand why this programs terminates with time limit exceeded error .https://www.codechef.com/viewsolution/26013090

https://www.codechef.com/viewsolution/26013090
This is my code for the below problem. I think that the algorithm runs in O(t*(n+q)).
Am I missing something?
https://www.codechef.com/COOK109B/problems/RICHSTR/
Thanks in advance.