#K48097. Rearrangement of Stones
Rearrangement of Stones
Rearrangement of Stones
You are given an integer \(n\) and a string representing a sequence of stones. Each stone is denoted by a lowercase letter. The task is to rearrange the stones such that no two adjacent stones have the same letter.
If it is possible to rearrange the stones, output YES
on the first line and the rearranged sequence on the second line. If it is not possible, simply output NO
.
Note: The rearrangement (if possible) is not necessarily unique. You just need to produce one valid sequence.
The problem can be formally stated as follows:
Given an integer \(n\) and a string \(s\) of length \(n\), determine if there exists a permutation of \(s\) such that for every \(1 \le i < n\), \(s_i \neq s_{i+1}\). If such a permutation exists, print \(YES\) and the permutation; otherwise, print \(NO\).
The mathematical constraint for the possibility of rearrangement can be derived from the following inequality: \[ \max_{c \in \text{letters}} \text{count}(c) \le \left\lceil \frac{n}{2} \right\rceil \]
inputFormat
The input is read from stdin and consists of two lines:
- The first line contains an integer \(n\), the number of stones.
- The second line contains a string of length \(n\) representing the sequence of stones.
outputFormat
Output to stdout as follows:
- If a valid rearrangement exists:
- The first line should contain
YES
. - The second line should contain one valid rearranged sequence where no two consecutive stones are the same.
- If no valid rearrangement exists, output a single line containing
NO
.
1
a
YES
a
</p>