#K9276. Rearrange Blocks
Rearrange Blocks
Rearrange Blocks
You are given n blocks each with a certain height. Your task is to rearrange the blocks so that no two adjacent blocks have the same height.
If a valid rearrangement exists, output YES
on the first line and one valid rearrangement (i.e. the sequence of block heights) on the second line. Otherwise, output NO
.
The solution may involve greedy strategies using a max‐heap. In case of ties, the block with the smallest height (or any deterministic rule) can be chosen. Formally, if the frequency of the most frequent block exceeds \(\lceil \frac{n}{2} \rceil\), then a valid rearrangement is impossible.
The input and output are passed via standard input and output respectively.
inputFormat
The first line of input is an integer n
representing the number of blocks. The second line contains n
space-separated integers, which represent the heights of the blocks.
outputFormat
If a valid rearrangement exists, print YES
in the first line and then print the rearranged block heights separated by spaces in the second line. Otherwise, print NO
on a single line.
5
1 2 3 4 5
YES
1 2 3 4 5
</p>