描述
Farmer John has purchased a lush new rectangular pasture composed of M by N (1 M 12; 1 N 12) square parcels. He wants to grow some yummy corn for the cows on a number of squares. Regrettably, some of the squares are infertile and can't be planted. Canny FJ knows that the cows dislike eating close to each other, so when choosing which squares to plant, he avoids choosing squares that are adjacent; no two chosen squares share an edge. He has not yet made the final choice as to which squares to plant.
Being a very open-minded man, Farmer John wants to consider all possible options for how to choose the squares for planting. He is so open-minded that he considers choosing no squares as a valid option! Please help Farmer John determine the number of ways he can choose the squares to plant.
输入
Line 1: Two space-separated integers: M and N
Lines 2..M+1: Line i+1 describes row i of the pasture with N space-separated integers indicating whether a square is fertile (1 for fertile, 0 for infertile)
输出
Line 1: One integer: the number of ways that FJ can choose the squares modulo 100,000,000.
样例输入
2 3
1 1 1
0 1 0
样例输出
9
提示
Number the squares as follows:
1 2 3
4 There are four ways to plant only on one squares (1, 2, 3, or 4), three ways to plant on two squares (13, 14, or 34), 1 way to plant on three squares (134), and one way to plant on no squares. 4+3+1+1=9.
题意
一块 M*N 的田用于养牛, 1 代表可以养牛, 要求每头牛上下左右没有其他牛, 问你方案数模 1e9
题解
状压 dp 经典题, 这里用样例解释
首先把列压成 01 串状态, 1 表示有牛, 0 表示无牛, 那么总共有 [000,111] 总状态, 000,001,010,011,100,101,110,111
dp[i][j]代表第 i 行可行状态 j 的方案总数, 可行状态 j 的意思是没有两个连续的 1, 所以 011 和 110 和 111 去掉
state[i]代表可行的状态, 所以只有 000,001,010,100,101 五种状态, 此时所有可行状态数 tot=5
cur[i]代表样例行的状态取反, 取反是为了判断当前行枚举的五种状态是否可行, 例如第二行题目是 010, 取反后是 101, 也就是说只有 000,010 两种状态可行
状态转移方程
if j[1,tot],state[j]&cur[i]=0,k[1,tot],state[k]&cur[i-1]=0,state[j]&state[k]=0
dp[i][j]=dp[i][j]+dp[i-1][k]表示当前行 i 状态 j 可由前一行 i-1 状态 k 转移过来
- else
- dp[i][j]=dp[i][j];
代码
- #include<stdio.h>
- #include<string.h>
- using namespace std;
- const int mod=1e9;
- int dp[15][1500],state[1500],cur[15];
- int n,m,k,tot;
- int main()
- {
- while(scanf("%d%d",&m,&n)!=EOF)
- {
- tot=0;
- for(int i=0;i<(1<<n);i++)/// 列的所有可行状态
- if(!(i&(i<<1)))/// 没有连续两个 1
- state[++tot]=i;
- for(int i=1;i<=m;i++)
- for(int j=1;j<=n;j++)
- {
- scanf("%d",&k);
- if(!k)cur[i]+=1<<(n-j);/// 第 i 行不可行置 1, 用于判断不可行状态
- }
- for(int i=1;i<=tot;i++)
- if(!(state[i]&cur[1]))
- dp[1][i]=1;
- for(int i=2;i<=m;i++)
- {
- for(int j=1;j<=tot;j++)/// 枚举当前状态
- {
- if(state[j]&cur[i])continue;/// 当前状态不可行
- for(int k=1;k<=tot;k++)/// 枚举前一个状态
- {
- if(state[k]&cur[i-1])continue;/// 当前前一状态不可行
- if(state[j]&state[k])continue;/// 当前状态和前一状态不可行
- dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;/// 当前状态可以从前一状态的 K 状态转移过来
- }
- }
- }
- int ans=0;
- for(int i=1;i<=tot;i++)
- ans=(ans+dp[m][i])%mod;
- printf("%d\n",ans);
- }
- return 0;
- }
来源: http://www.bubuko.com/infodetail-2687088.html