Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 10900 | Accepted: 5711 |
有一个N*M块大的田地,1代表肥沃,0代表贫瘠,一群牛要在肥沃的土地上吃草,且不能相邻(上下左右),最多有多少种分配方案;状态压缩;
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<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<iostream>
#define LL long long
using namespace std;
const int N=(1<<12);
LL dp[13][N];
int tmp[N]; //(1---N)满足左右不相邻的数;
int ans[13]; //每一行的零数至和,用来判段这一行的枚举的数,是否符合要求。
const LL MOD=1e9;
bool ok(int x)
{
return (x&(x<<1))==0;
}
bool judge(int i,int j)
{
return (ans[i]&tmp[j])==0;
}
int main()
{
int k=0;
for(int i=0;i<N;i++)
{
if(ok(i))
tmp[k++]=i;
}
int n,m;
int x;
while(~scanf("%d%d",&n,&m))
{
memset(ans,0,sizeof(ans));
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
{
scanf("%d",&x);
if(x==0)ans[i]+=(1<<(j-1));
}
}
int M=lower_bound(tmp,tmp+k,(1<<m))-tmp;
for(int i=0;i<M;i++)
{
if(judge(1,i))
dp[1][i]=1;
}
for(int i=2;i<=n;i++)
{
for(int j=0;j<M;j++)
{
if(!judge(i,j))
continue;
for(int p=0;p<M;p++)
{
if(!judge(i-1,p))
continue;
if(!(tmp[j]&tmp[p]))
dp[i][j]+=dp[i-1][p];
}
}
}
LL sum=0;
for(int i=0;i<M;i++)
{
sum=(sum+dp[n][i])%MOD;
}
printf("%I64d\n",sum);
}
return 0;
}