Official

E - 3 Letters Editorial by antontrygubO_o


Firstly, let’s convert \(A\), \(B\), \(C\) into \(0\), \(1\), \(2\).

Now, let’s represent any good string \(S\) of length \(N\) by an array \(A\) of length \(N\) such that:

  • $|A_{i+1} - A_i| = 1$ for $1 \le i \le n-1$
  • $A_i \equiv S_i \bmod 3$

Let’s call such arrays good too.

It’s easy to see that such array \(A\) is uniquely determined after choosing \(A_1\).

Now, the operation becomes choosing some \(i\) and changing \(A_i\) to \(A_i \pm 2\) so that the array remains good.

Now, consider \(2\) good arrays \(A_1, \dots, A_N\) and \(B_1, \dots, B_N\). What’s the smallest number of operations needed to get second from the first?

If \(A_1 \bmod 2 \neq B_1 \bmod 2\), it’s clearly impossible.

Else, we can prove that it’s \(\sum_{i = 1}^N \frac{|A_i - B_i|}{2}\).

Clearly, we need at least this many operations. Now, it’s enough to prove that it’s enough. For this, it’s enough to prove that for any \(2\) different arrays with \(A_1 \equiv B_1 \bmod 2\), there is an operation decreasing \(\sum_{i = 1}^N |A_i - B_i|\) by \(2\).

Suppose not. Suppose there is some \(i\) with \(A_i>B_i\) (similarly if there exists some \(i\) with \(A_i<B_i\)). Among all \(i\)-th for which \(A_i>B_i\), consider the one with the largest \(A_i\). I claim that we can reduce this \(A_i\) by \(2\), and the array will remain good.

For this, we have to prove that every neighbor of \(A_i\) is equal to \(A_i - 1\) if it exists. Suppose not, and (wlog) \(A_{i+1} = A_i + 1\). But then \(A_{i+1} = A_i + 1 > B_i + 1 \ge B_{i+1}\), so our choice of \(i\) was wrong.

After we proved this, it’s easy to solve the problem. We need to find the minimum sum of \(\sum_{i = 1}^N |A_i - B_i|\) over all choices of \(B_1\) satisfying \(B_1 \equiv A_1 \bmod 2\) and \(B_1 \equiv T_1 \bmod 3\). This can be done in \(O(n)\).

posted:
last update: