#C6583. Minimum Moves to Rearrange Books
Minimum Moves to Rearrange Books
Minimum Moves to Rearrange Books
You are given a bookshelf with n sections, where each section is colored with a certain color represented by an integer. The goal is to rearrange the bookshelf so that all books of the same color appear in contiguous sections.
You can perform moves to adjust the arrangement. It turns out that the minimum number of moves needed is equal to the number of times the color changes between consecutive sections. In other words, if there are k contiguous blocks of identical colors, then the minimum moves required is \( k - 1 \).
For example, consider the bookshelf represented by the list [1, 2, 1, 2, 1]. Here, the color changes occur between sections 1→2, 2→1, 1→2, and 2→1, totaling 4 moves.
inputFormat
The input is given via standard input (stdin) and consists of two lines:
- The first line contains an integer n (1 ≤ n ≤ 105), which is the number of sections on the bookshelf.
- The second line contains n space-separated integers representing the color code for each section.
outputFormat
Print a single integer to standard output (stdout) which is the minimum number of moves required to rearrange the bookshelf so that all books of the same color are in contiguous blocks.
Recall that if there are k contiguous blocks of colors, then the answer is \( k - 1 \).
## sample5
1 2 1 2 1
4
</p>