Given two black/white panel arrangements, find the minimum movement cost to sort one into the other, where each swap of two panels costs 3 plus the distance moved.
Medium7MathCombinatoricsNo attempts yetTime limit8sMemory limit512 MBThe explorer Henry Nelson arrived at an ancient building. He wanted to go inside, but the entrance was held shut by a strange locking system.
In front of the entrance, black and white panels sit in a line at equal intervals, next to a machine with a cryptogram attached to it. After a while Henry read the cryptogram: the entrance opens once the panels are rearranged into a certain order, and the only way to change the order is this machine.
All the machine can do is swap a pair of panels. One swap takes three steps.
Three or more panels can never be marked at the same time. Every mark is erased once a swap is done.
The machine is heavy, so Henry does not want to move it more than he has to. Moving the machine between two adjacent panels costs 1. Find the minimum total cost of turning the panels into the target order. You can choose the starting position of the machine freely, and moving the machine to that position is not counted.
The input consists of several datasets.
One dataset is three lines. The first line holds the number of panels N (2≤N≤16). The second and the third line hold N characters each, describing the initial order and the target order of the panels in that order. Each character is B for black or W for white. Panels of the same color are not distinguished.
The last line of the input holds a single 0. The input has at most 15 datasets.
For each dataset, print the minimum cost on one line.
You can assume that at least one way of turning the initial order into the target order exists.