http://poj.org/problem?id=3254
Corn Fields
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 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 Sample Output 9 Hint Number the squares as follows:
1 2 3 There are four ways to plant only on one squares (1, 2, 3, or 4), Source |
大意:有一个m行n列的矩阵,里面为1的地方可以种玉米,为0的地方不能种玉米。玉米不能种在相邻的格子(种玉米的格子不能有共用边),求种玉米的种类数。模100000000。
题解:状压DP。
状压DP一般是把状态压到1个数里,然后这个数可以当数组的下标。这题就是把一行当一个状态,用一个数的12个二进制位表示这一行各个地有没有种玉米,2^12=4096,随便接受。
由于玉米不能相邻,我们可以预处理排除很多状态,只用可能的状态。用x表示状态,则(x&(x<<1))为真就是有玉米相邻,不用这种状态。最后把状态存到state[]里,n=12时也只有不到400个。
把一行各个格子是否允许种玉米也压成一个数y,(x&y)为真就是这行不能用x这个状态。
f[i][j]表示:第i行的状态为j,0~i-1行有多少种方案。
一行一行推,枚举这一行的状态j、上一行的状态l(这里的j和l是状态编号,不是状态的二进制),若(state[j] & state[l])为真,说明有两行有相邻的,continue。
一行一行累计种类数,把最后一行各个状态的种类数求和就能得到答案,记得取模。
我怕运算过程中产生超int,所以过程中转成long long。其实也可以直接全部用long long变量就行。
代码:
//#pragma comment(linker, "/STACK:102400000,102400000")
#include<cstdio>
#include<cmath>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define ll long long const int MOD=; int a[];
int state[], sn;
int f[][];
int m,n; void init(){
sn=;
int maxi=<<n,i;
memset(state,,sizeof(state));
for(i=;i<maxi;i++){
if(i&(i<<))continue;
state[sn++]=i;
}
} int main(){
int i,j,l,x,y;
while(scanf("%d%d",&m,&n)!=EOF){
for(i=;i<m;i++){
y=;
for(j=;j<n;j++){
scanf("%d",&x);
y|=x<<j;
}
a[i]=y;
}
init();
memset(f,,sizeof(f));
for(i=;i<sn;i++)
if((state[i]&a[]) == state[i]) f[][i]=;
for(i=;i<m;i++){
for(j=;j<sn;j++){
if((state[j]&a[i]) != state[j]) continue;
for(l=;l<sn;l++){
if(state[j]&state[l])continue;
f[i][j]=((ll)f[i][j]+(ll)f[i-][l])%MOD;
}
//printf("i=%d,state[j]=%x,f[i][j]=%d\n",i,state[j],f[i][j]);
}
}
int ans=;
for(i=;i<sn;i++){
ans=((ll)ans+(ll)f[m-][i])%MOD;
}
printf("%d\n",ans);
}
return ;
}