Official

D - Coincidence Editorial by sumitacchan


Obviously, the following conditions are necessary.

  • (1) \(\sum_i A_i = \sum_i B_i = M\)
  • (2) \(\sum_i \min(A_i, B_i) \ge X\)

Let \(Y:=M-X\) be the number of operations such that \(i \ne j\) must hold. Considering the case \(X=0\), since each \(A_i+B_i\) increases at most by \(1\) per operation,

  • (3’) \(A_i+B_i \le Y\ \mathrm{for\ all}\ i\)

is also necessary. From Hall’s theorem, (1),(2),(3’) are also sufficient conditions.

If \(X>0\), the following condition is required instead.

  • (3) Condition (3’) can be satisfied by the following operations at most \(X\) times
    • Choose \(i\) and decrement \(A_i\) and \(B_i\) by \(1\)

(1), (2), and (3) above are necessary and sufficient conditions.

The answer to this problem can be obtained by finding the number of \(A,B\) satisfying (1) and (2), and that satisfying (1) and (2) but not (3), respectively. The former can be computed in \(O(NM)\) time by dividing the cases by the number of \(i\) such that \(A_i>B_i\) and the value of \(\sum_i \min(A_i, B_i)\). The latter is considered below.

Since \(|A_i-B_i| \le Y\) can be shown from (1) and (2), condition (3’) can always be made to satisfy if the restriction “operations at most \(X\) times” in (3) is ignored. Let us count the number of \(A,B\) for which we need more than \(X\) operations.

Let \(A',B'\) be the sequences after the minimum number of operations to satisfy (3’). The operation may have been performed with \(i\) if and only if \(A'_i+B'_i\) equals to \(Y-1\) or \(Y\). As \(\sum_i A'_i = \sum_i B'_i \le Y - 1\) holds since the operation was performed more than \(X\) times, we only have to consider the following \(3\) cases when \(Y \ge 2\) (\(Y=0,1\) may be corner cases).

  • There is just one \(i\) such that \(A'_i+B'_i=Y\), and for others \(A'_i+B'_i \le Y-2\)
  • There is just one \(i\) such that \(A'_i+B'_i=Y-1\), and for the others \(A'_i+B'_i \le Y-2\)
  • There are two \(i\)s such that \(A'_i+B'_i=Y-1\), and all others are \(0\)

We can count the original \(A,B\) that will become \(A',B'\) above after the operations, in \(O(M)\) time.

We can answer this problem in \(O(NM)\) time.

posted:
last update: