Corn Fields
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.
题目大意:农主有一片n*m的地,他想在上面种草,其中只有为1的才可以种,且相邻的两块地不能同时种,问一个有几种种法。
思路:一般基础的状压就是将一行的状态压成一个数,这个数的二进制形式反映了这一行的情况,这里只有种和不种两种状态,所以可以想到把每一行的种植状态压成一个数
dp[i][j] 表示 前i行中,第i行采用第j种状态时可以得到的所有可行方案总数
dp [ i ] [ j ] = dp[i-1] [k1] +dp[i-1] [k2] ......+dp[i-1][k]
其中第 j 种状态 和第 k1,k2......k 种状态都满足相同位不同时为1,例如 j 为 101 那么ki可能为 000 010
具体可以参考: https://blog.csdn.net/harrypoirot/article/details/23163485 (讲的很详细)
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define mod 100000000
const int N=15;
int st[1<<N],a[N],dp[N][1<<N];
int n,m,top;
int f(int x)
{ //判断相邻位是否为1
if(x&x<<1) return 0;
return 1;
}
void init()
{
top=0;
int tot=1<<m;
for(int i=0;i<tot;i++) //找出m位二进制中所有满足没有相邻1的状态
if(f(i)) st[++top]=i;
}
int fun(int x,int k)
{//判断第k行是否存在状态x
if(x&a[k]) return 0;
return 1;
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
init();
int x;
for(int i=1;i<=n;i++)
{
a[i]=0;
for(int j=1;j<=m;j++)
{
scanf("%d",&x);
if(x==0) a[i]+=(1<<(m-j));
}
}
memset(dp,0,sizeof(dp));
for(int i=1;i<=top;i++)
if(fun(st[i],1))dp[1][i]=1;
for(int i=2;i<=n;i++)
for(int j=1;j<=top;j++)
{
if(!fun(st[j],i)) continue;
for(int k=1;k<=top;k++)
{
if(!fun(st[k],i-1)) continue;
if(st[j]&st[k]) continue; //和上一行的状态有相邻1
dp[i][j]=(dp[i][j]+dp[i-1][k])%mod;
}
}
int ans=0;
for(int i=1;i<=top;i++)
ans=(ans+dp[n][i])%mod;
printf("%d\n",ans);
}
return 0;
}