Find the fewest adjacent swaps that let all paired cubes cancel by repeatedly deleting equal neighbors.
Medium7IntervalsSortingSegment treeNo attempts yetTime limit1sMemory limit256 MBA pile holds 2N cubes stacked one on top of another. Every cube carries an integer between 1 and N, and each integer appears on exactly two cubes.
When two cubes with the same number end up next to each other, both cubes disappear and every cube above them drops down to close the gap. Annihilation keeps going while some neighboring pair carries the same number.
You can swap two neighboring cubes. A swap is allowed only in a pile where no annihilation is possible, so you have to finish every annihilation first.
Find the smallest number of swaps that empties the pile.
Take N=4 and the pile 2 1 4 3 3 1 4 2, listed from the bottom up. One swap is enough. The two cubes labeled 3 already touch, so they vanish at once and the pile becomes 2 1 4 1 4 2. Swap the fourth cube (label 1) with the fifth cube (label 4): the two 4s vanish, then the 1s, then the 2s. Swapping the third and fourth cubes works too, and so does swapping the second and third.

Take N=3 and the pile 1 3 2 1 3 2. Three swaps are needed. Swap the fifth and sixth cubes, then the fourth and fifth; the two cubes labeled 2 vanish and the pile becomes 1 3 1 3. Swap the second and third cubes, and the remaining cubes vanish.

The first line contains one integer N (2≤N≤100000).
The second line contains 2N integers, the labels of the cubes listed from the bottom of the pile to the top, separated by spaces. Each integer from 1 to N appears exactly twice.
Print one non-negative integer M, the minimal number of swaps needed to remove every cube.