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的方格可以种草,为0的不可以,你可以任意选择为1的方格去种草,但是任意两块种草的地方不能相邻(上下或者左右都不可以),问有多少种方案。
思路:经典状压dp,dp[j][i]表示前i行,当前行状态为j时共有多少种方案。
转移时枚举上一行的状态,若两行不冲突,且状态不与地图冲突(即不能在为0的方格种草)
那么dp[j][i]+=dp[k][i-1](k为上一行的状态)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define mod 100000000
const int N =1<<13;
int dp[N][13];
int nr[N],top,n,m;
int mp[N];
void init()
{
for(int i=0;i<(1<<m);i++) //提前预处理所有可行的行的状态
{
if((i<<1&i)==0) //只要满足没有相邻的两个1就可以
nr[top++]=i;
}
}
int main()
{
cin>>n>>m;
for(int i=1;i<=n;i++)
{
int x=0,y;
for(int j=0;j<m;j++)
{
scanf("%d",&y);
if(y==1)
x+=1<<(m-j-1); //要保证存的1的位置和地图的位置一样,那么位置靠左的就左移的多一点,自己想想就明白了
}
mp[i]=x;
}
init();
dp[0][0]=1; //注意初始化,,刚开始我把第0行的所有状态都初始化成1了,,很傻
int ans=0;
for(int i=1;i<=n;i++)
{
for(int j=0;j<top;j++)
{
if((mp[i]|nr[j])!=mp[i]) //当前状态的所有1都必须在地图上有,即不能在地图为0的格子种草
continue;
for(int k=0;k<top;k++)
{
if((nr[k]&nr[j])==0) //若不与上一行的状态冲突,进行转移
dp[nr[j]][i]=(dp[nr[k]][i-1]+dp[nr[j]][i])%mod;
}
}
}
for(int i=0;i<top;i++)
ans=(ans+dp[nr[i]][n])%mod;
cout<<ans<<endl;
return 0;
}