Encoding April 20 contest problem: Naruto and chunin

Can someone please help me to figure out why my code is getting TLE?
I think my code’s time complexity is O(T*(M*M)), I am sorting the query elements and then using previously computed values to compute value for new query. Overall i am visiting each element in the matrix atmost thrice.

Link to my submission : - https://www.codechef.com/viewsolution/32314206

the size of set “last” can exceed 10^5 in one query
so complexity in worst case = O (Q*(10^5)*log(10^5))

1 Like

Ohh… Thanks a lot!!