Description
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
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
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
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.
#include<iostream>
#include<cstdio>
#include<string>
#include<vector>
#include<cstring>
using namespace std;
int n,m;
int dp[13][2048];//记录第i行的第j个状态所对应的方案总数
vector<int> num[13];//记录每一行的状态
void getstatus(int i,int temp) //求第i行所有可行的状态
{
int j;
for(j=0;j<(1<<m);j++)//枚举所有的状态
{
if((j<<1)&j || (j>>1)&j)//如果状态j有两个或以上相邻的1,忽略
continue;
if(j&temp) //如果状态j和temp(草地一行的情况)相与不为0,
//说明在没有种植玉米的地方放牛了,不可行,忽略
//temp表示草地一行的情况,注意:0表示可以放牛,1表示不可以
continue;
num[i].push_back(j); //可行的状态,放入数组num[i][j]中
}
}
int main()
{
int i,j,temp,a,k;
//freopen("3254.in","r",stdin);
while(scanf("%d%d",&n,&m)!=EOF)
{
for(i=1;i<=n;i++)
{
num[i].clear();
temp=0;//存放草地的一行
for(j=1;j<=m;j++) //将草地的一行转变为二进制数,并将草地的数据进行了求反
{ //即1表示不能放牛,0表示能够放牛
scanf("%d",&a);//便于判断某个状态对于草地的一行来说是否可行
a=1-a;//取反,因为输入的是0或1
temp=temp*2+a;//以二进制形式存储
}
getstatus(i,temp);
}
memset(dp,0,sizeof(dp));
for(i=0;i<num[1].size();i++)
{
dp[1][i]=1;
}
for(i=2;i<=n;i++)
{
for(j=0;j<num[i].size();j++)//第i行的每个状态
{
for(k=0;k<num[i-1].size();k++)//i-1行的每个状态
{
if((num[i][j])&(num[i-1][k]))
continue;
dp[i][j]+=dp[i-1][k];
}
}
}
int ans=0;
for(i=0;i<num[n].size();i++)
{
ans=(ans+dp[n][i])%100000000;
}
printf("%d\n",ans);
}
return 0;
}