# Codeforces 343B

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

1. Find a place where red or blue is on top twice consecutively -> Find any “++” or “–” in the string.
2. Entangle it -> Remove the “++” or “–” found from the string.
3. 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.

2 Likes

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 .