Olympiad in Informatics

[Fortuna OJ] Mar 8th - Group A Problem-Solving Report

It's the last day of the spring training camp, and sure enough, the contest went to pieces too.

A - Coloring Game

How is this problem so godlike?

Let's first consider the number of ways within a single row. We can define a state: \(f[i][j]\) means that the first \(i\) elements contain \(j\) colors, and the formula is easy to derive:

\[ f[i][j] = f[i-1][j-1]*(p-(j-1))+f[i-1][j]*j \]

Since the number of columns is fixed, we only need to keep the values for \(i=m\), so we let \(g[i]=f[m][i]\), that is, the number of ways for a single row to have \(i\) colors. Next we think about designing a state to compute our answer: we can fix one row and then discuss the case of two rows placed together. So \(dp[i][k]\) means the number of ways for the first \(i\) rows, where the last row contains \(k\) colors.

\[ dp[i][k] = dp[i-1][j]+\frac{g[k]}{ { p \choose k }}*\sum_{ x = max\{ j,k,q \} }^{ min\{ p,j+k \} } { { j \choose j+k-x }*{ p-j \choose x-j } } \]

I know this formula is complicated, so let's explain it. First, the state \(dp[i][k]\) means we have reached row \(i\) and row \(i\) has \(k\) colors; we enumerate the previous row having \(j\) colors, so we transition from \(dp[i-1][j]\). Because here we enumerate the contribution of the color types to the answer separately, we have to cancel out the effect that the kinds of colors in \(g[i]\) have on \(g[i]\), to avoid double counting. Then we enumerate the two rows having \(x\) colors in total. Because \(j\) and \(k\) may overlap, we need to enumerate this separately, and the bounds of \(x\) are: \( [max\{ j,k,q \},min\{ p, j+k \}] \). After that comes the ever-popular separate enumeration of the two parts: \( { j \choose j+k-x } \) enumerates the part the two rows share, while \( { p-j \choose x-j } \) represents the part the two rows don't share. So, this way the answer can be counted.

Then the \(f[i]\) in this problem can be handled with fast matrix exponentiation, lowering the complexity further.