Official

C - ABS Ball Editorial by evima


Let \(k = \sum |a_i-b_i|\) and find the answer for each \(k\).

For the \(N\) balls, we keep \(k\) balls white for now, and treat the remaining \(N-k\) balls as \((N-k)/2\) pairs of one red ball and one blue ball.

First, we decide how to place the \((N-k)/2\) pairs of red and blue balls. The number of ways to do this can be found using simple binomial coefficients. For any placement, \(|a_i-b_i| = 0\) remains for all boxes \(i\).

Next, we decide how to place the white balls. Let \(x_i\) be the number of white balls to place in box \(i\).

Here, after placing the white balls, if we “paint all white balls in each box the same color, either red or blue”, then \(|a_i-b_i|=x_i\). Therefore, we find the sum of \(\prod x_i\) over all placements of white balls, and multiply by \(2^M\) to account for choosing which color to paint each box. (The sum of \(\prod x_i\) over all placements of white balls can be expressed using simple binomial coefficients.)

If we precompute binomial coefficients, we can find the answer for each \(k\) in \(O(1)\).

Here, after placing the white balls, if we “paint all white balls in each box the same color, either red or blue”, then \(|a_i-b_i|=x_i\). We consider finding the sum of \(\prod x_i\) over all placements of white balls. This value can be interpreted as “the number of ways to divide \(k\) white balls into \(M\) boxes, then choose one ball from each box (where which ball is chosen is distinguishable)”. We can think of this as arranging \(M-1\) box separators, \(M\) selected white balls, and \(k-M\) unchosen white balls. Since the chosen white balls and box separators must always alternate, we can identify them as \(2M-1\) separators without changing the count. In the end, the sought value is the number of ways to arrange \(k-M\) white balls and \(2M-1\) separators, which can be expressed as \(\binom {k + M - 1} {2M - 1}\).

Then, we multiply by \(2^M\) to account for choosing which color to paint the white balls in each box.

If we precompute binomial coefficients, we can find the answer for each \(k\) in \(O(1)\).

The overall time complexity is \(O(N)\).

posted:
last update: