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.
题意:在一片M行N列的草地上(用0和1矩阵表示),1表示能放牛,0表示不能放。在草地上放牛并且牛不能相邻,问有多少种放法(一头牛都不放也算一种)。
每一行放的方法可能很多,可以不放,可以放1个,等等,只要是不相邻都是可以的,这样的情况每一行的状态就可能很多,这里用状态压缩,把每一行的可行状态用一个二进制数来表示,那么dp[i][j]表示在第i行时状态为j的总的方案个数,这个状态j要求是不和上一行状态k相邻,那么dp[i][j]=dp[i][j]+dp[i-1][k].
最后总的方案数就是 ans=Sigma dp[n-1][i](行从0开始)
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
#define mod 100000000
int n,m,dp[13][1<<12],row[15],tot,states[1<<12];
void init() //筛选符合要求的状态(不能相邻)
{
tot=0;
int cnt=1<<m; //总状态数
for (int i=0; i<cnt; i++)
{
if ((i&i<<1)==0)
states[tot++]=i; //保存符合要求的状态
}
}
int main()
{
int temp,ans;
while (scanf("%d%d",&n,&m)!=EOF)
{
ans=0;
for (int i=0; i<n; i++)
{
row[i]=0;
for (int j=0; j<m; j++)
{
scanf("%d",&temp);
row[i]+=temp<<j; //而二进制方式保存每一行的状态
}
}
init();
memset(dp, 0, sizeof(dp));
for (int i=0; i<tot; i++)
{
if ((row[0] & states[i])==states[i]) //设置dp数组第一行(从0开始)的符合要求的状态初始值
dp[0][i]=1;
}
for (int i=1; i<n; i++) //对第i行处理
{
for (int j=0; j<tot; j++) //查找当前状态
{
if ((row[i] & states[j])==states[j]) //当前这一状态符合草地硬件要求(肥沃)
{
for (int k=0; k<tot; k++) //枚举i-1的状态
{
if ((states[j] & states[k])==0)//当前状态states[j]不和上一次状态states[k]冲突
dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;
}
}
}
}
for (int i=0; i<tot; i++)
ans=(ans+dp[n-1][i])%mod;
printf("%d\n",ans);
}
return 0;
}