---
id: 1766
lang: en
translation_of: index.md
source_sha256: 56520f8bd04c020e34b7c4c57d480facb4b5cd5352083e650713035ad3e7ac61
title: "Codeforces 1239A: Ivan the Fool and the Probability Theory — Solution"
description: "Fixing the first row and column determines the whole grid, so the count reduces to a DP on a strip, minus two invalid cases."
tags: ["OI","DP","Counting"]
translated: 2026-11-27
translator: Claude Opus 5.5
translator_model: claude-opus-5-5
translation_notes:
  - "是否连续 (whether it is consecutive) rendered as “whether the last position continues a run”."
---

## 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).

<!--more-->

## Code

```cpp
// 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;
}
```
