Help needed SPOJ - KOSARE

I tried solving SPOJ Problem KOSARE but I am getting WA on test case 12,Can any body point out the mistake in my implementation and also suggest some optimization so that it will not get TLE further.

Here is my implementation.

You can also explain your approach , Any help would be appreciated.

There is already a detailed post about such kinds of problems by @usaxena95 in the following link. Give it a try.

http://codeforces.com/blog/entry/45223

//