Olympiad in Informatics

Codeforces 1239A: Ivan the Fool and the Probability Theory — Solution

Main Idea

First, we need one property: once the first row and the first column are fixed, the whole configuration is completely determined. This can be proved by induction:

Proof If the colors of cells \((i - 1, j)\), \((i, j - 1)\) and \((i - 1, j - 1)\) are fixed, then clearly the color of \((i, j)\) is uniquely determined. If the first row and the first column can be fixed, then by the above, a unique configuration is generated.

So to count the configurations, we need to count the valid ways to fill the first row and the first column. This turns the problem into one on a strip.

Let \(dp[i][0/1][0/1]\) describe the first \(i\) positions: whether the last position continues a run, and the digit filled in last. The transitions are very natural, so you can derive them yourself (they really are).

The final answer is the sum of all the cases, minus the two invalid ones (that is, the cases where the three top-left cells share a color).

Code

// CF1239A.cpp
#include <bits/stdc++.h>

using namespace std;

const int mod = 1e9 + 7, MAX_N = 1e5 + 200;

int n, m, dp[MAX_N][2][2];

int main()
{
    scanf("%d%d", &n, &m);
    dp[1][1][0] = dp[1][0][0] = 1;
    for (int i = 2; i <= max(n, m); i++)
    {
        // white settings;
        // both white;
        dp[i][0][1] = dp[i - 1][0][0];
        // the prev one is black or double black;
        dp[i][0][0] = (1LL * dp[i - 1][1][0] + 1LL * dp[i - 1][1][1]) % mod;
        // black settings;
        // both black;
        dp[i][1][1] = dp[i - 1][1][0];
        // double or single;
        dp[i][1][0] = (1LL * dp[i - 1][0][0] + 1LL * dp[i - 1][0][1]) % mod;
    }
    int ans = 0;
    for (int i = 0; i <= 1; i++)
        for (int j = 0; j <= 1; j++)
            ans = (1LL * ans + 1LL * dp[n][i][j] + 1LL * dp[m][i][j]) % mod;
    ans -= 2;
    while (ans < 0)
        ans += mod;
    ans %= mod;
    printf("%d", ans);
    return 0;
}

Comments 4

  1. wgw

    我不太懂为什么要减二呢,刚开始
    0 0 1 1
    0 1
    这样,后面还是由这个推出来的,我怎么感觉不仅对答案共享了2

    1. wgw

      0 0
      0
      1 1
      1

  2. wgw

    0 0
    0
    1 1
    1

  3. wgw

    我懂了,当我没说