I sent my solution to this problem, and I got ACC, but the last test case makes my program infinite-looping... that's weird... but I have no time to test that manually.
Your suggestions helped me a lot, though I don't understand absolutely the reason the algorithm is the way it is... I was trying a different approach, but didn't work. I'll have to analyze it later, so I can really understand the idea behind the solution ...