题目描述
Farmer John has purchased a lush new rectangular pasture composed of by 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.
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 andLines 2.. M+1: row describes each cell in row of the ranch, space-separated integers indicating whether the cell can be planted (1 means fertile and suitable for planting, 0 means barren and not suitable for planting).
输出描述:
Line 1: an integer: FJ total number of alternatives divided by a remainder of 100,000,000.
示例1
输入
2 3
1 1 1
0 1 0
输出
9
解答
题意:
给出一个行列的草地,1表示肥沃,0表示贫瘠,现在要把任意数量牛放在肥沃的草地上,但是要求所有牛不能相邻,问有多少种放法。题解:
状态压缩型dp,一般可以通过数据范围来判断,我们可以将每一行的肥沃草地状态与牛的分布状态用二进制数来表示出来,表示在第行牛的状态为的方法数,转移方法见代码,而且我们发现题上要求两个牛不能相邻,那么在二进制状态种有很多的状态都不满足这一性质,原本种状态经过预处理后发现实际上满足的限制的状态数很少,可以自己写个小程序算一下最多有多少种。代码:
#include<iostream> #include<algorithm> #include<stdio.h> using namespace std; int ans,n,m,dp[13][1<<13],map[13],st[1<<13]; int M=1e8; int judge1(int x)//判断此状态是否有相邻的牛 { return x&(x<<1); } int judge2(int i,int x)//判断此状态与地图是否冲突 { return map[i]&x; } int main() { scanf("%d%d",&n,&m); for (int i=1;i<=n;i++) for (int j=1;j<=m;j++) { int x; scanf("%d",&x); if (x==0) map[i]+=(1<<(j-1)); } int tot=0; for (int i=0;i<=(1<<m)-1;i++) if (!judge1(i)) { tot++; st[tot]=i; } for (int i=1;i<=tot;i++) { if (judge2(1,st[i])==0) dp[1][i]=1; } for (int i=2;i<=n;i++) { for (int j=1;j<=tot;j++) { if (judge2(i,st[j])) continue; for (int k=1;k<=tot;k++) { if (judge2(i-1,st[k])) continue; if ((st[j]&st[k])==0) { dp[i][j]+=dp[i-1][k]; dp[i][j]%=M; } } } } for (int i=1;i<=tot;i++) { ans+=dp[n][i]; ans%=M; } printf("%d\n",ans); }
来源:deritt