C - Error Swap Editorial by evima
When \(N = 2\), no matter how many operations you do, the array just alternates between \((A_1,A_2)\) and \((A_2-1,A_1+1)\). Hence, the task is possible if and only if \(B\) equals one of these two arrays. Below, assume \(N \ge 3\), and let \(M\) be the maximum of the numbers in \(A,B\).
The operation preserves \(\sum A\), so if \(\sum A \neq \sum B\), the task is impossible. Conversely, if \(\sum A = \sum B\), it is always possible to reach \(A = B\).
For \(2 \le x < y\), we can swap \(A_x\) and \(A_y\) by operations \((i,j) = (1,y),(1,x),(1,y)\). Similarly, we can also swap \(x<y\le N-1\). For \((x,y) = (1,N)\), we can swap by \((i,j) = (1,N),(1,2),(2,N),(1,2),(1,N)\).
With this swap, we can “increase \(A_x\) by \(1\) and decrease \(A_y\) by \(1\)” whenever \(A_x < B_x\) and \(A_y > B_y\): if \(x < y\), perform the operation \((i,j) = (x,y)\), then swap \(A_x\) and \(A_y\). A similar method works for \(x>y\).
Let \(D_i = A_i - B_i\). Performing the above adjustment \(S = \sum \max(D_i,0)\) times makes \(A = B\). We have \(S \le \frac{NM}{2}\), and each decrement of \(S\) costs four operations (three for the swap plus one more).
However, only for \((x,y) = (1,N),(N,1)\), the swap costs five operations, so each decrement of \(S\) costs six operations, but such a choice of \((x,y)\) happens at most \(\tfrac{M}{2}\) times, so the total number of operations is at most \(2NM + M\).
A straightforward implementation runs in \(\mathrm{O}(N^2M)\), which is fast enough.
Bonus: Achieve the goal in at most \(3500\) operations.
posted:
last update: