原题链接
Recently Ivan the Fool decided to become smarter and study the probability theory. He thinks that he understands the subject fairly well, and so he began to behave like he already got PhD in that area.
To prove his skills, Ivan decided to demonstrate his friends a concept of random picture. A picture is a field of n rows and m columns, where each cell is either black or white. Ivan calls the picture random if for every cell it has at most one adjacent cell of the same color. Two cells are considered adjacent if they share a side.
Ivan’s brothers spent some time trying to explain that it’s not how the randomness usually works. Trying to convince Ivan, they want to count the number of different random (according to Ivan) pictures. Two pictures are considered different if at least one cell on those two picture is colored differently. Since the number of such pictures may be quite large, print it modulo 109+7.
Input
The only line contains two integers n and m (1≤n,m≤100000), the number of rows and the number of columns of the field.
Output
Print one integer, the number of random pictures modulo 109+7.
Example
inputCopy
2 3
outputCopy
8
Note
The picture below shows all possible random pictures of size 2 by 3.
题意
给定一个 n×m 的方格图,每个格子可以被染成黑色或白色,且与其相邻的格子(上,下,左,右)中至多只有一个与其颜色相同。求方案数。
思路(DP)
1.先看一维横向,最多只能是两种颜色连在一起,然后递推,可以得出f[i]=f[-1]+f[i-2]
2.然后考虑一维纵向,可以发现纵向是由横向的决定的,把横向的看成一个整体,然后纵向只能是和上一行相同或者是相反,可以发现,也是一样的规律
3.但是还有不合法的情况要减去,比如上一行是110011,那么下一行只能放置不同的,不能放置相同的,下一行只能放置001100,不可以放置110011
AC代码
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int mod=1e9+7;
const int N=1e5+5;
ll n,m;
ll f[N];
int main(){
f[1]=2;
f[2]=4;
for(int i=3;i<N;i++){
f[i]=(f[i-1]+f[i-2])%mod;
}
cin>>n>>m;
ll res=(f[n]+f[m]-2)%mod;
cout<<res<<endl;
return 0;
}