B - Rivalry Editorial by evima
First, \(X \ge 1\) is necessary. Focusing on a minimum value of \(A\), its two neighbors are clearly not smaller than it, so the minimum must be \(0\).
Consider the case \(X = 1\). The neighbors of a \(2\) must be \(0\) or \(1\). The neighbor of such a \(1\) (the other side) must be \(0\). Thus, if \(Z \ge 1\), we need \(Z = 1\) and \(Y \le 2\). These can actually be built, e.g. \((0,2)\), \((0,1,2)\), \((0,1,2,1)\). If \(Z = 0\), only \(Y = 0,2\) work, namely \((0)\) and \((0,1,1)\). Hence, for \(X = 1\), the necessary and sufficient condition is \(Y \le 2\), \(Z \le 1\), and \((Y,Z) \neq (1,0)\).
Consider general \(X\). Regard the sequence as \(X\) copies of the \(X = 1\) case concatenated. Thus, we require \(Y \le 2X\) and \(Z \le X\), but this is not yet sufficient: since \((Y,Z) = (1,0)\) does not work for \(X = 1\), the case “\(Y\) odd and \(Z = 0\)” must be excluded.
Summarizing, the necessary conditions for general \(X\) are \(X \ge 1\), \(Y \le 2X\), \(Z \le X\), and “\(Y\) is even or \(Z \ge 1\).” These conditions are also sufficient; we prove sufficiency by an explicit construction.
First, write \(X\) zeros. Then, insert twos into \(Z\) of the gaps between the zeros. If \(Y\) is odd (then \(Z \ge 1\)), pick one fragment \((0,2,0)\) and turn it into \((0,1,2,0)\) by inserting a one, making \(Y\) even. Then, apply the following operation \(\frac{Y}{2}\) times: \((0,0) \rightarrow (0,1,1,0),(0,2,0) \rightarrow (0,1,2,1,0)\). Since \(Y \le 2X\), this is always possible.
With this construction, each test case can be solved in \(\mathrm{O}(1)\) time.
posted:
last update: