Official
A - A ↔ BB Editorial by evima
C
s do not change, so let us focus on a maximal segment consisting of A
s and B
s.
If we assign a weight of \(2\) to A
and a weight of \(1\) to B
, the operations do not change the total weight.
Now, let \(W\) be the total weight of a maximal segment consisting of A
s and B
s.
Then, the optimal move is as follows.
- If \(W\) is even: change it to \(W/2\) repetitions of
A
. - If \(W\) is odd: change it to \((W+1)/2\) repetitions of
A
followed by oneB
.
It can be easily seen that this is the lexicographically smallest possible under the fixed total weight.
Additionally, this is actually achievable (by temporarily changing all A
s to B
s and then changing them to A
s from left to right).
This solution works in \(O(N)\) time.
posted:
last update: