Official

A - Reverse A…B Editorial by evima


First, we define the notation used in this editorial.

  • When string \(S\) is lexicographically less than or equal to \(T\), we write \(S\leq T\).
  • The string obtained by reversing the entire string \(S\) is written as \(\mathrm{rev}(S)\).
  • The substring of \(S\) consisting of the \(l\)-th through \(r\)-th characters is written as \(S[l:r]\).

The necessary and sufficient condition for being able to transform \(X\) into \(Y\) is as follows:

  • The numbers of As in \(X\) and \(Y\) are equal.
  • \(X\leq Y\)
  • \(\mathrm{rev}(Y)\leq \mathrm{rev}(X)\)

It is clear that these conditions are necessary. We show they are sufficient by presenting an actual construction.

Consider the case where \(X_1, X_N, Y_1, Y_N\) are A, B, B, A respectively, and \(X\) and \(Y\) contain the same number of As.

We require that the operation \((l, r) = (1, N)\) is performed at some point. Let \(\mathrm{op\_front}\) denote the operations before this, and \(\mathrm{op\_back}\) denote the operations after.

Here, we regard \(\mathrm{op\_back}\) as operations applied to \(Y\). Viewing \(\mathrm{op\_back}\) in reverse order, it corresponds to:

  • For \((l, r)\) such that \(Y_l, Y_r\) are B, A, reverse \(Y[l:r]\).

Let \(X'\) be the string obtained by applying \(\mathrm{op\_front}\) and \((1,N)\) to \(X\) in this order, and let \(Y'\) be the string obtained by applying \(\mathrm{op\_back}\) to \(Y\) in reverse order. Then \(X'=Y'\).

Let \(S\) be \(X[2:N-1]\) and \(T\) be the reversal of \(Y[2:N-1]\). The problem is then equivalent to the following:

  • Perform the following operations a total of at most \(\frac{N-2}{2}\) times to make \(S=T\).
    1. Choose \((l,r)\ (1\leq l\lt r\leq N-2)\) such that \(S_l, S_r\) are A, B, and reverse \(S[l:r]\).
    2. Choose \((l,r)\ (1\leq l\lt r\leq N-2)\) such that \(T_l, T_r\) are A, B, and reverse \(T[l:r]\).

The sequence of type-\(1\) operations in order of application corresponds to \(\mathrm{op\_front}\), and the sequence of type-\(2\) operations in reverse order of application corresponds to \(\mathrm{op\_back}\).

Consider the above problem. Suppose the number of As in \(S\) is less than the number of Bs. Let \(p, q\) be the sequences of positions of A in \(S, T\) listed in ascending order. By performing the following for \(i = |p|, |p|-1, \dots, 1\) in this order, we can make \(S=T\):

  • If \(p_i=q_i\): do nothing.
  • If \(p_i\lt q_i\): reverse \(S[l:r]\) with \(l=p[i], r=q[i]\).
  • If \(p_i\gt q_i\): reverse \(T[l:r]\) with \(l=q[i], r=p[i]\).

Since \(|p|\leq \frac{N-2}{2}\), the number of operations is at most \(\frac{N-2}{2}\). The case where B is more frequent can be handled similarly in at most \(\frac{N-2}{2}\) operations.

posted:
last update: