Official

A - My Last ABC Problem Editorial by antontrygubO_o


Let’s see how to find the answer for a single string \(S\).

Let’s consider \(S\) as a cyclic string (that is, the first character is adjacent to the last one). Note that we can apply our operation to any segment of this cyclic string (doing an operation with some permutation on a segment is equivalent to doing the same operation with an inverse permutation on the complement).

Let \(k\) denote the number of pairs of adjacent characters which are different. In the end, no such pairs should exist, so \(k\) should be \(0\). On the other hand, in one operation, we can reduce \(k\) by at most \(2\), as a pair may disappear only if one character from it is inside the interval to which we apply the operation and the other one is outside. So, the answer is at least \(\lceil \frac{k}{2} \rceil\).

It turns out that we can always make all characters equal in at most this many operations. Let’s show that when \(k \ge 4\), then we can always reduce the number of such pairs by \(2\) in a single operation. Consider all these \(k\) pairs, choose some \(2\) which contain equal set of characters (there are only three possible sets of characters: AB, BC, CA). Wlog there are two pairs with set of characters AB. Then, choose a segment, which contains exactly one character from each of these pairs, and apply the permutation \((X, Y, Z) = \)B, A, C. These pairs would disappear.

For the case \(k = 3\), after we delete all equal elements, we are left with just the string ABC. We can turn it into AAA in \(2\) operations. For the case \(k = 2\), we are left with just AB, which we can turn into AA in a single operation; \(k = 1\) is impossible.

posted:
last update: