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.
Input
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)
Output
Line 1: One integer: the number of ways that FJ can choose the squares modulo 100,000,000.
Sample Input
2 3
1 1 1
0 1 0
Sample Output
9
Hint
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.
分析: 由于我是了解一些状态压缩的原理,所以这道题目的关键地方有两点
1 :如何快速判断一个状态中是否有相邻的位置种植
2 :如何判断一个状态是只在能够种植的地方上种植
解决方法问题一 :
相邻的情况一共有两种,一个是一行中的种植发生了相邻的情况 ,这种情况解决方案就是 (假设当前的状态为state)if(state&(state<<1)==1) 说明有相邻的种植。
另一种相邻的情况是 上一行与当前行发生相邻,这种情况很简单解决 if ((state[i]&state[i-1] )==1) 说明有相邻的位置。
解决方法问题二:
我们将每一行基本状态压缩为一个整数(1为0,0为1的压缩),这样的话如果这个状态和 我们将要种植的状态 有重叠 (即 if( cur[i] & state ==1) ) 那说明你的种植方案肯定有将不能够种植的地方给种植了 。
代码
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
#define LL long longconst int MAXN =15;
const int MAXM = 1e6;
const int mod = 100000000;int cur[MAXN+1]; LL dp[MAXN][1<<15];
int main(){int n,m;while(scanf("%d%d",&n,&m)!=EOF){memset(dp,0,sizeof(dp));for(int i=1;i<=n;i++){cur[i]=0;for(int j=1;j<=m;j++){int t; scanf("%d",&t);if(t==0) t=1;else t=0;cur[i]=(cur[i]*2+t); // 得到反向状态的 压缩整数}}// for(int i=1;i<=n;i++) printf("%d ",cur[i]);for(int j=0;j<(1<<m);j++) {if(j&(j<<1 )|| cur[1]&j ) continue; // 相邻的判断和是否能够种植的判断dp[1][j]=1;}for(int i=2;i<=n;i++){for(int j=0;j<(1<<m);j++){ // 遍历当前行的状态if((j&(j<<1)) || (cur[i]&j)) continue;for(int k=0;k<(1<<m);k++){ // 遍历上一行的状态if((k&(k<<1)) || (cur[i-1]&k) ) continue;if(j&k) continue; // 上一行是否与当前行发生相邻dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;}}}LL ans=0;for(int j=0;j<(1<<m);j++) { // 遍历最后一行所有状态的每个方案数if(j&(j<<1 )|| cur[n]&j ) continue;ans=(ans+dp[n][j])%mod;}printf("%lld\n",ans);}
return 0;
}