CSES - Counting Tilings

Author: Andi Qu

Time Complexity: O(NM2N)\mathcal O(NM2^N).

Let dp[i][j][mask]\texttt{dp}[i][j][mask] be the number of ways to tile the grid so that:

  • All cells from cell (0,0)(0, 0) to cell (i1,j)(i - 1, j) are covered.
  • All cells from cell (i,j+1)(i, j + 1) to cell (N,M)(N, M) are empty.
  • maskmask represents whether each of the remaining NN cells are empty, with the kk-th bit corresponding to the cell in column kk.

For example, the following state would contribute toward dp[4][2][101012]\texttt{dp}[4][2][10101_2]: state example

We now have two cases when calculating dp[i][j][mask]\texttt{dp}[i][j][mask]:

  • The jj-th bit of mask is 0, meaning that cell (i,j)(i, j) is covered.
    • Case 1: we used a vertical tile to cover it.
      • Cell (i1,j)(i - 1, j) must have been empty before this, so there are dp[i1][j][mask2j]\texttt{dp}[i - 1][j][mask \oplus 2^j] ways to do this.
    • Case 2: we used a horizontal tile to cover it.
      • This is only possible if j>1j > 1.
      • Cell (i,j1)(i, j - 1) must have been empty before this, while cells (i1,j1)(i - 1, j - 1) and (i1,j)(i - 1, j) must have been covered, so there are dp[i][j2][mask]\texttt{dp}[i][j - 2][mask] to do this.
  • The jj-th bit of the mask is 1, meaning that cell (i,j)(i, j) is empty.
    • Cell (i1,j)(i - 1, j) must have been covered before this, so there are dp[i1][j][mask2j]\texttt{dp}[i - 1][j][mask \oplus 2^j] ways to do this.

Note that the indices we need to use may become negative and will thus require wrapping. To simplify calculations and bypass this, simply drop the first two dimensions of the DP array, as dp[i][j]\texttt{dp}[i][j] depends only on dp[i][j1]\texttt{dp}[i][j - 1] and dp[i][j2]\texttt{dp}[i][j - 2].

C++

#include <bits/stdc++.h>
typedef long long ll;
using namespace std;
const ll MOD = 1e9 + 7;
ll dp[1 << 10][3];
int main() {
cin.tie(0)->sync_with_stdio(0);

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!