Official

E - Adjacent Sums (hard) Editorial by en_translator


Original proposer: admin

Let \((A'_1,A'_2,\dots,A'_N)\) be the resulting \(A\).
Define \(C\) as \(C_1=0\) and \(C_{i+1} = B_i-C_i\).
Let \(D_i=C_i-A_i\).
If we let \(s=A'_1 \pmod M\), it satisfies \(A'_i \equiv C_i+(-1)^{(i+1)}s \pmod M\), so the number of operations required is \(\sum_{i=1}^{N}{((D_i+(-1)^{(i+1)}s) \pmod M)}\).
It suffices to find the minimum value for this.
In fact, it is sufficient to consider \(s\) such that \((D_i+(-1)^{(i+1)}s) \pmod M\) is \(0\) for some \(i\) (proof later).
Enumerate such \(s(0 \leq s \lt M)\), and find \(\sum_{i=1}^{N}{(D_i+(-1)^{(i+1)}s) \pmod M}\) using differential updates. When \(s\) increases by \(1\), \((D_i+(-1)^{(i+1)}s) \pmod M\) increases by one if \(i\) is odd, and decreases by one if \(i\) is even, in most cases.
The exception occurs on transitions between \(0\) and \((M-1)\), which occurs only \(N\) times.
By memorizing the exceptional moments and performing differential updates, the answer can be found. The total time complexity is \(O(N\log N)\), where sorting the enumerated \(s\) is the bottleneck.

Proof that it is sufficient to consider \(s\) such that \((D_i+(-1)^{(i+1)}s) \pmod M\) is \(0\) for some \(i\).

Among those \(s\) minimizing \(\sum_{i=1}^{N}{(D_i+(-1)^{(i+1)}s) \pmod M}\), take one \(s'\) that minimizes \(\min{((D_i+(-1)^{(i+1)}s) \pmod M)}\). Assume \(D_i+(-1)^{(i+1)}s \not\equiv 0 \pmod M\) for all \(i\).
Taking \(s'+1 \pmod M\) or \(s'-1 \pmod M\) affects in one of the following way:

  • \(\sum_{i=1}^{N}{(D_i+(-1)^{(i+1)}s) \pmod M}\) becomes smaller.
  • \(\sum_{i=1}^{N}{(D_i+(-1)^{(i+1)}s) \pmod M}\) is invariant, but \(\min{((D_i+(-1)^{(i+1)}s) \pmod M)}\) becomes smaller.

Therefore, it has been proved by contradiction.

posted:
last update: