公式

C - All Add or Single Negate 解説 by evima 印刷ページ


Suppose we fix the number \(s\) of operations that add \(1\) to all elements. Then, the minimum number of operations can be computed as a minimum-weight perfect matching in a bipartite graph.

Specifically, when we want to match \(A_i\) with \(B_j\), the number of sign-flip operations to be applied to \(A_i\) can be computed as follows.

  • If \(A_i+s \not\equiv B_j \pmod{2}\): by parity, it is impossible to match \(A_i\) with \(B_j\).
  • If \(||A_i|-|B_j|| > s\): consider how the value \(||A_i|-|B_j||\) changes with the operations. It does not change with a sign flip. It decreases by at most \(1\) with one addition to all elements. Thus, it is impossible to match \(A_i\) with \(B_j\).
  • If \(B_j-A_i=s\): clearly, \(0\) sign flips suffice.
  • If \(-s \leq B_j - (-A_i) \leq s\): let \(k=B_j-(-A_i)\). Then, performing \((s-k)/2\) additions to all elements, a sign flip of \(A_i\), and \((s+k)/2\) additions to all elements makes \(A_i\) equal to \(B_j\). Thus, the required number of sign flips is \(1\).
  • Otherwise: \(A_i\) cannot be made equal to \(B_j\) with one sign flip, but it is always possible with two. Specifically, if we first flip the sign to replace \(A_i\) with \(-A_i\), we can see that the condition for reaching \(B_j\) with one sign flip is satisfied.

What remains is to estimate the number \(s\) of additions to all elements. First, let us find the minimum value \(smin\) of \(s\) for which a perfect matching exists. This can be done by trying both parities of \(smin\), classifying \(A_i,B_j\) by parity, sorting \(|A_i|,|B_j|\), and matching them greedily.

Here, noting that the cost of each edge of the matching is at most \(2\), we can take \(smin+2N\) as an upper bound for the answer.

Therefore, it suffices to try the \(O(N)\) candidates \(s=smin,smin+1,\cdots,smin+2N\).

Computing a minimum-weight perfect matching with the Hungarian algorithm takes \(O(N^3)\) time. Thus, the problem can be solved by an \(O(N^4)\)-time algorithm in total.

Sample Solution (C++)

投稿日時:
最終更新: