Can somebody explain solution to this problem http://codeforces.com/contest/343/problem/B

Think about how you would actually entangle such a thing if given. You cannot just pull any wire at any point in any direction. You would have to start somewhere suitable and entangle the whole mess step by step. The starting point would be anywhere that looks like the third test case (ignore the ends and pretend itâ€™s in the middle of the long chain)

Here you would pull up the red wire and pull down the blue wire, and you have successfully removed a pair of crossover points without affecting anything else. Of course if the red and blue wires were swapped you could still do the same thing.

So this means that you need to do the following

- Find a place where red or blue is on top twice consecutively -> Find any â€ś++â€ť or â€śâ€“â€ť in the string.
- Entangle it -> Remove the â€ś++â€ť or â€śâ€“â€ť found from the string.
- Repeat until there are no more such double crossovers -> Repeat until there are no â€ś++â€ť or â€śâ€“â€ť.

Now if you follow this itâ€™s actually \mathcal{O}(n^2) where n is the length of the string, which is too slow. One solution is to use a stack, in a way very similar to the various balanced brackets problems. At each index you check whether the top of the stack is the same symbol at the current index. If so, you pop the stack (effectively removing the â€ś++â€ť or â€śâ€“â€ť), and if not you add the current symbol to the stack (setting it up for removal when a matching symbol is found further along the string). Then move on to the next index. At the end if all symbols added to the stack were popped off, the wires have been untangled

This approach is \mathcal{O}(n) which works, and hereâ€™s my solution.

Thanks @meooww . Actually I was not able to understand the tutorial provided by them . It is completely different . Your solution is way nicer . Thank you very much for your time .

One more additional request :

Can you please advice me how to step up my level . I am stagnant from a long time now .

Yes in the tutorial they have changed the problem to another form with A and B symbols but it doesnâ€™t simplify the problem so I didnâ€™t see the point of that.

And to become better just keep participating in contests and practicing, really there is no secret to it

By the way I donâ€™t think questions like these should be closed, because if later someone else wants to share his possibly better approach, he wouldnâ€™t be able to.