E - Fruit Lineup Editorial by Kiri8128


Let \(N = A + B + C + D\), and denote the binomial coefficient as \(\displaystyle \binom{n}{m}\).

The position \(i\) of the rightmost apple must satisfy \(\displaystyle A \le i \le A + B\). We need to choose \(A - 1\) positions for apples among the first \(i - 1\) elements (from the left), and \(C\) positions for bananas among the last \(N - i\) elements (from the right). There are \(\displaystyle \binom{i - 1}{A - 1} \times \binom{N - i}{C}\) such combinations.
Once these positions are fixed, the positions for oranges and grapes are uniquely determined.

Therefore, the answer is given by the sum:
\(\displaystyle \sum_{i = A}^{A + B} \binom{i - 1}{A - 1} \times \binom{N - i}{C}\).

By precomputing factorials, this can be solved in \(O(N)\) time.

AC Code (Python)

posted:
last update: