题目链接:http://poj.org/problem?id=3254
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 11536 | Accepted: 6045 |
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.
题目大意:有n*m大的一个地方,1表示土地肥沃可以种植物,0表示不能种植物,问:在不许有两个植物相邻的情况下,有多少种放置的方法。
用状压dp求解。
dp[i][j]表示第i行状态 j 的可行数目。
状态转移方程为: dp[i][j]=dp[i-1][k1]+...dp[i-1][kn] (其中k1,k2,...kn为在当前行状态下,上一行满足的状态)
其他细节见代码注释:
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<vector>
using namespace std;
#define ll long long
const int INF=0x3f3f3f3f;
const int MOD=100000000;
const int MAXX=10000+5;
const int N=13;
const int M=1<<N;
int mp[N]; //存储每一行的输入状态
int dp[N][M]; //第N行状态为M的个数
bool judge(int i,int x){ //判断状态x在第i行是否符合
if((mp[i]&x)!=x){ //如果x是合法的状态,mp[i]&x=x;【x为1的位 mp[i]响应为1; x为0的位,结果相应位上位0,故与x相等】
return false;
}
if((x&(x<<1))!=0){ //判断x是否有相邻的1
return false;
}
return true;
}
int main(){
int n,m,x;
while(scanf("%d%d",&n,&m)!=EOF){
memset(mp,0,sizeof(mp));
memset(dp,0,sizeof(dp));
for(int i=1;i<=n;i++){
for(int j=1;j<=m;j++){
scanf("%d",&x);
mp[i]=(mp[i]<<1)+x; //保存每一行的状态
}
}
dp[0][0]=1;
for(int i=1;i<=n;i++){ //遍历所有行
for(int j=0;j<(1<<m);j++){ //遍历所有状态
if(!judge(i,j)){ //判断该状态在当前行是否符合
continue;
}
for(int z=0;z<(1<<m);z++){ //遍历上一行的所有状态
if(judge(i-1,z)==0){
continue;
}
if((j&z)!=0){ //判断上一行和当前行是否有相邻1
continue;
}
dp[i][j]=(dp[i][j]+dp[i-1][z])%MOD;
}
}
}
int ans=0;
for(int i=0;i<(1<<m);i++){
ans=(ans+dp[n][i])%MOD;
}
printf("%d\n",ans);
}
}