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 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), 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变量就行。
代码:
1 //#pragma comment(linker, "/STACK:102400000,102400000") 2 #include<cstdio> 3 #include<cmath> 4 #include<iostream> 5 #include<cstring> 6 #include<algorithm> 7 #include<cmath> 8 using namespace std; 9 #define ll long long 10 11 const int MOD=100000000; 12 13 int a[13]; 14 int state[400], sn; 15 int f[13][400]; 16 int m,n; 17 18 void init(){ 19 sn=0; 20 int maxi=1<<n,i; 21 memset(state,0,sizeof(state)); 22 for(i=0;i<maxi;i++){ 23 if(i&(i<<1))continue; 24 state[sn++]=i; 25 } 26 } 27 28 int main(){ 29 int i,j,l,x,y; 30 while(scanf("%d%d",&m,&n)!=EOF){ 31 for(i=0;i<m;i++){ 32 y=0; 33 for(j=0;j<n;j++){ 34 scanf("%d",&x); 35 y|=x<<j; 36 } 37 a[i]=y; 38 } 39 init(); 40 memset(f,0,sizeof(f)); 41 for(i=0;i<sn;i++) 42 if((state[i]&a[0]) == state[i]) f[0][i]=1; 43 for(i=1;i<m;i++){ 44 for(j=0;j<sn;j++){ 45 if((state[j]&a[i]) != state[j]) continue; 46 for(l=0;l<sn;l++){ 47 if(state[j]&state[l])continue; 48 f[i][j]=((ll)f[i][j]+(ll)f[i-1][l])%MOD; 49 } 50 //printf("i=%d,state[j]=%x,f[i][j]=%d\n",i,state[j],f[i][j]); 51 } 52 } 53 int ans=0; 54 for(i=0;i<sn;i++){ 55 ans=((ll)ans+(ll)f[m-1][i])%MOD; 56 } 57 printf("%d\n",ans); 58 } 59 return 0; 60 }
poj3254 Corn Fields (状压DP),布布扣,bubuko.com