E - Fruit Lineup Editorial by en_translator
Let us focus on the leftmost grape.
Let us count how many ways are there to arrange the fruits to the left and right of the grape, when there are exactly \(i\) bananas \((0 \leq i \leq C)\) to the left of the leftmost grape.
(1) to the left of the leftmost grape
The fruits to the left of the leftmost grape are:
- \(A\) apples, \(B\) oranges, and \(i\) bananas.
Since an apple should come always to the left of a banana, the number of arrangements \((A+B+i)\) fruits turns out to be equal to:
- the number of ways to insert oranges to the sequence of \((A+i)\) apples and bananas.
Therefore, the sought count is:
\[\binom{A+B+i}{B}.\]
(2) to the right of the leftmost grape
The fruits to the right of the leftmost grape are:
- \((C-i)\) bananas and \((D-1)\) grapes.
We may arrange them in arbitrary order, so the sought count is:
\[\binom{D-1+C-i}{D-1}.\]
By (1) and (2), the number of ways to arrange fruits when there are exactly \(i\) bananas \((0 \leq i \leq C)\) to the left of the leftmost banana is:
\[\binom{A+B+i}{B}\binom{D-1+C-i}{D-1}.\]
The answer to the original problem is the sum of this value over \(i=0,1,\dots,C\), that is,
\[\sum_{i=0}^C \binom{A+B+i}{B}\binom{D-1+C-i}{D-1}.\]
This can be computed in \(\mathrm{O}(A+B+C+D)\) time after appropriate precalculation of factorials and their inverses. (The sample code is omitted.)
posted:
last update: