Official

E - White and Black Balls Editorial by en_translator


If we regard putting a black ball as “advancing in the direction of \(x\) axis by \(1\)” and putting a white ball as “advancing in the direction of \(y\) axis by \(1\),” then each permutation of \(M\) black balls and \(N\) white balls corresponds to a path from \((0, 0)\) and \((M, N)\).

How can we rephrase the condition \(w_i \leq b_i + K\)? A path passes through a point \((x, y)\) if and only if the first \((x + y)\) balls of the corresponding permutation has \(x\) black ones and \(y\) white ones. Therefore, the condition is equivalent to “the path is included in a region represented by \(y \leq x + K\).”

When \(N = 5, M = 6, K = 2\), the path corresponding to the permutation bwwwbbwbbbw is illustrated below:

image0

Obviously, the answer is \(0\) if \(N > M + K\). Hereinafter we assume \(N \leq M + K\).

Without the constraints \(y \leq x + K\), the total number of paths is \(\binom{N + M}{N}\). We now consider eliminating the total number of paths that does not satisfy the condition.

Every path violating the condition has one or more common points with a line \(y = x + K + 1\). Among them, let us focus the one with the smallest \(x\) coordinates, and consider the mirror image of the path from the origin to this point with respect to the line \(y = x + K + 1\). Then we obtain a path from \((-K-1, K + 1)\) to \((M, N)\). Conversely, every path from \((-K-1, K + 1)\) to \((M, N)\) has one or more common point with the line \(y = x + K + 1\), because its initial point of the path is above the line, while the terminal below, so again we can consider a mirror image to obtain a path from \((0, 0)\) to \((M, N)\) such that it has a common points with the region \(y > x + K\).

image1

Therefore, every path that does not satisfy the constraints corresponds one by one with a path from \((-K-1, K + 1)\) and \((M, N)\), and their total number is \(\binom{N + M}{M + K + 1}\) (where we define \(\binom{n}{r} = 0\) for \(n < r\)).

Be careful not to forget to check if \(N \leq M + K\).

Sample code (C++)

posted:
last update: