Official

C - Permutation Addition Editorial by evima


Let \(S\) be the sum of the initial elements of \(A\). When all elements become equal, this sum will be a multiple of \(N\). One operation increases their values by \(1+2+\ldots+N = \frac{N(N+1)}{2}\) in total, so in order to make them all equal, it is necessary that one of \(S, S+\frac{N(N+1)}{2}, S+2\frac{N(N+1)}{2}, \ldots\) is a multiple of \(N\). Particularly, \(2\frac{N(N+1)}{2}\) is a multiple of \(N\), so \(S\) or \(S+\frac{N(N+1)}{2}\) has to be a multiple of \(N\).

On the other hand, if the above condition is satisfied, one can always make all elements of \(A\) equal.
Performing the operation with the permutation \((1,2,3, \ldots,N)\) and then with \((N,N-1,N-2, \ldots,1)\) increases every value in \(A\) by \(N+1\). Here, if we replace the second permutation with \((N-1, N, N-2, \ldots,1)\), \(a_1\) increases by \(N\), \(a_2\) increases by \(N+2\), and each of \(a_3,a_4,\ldots,a_N\) increases by \(N+1\). We may subtract a constant number from every element without affecting the equality, so let us subtract \(N+1\) from every value for simplicity, and now \(a_1\) gets \(-1\) and \(a_2\) gets \(+1\). In this way, we may add \(+1\) and \(-1\) to two arbitrary elements.
Let us perform at most one operation so that the sum of the elements of \(A\) is a multiple of \(N\). Now, let \(x\) be the average value. If \(A\) contains a value that is not \(x\), let us repeat adding \(+1\) and \(-1\) to a value greater than \(x\) and a value less than \(x\). This operation does not change the sum, and if there is a value that is not \(x\), there are a value greater than \(x\) and a value less than \(x\) (or the sum would not be \(x \times N\)), so this process always achieves the objective in a finite number of operations.

Let us evaluate the number of operations. After performing the operation at most once, the values of \(A\) are at most \(100\), so the average value is also at most \(100\). For each value, we need at most \(100\) additions of \(+1\) or \(-1\) to match it to the average, so by simply multiplying this number by \(N\) (at most \(50\)), we need at most \(5000\) operations, which is well within the limit of \(10^4\) operations.

posted:
last update: