Official

A - Reversi 2 Editorial by evima


No matter how you perform the operations, the number written in cell \(1\) will always remain \(1\). Therefore, if \(A_1 = 0\), the answer is \(0\). From now on, assume \(A_1 = 1\). Let the number written in cell \(i\) be \(X_i\).

Define a sequence \(Y\) of length \(N-1\) by \(Y_i = (X_i + X_{i+1}) \bmod 2\). Initially, \(Y\) is a sequence of all \(1\)s. The operation described in the problem, selecting \(l, r\) that satisfy the conditions and changing \(X\), can be reinterpreted as choosing a subsequence of \(Y\) that is \((1, 0, 0, \dots, 0, 1)\) and replace both ends (the \(1\)s) with \(0\). Our goal is to transform \(Y\) into another sequence \(B\) of length \(N-1\) defined by \(B_i = (A_i + A_{i+1}) \bmod 2\).

First, consider the case where \(B = (0,0,\dots,0)\). If \(N-1\) is odd, the answer is \(0\). Otherwise, initially we can only perform an operation on any of the \((N-2)\) pairs of adjacent terms of \(Y\). After performing one such operation, we can consider those two terms as removed from the sequence, reducing the problem by length \(2\). Therefore, the answer in this case is \((N-2)!! = (N-2) \times (N-4) \times \cdots \times 3 \times 1\).

Next, consider the general case where \(B\) may have multiple maximal contiguous subsequences consisting only of \(0\)s. Operations on different zero-only subsequences do not interfere with each other. Thus, if there is any zero-only subsequence of odd length, the answer is \(0\). If all such zero-only subsequences have even length, let these lengths be \(x_1, x_2, \dots, x_k\). Each such subsequence of length \(x_i\) can be resolved with \(\frac{x_i}{2}\) operations. The number of ways to interleave these operations among the different subsequences is \(\frac{\left(\sum_{i=1}^{k} \frac{x_i}{2}\right)!}{\prod_{i=1}^{k} \left(\frac{x_i}{2}\right)!}\), and for these subsequences, there are \(\prod_{i=1}^{k} (x_i - 2)!!\) ways to perform the operations internally. Multiplying these together gives the final answer. This can be computed in \(O(N)\) time.

posted:
last update: