Comments

isn't the time complexity of solution of f given is O(m*n) ?

TestCase for D were really not good. During contest my q*n solution got accepted. And after that someone hacked it. I didn't realise during the contest that what I was coding was q*n, if I would have got TLE, it would have been fairly easy to code up O(q) solution.