Official

A - +3 +5 +7 Editorial by evima


Hints → https://atcoder.jp/contests/arc158/editorial/5987


[1] Change the problem

In the problem, the values of \(x_1,x_2,x_3\) themselves do not quite matter; their differences do. Thus, the answer to the problem will not change if we may do the following at any time:

add a constant number \(c\) to each of \(x_1, x_2, x_3\).

Particularly, the answer will remain the same if \(c\) is added to the numbers each time we do the \((+3, +5, +7)\) operation.

For instance, if we let \(c=-1\), we may consider the problem with a \((+2,+4,+6)\) operation instead of \((+3, +5, +7)\); if we let \(c=-3\), we have a \((+0,+2,+4)\) operation.

Here, we let \(c=-5\) and consider the problem with a \((-2, 0, +2)\) operation. That is, we have the following operation:

add \(-2\) to one number and \(+2\) to another.


[2] The necessary condition

The \((-2, 0, +2)\) operation does not change \(x_1+x_2+x_3\). Thus, we can achieve \(x_1=x_2=x_3\) only if \(x_1+x_2+x_3\) is a multiple of \(3\).

Assume that it holds and let \(a = \dfrac{x_1+x_2+x_3}{3}\). Then, we need to make each \(x_i\) equal \(a\) by \(\pm 2\) operations, so it is necessary that \(x_i\) and \(a\) have the same parity.

Thus, we have the following necessary condition:

\(a = \dfrac{x_1+x_2+x_3}{3}\) is an integer, and \(a,x_1,x_2,x_3\) have the same parity.


[3] The sufficiency of the condition and the answer

Assume that the above necessary condition holds and let \(d = |x_1-a| + |x_2-a| + |x_3-a|\). We can verify the following.

  • [A] One operation changes \(d\) by at most \(4\).
  • [B] If \(d\neq 0\), it is always possible to decrease \(d\) by \(4\).

[A] can be seen from the fact that when \(x_i\) changes by \(\pm 2\), \(|x_i - a|\) does not decrease by more than \(2\).

[B] can be proved by considering the fact that when \(d\neq 0\), there are \(i\) and \(j\) such that \(x_i < a\) and \(x_j>a\), and adding \(+2\) to \(x_i\) and \(-2\) to \(x_j\) (note that \(|x_i-a|\geq 2\) if \(x_i\neq a\), since \(x_i\) and \(a\) have the same parity).

If the above necessary condition holds, [B] enables us to achieve the objective in \(\dfrac{d}{4}\) operations. Additionally, [A] shows that this is the minimum number of operations needed.


Properly implementing the above solves the problem in \(O(1)\) time per test case.

posted:
last update: