Official

F - Chance Meeting Editorial by evima


Let us decrease \(H\) and \(W\) by \(1\) so that we have \(H\) vertical moves and \(W\) horizontal moves.

There are \(\binom{2H}{H}\) ways to move the two animals up and down, but they will be in the same row after \(H\) of those moves regardless of how we make them. Thus, the way we make vertical moves is unimportant, and we just need to consider the case they meet in the \(H\)-th row.

Let \(f(n)\) be the number of ways in which the two animals move right \(n\) times each and the camel moves down \(H\) times for them to meet for the first time on \((H,n)\). The answer is \(\binom{2H}{H} \sum_{i=0}^{W} f(i)f(W-i)\). Let us try to find \(f\).

Let \(g(n)\) be the number of ways in which the two animals move right \(n\) times each and the camel moves down \(H\) times for them to meet (not necessarily for the first time) on \((H,n)\). Then, we can represent it as \(g(n) = \binom{2n}{n} \binom{2n+H}{H}\). Thus, we have \(f(n) = g(n) - 2\sum_{i=0}^{n-1}g(i)C(n-i-1)\), where \(C(n)\) is the Catalan number.

Using FFT, we can find \(f\) in \(O(H+W \log W)\) time, which is fast enough.

posted:
last update: