Official

C - Roller Editorial by evima


Below, let us call the operation of replacing \(A_k\) with \(A_{k+1}\) operation \(k\).

Consider the case \(A=(1,2,\dots,N)\). We can make \((1,2,\dots,N)\) in zero operations. Below, assume that we perform at least one operation.

After one operation, \(A\) has \(N-1\) different integers, and this number will not increase. Thus, any sequence that can be yielded has \(N-1\) or fewer different integers.

Additionally, the operation keeps this property of the sequence: there is an integer \(i\) such that \(A_i \le A_{i+1} \le ... \le A_N \le A_1 \le ... \le A_{i-2} \le A_{i-1}\). Thus, this is also a necessary condition for a sequence to be yieldable.

These conditions turn out to be necessary and sufficient.

To show that, let us first solve the following property.

  • When one or more operations have been performed, one can shift \(A\) to the left.
Proof Since there is an integer $i$ such that $A_i \le A_{i+1} \le ... \le A_N \le A_1 \le ... \le A_{i-2} \le A_{i-1}$, and $A$ has at most $N-1$ different integers, one may take an integer $k$ such that $A_k = A_{k+1}$. (Here, regard $A_{N+1}=A_1$.) Then, performing operations $k+1,k+2,\dots,N,1,\dots,k-1,k$ in this order shifts $A$ to the left.

Thus, \(A\) can be seen as \(Y_1\) copies of \(X_1\), \(Y_2\) copies of \(X_2\), \(\dots\), and \(Y_k\) copies of \(X_k\), arranged in this order. \((X_1 < X_2 < \dots < X_k,\sum_{i=1}^{k} Y_i = N.)\) For instance, when \(A=(1,1,3,4)\), we have \(X=(1,3,4),Y=(2,1,1)\). When \(A=(1,3,3,6,1,1)\), we have \(X=(1,3,6),Y=(3,2,1)\).

Here, by performing the operation at the border between \(X_i\) and \(X_{i+1}\), one can decrease \(Y_i\) by \(1\) and increase \(Y_{i+1}\) by \(1\), so all \(Y\) of this form can be yielded. This, in addition to the above property, proves the necessity and sufficiency of the conditions.

Now, let us solve the problem with the general \(A\). First, if \(A=B\), the answer is Yes. If not, and the length of \(B\) after compression is \(N\), then No.

If neither of the above holds, let us check whether the following holds for the \(N\) sequences \(C\) that are rotations of \(B\). If it holds for one of them, the answer is Yes.

  • There is a non-decreasing integer sequence \(x_1 \le x_2 \le \dots \le x_{N-1} \le x_N\) that satisfies \(C_i = A_{x_i}\).

This can be checked greedily in \(\mathrm{O}(N)\) time, so one can naively check it for all \(C\) to solve the problem in \(\mathrm{O}(N^2)\) time.

posted:
last update: