Tetris Attack
Time limit1sMemory limit128 MB
A stack holds each of n symbols twice; adjacent equal pairs vanish on contact, and one move swaps neighboring elements. Find the minimum swaps to empty the stack.
- Level
Hard8 of 10
- Topics
- Greedy, Stack, Simulation, Combinatorics
- Solved
- No attempts yet
Problem
The puzzle "Tetris Attack" has recently become very popular in Byteotia. The full game is quite elaborate, so here we describe only a simplified version.
A stack is built from elements placed one on top of another. Each element carries one of symbols, and every symbol is written on exactly two elements.
A single move swaps two neighbouring elements, exchanging their positions. If, after a swap, two neighbouring elements carry the same symbol, both of them are removed from the stack. Every element that was above the removed pair falls down, and this may trigger further removals in a chain reaction.
The goal is to empty the stack completely in as few moves as possible. Given the initial contents of the stack, compute the minimum number of moves needed to empty it.
Input
The first line contains one integer (). The next lines describe the initial stack from bottom to top. The -th of these lines contains the symbol written on the -th element from the bottom ().
Every symbol appears exactly twice, and initially no two identical symbols are neighbours. The input is always chosen so that the stack can be emptied in at most moves.
Output
Print a single integer: the minimum number of moves needed to empty the stack.
Hint
