标签:
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
Output
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
1 2 3 4There 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.
题意:
有一片地,有的地方可以种草,有的地方不能,并且相邻的两块不能同时种草,问总共有多少种种草的方法。
思路:
由于一行的状态可由前一行的状态推出,dp[i][j]+=dp[i-1][k],k,j表示此行的状态。第一道状压DP,虽然是照着别人的博客写出来的但确实学到了很多。
代码:
1 #include<iostream> 2 #include<string> 3 #include<cstdio> 4 #include<cmath> 5 #include<cstring> 6 #include<algorithm> 7 #include<vector> 8 #include<iomanip> 9 #include<queue> 10 using namespace std; 11 int n,m; 12 int dp[15][1<<13]; 13 bool flag[15][1<<13]; 14 int mat[15]; 15 void init() 16 { 17 for(int i=1;i<=n;i++) 18 for(int j=0;j<(1<<m);j++) 19 { 20 flag[i][j]=true; 21 if((~mat[i]&j)||j&(j<<1)) 22 //原来第i行的状态取反与j状态相与为1说明j状态在没草的地方放牛,所以不合法即~mat[i]&j 23 //判断j状态是否有相邻的两个1,若有即不合法,用j&(j<<1)判断,j<<1即j右移1位 24 //eg:01101--->11010,相与为1,即可判断出有相邻的1,不合法。 25 flag[i][j]=false; 26 } 27 } 28 int main() 29 { 30 while(cin>>n>>m) 31 { 32 memset(mat,0,sizeof(mat)); 33 memset(dp,0,sizeof(dp)); 34 int num; 35 for(int i=1;i<=n;i++) 36 for(int j=m-1;j>=0;j--) 37 { 38 cin>>num; 39 if(num==1) 40 mat[i]|=(1<<j); 41 } 42 init(); 43 for(int i=0;i<(1<<m);i++) 44 if(flag[n][i]) 45 dp[n][i]=1; //初始化为1 46 for(int i=n-1;i>=1;i--) 47 { 48 for(int j=0;j<(1<<m);j++) 49 { 50 if(!flag[i][j]) continue; 51 for(int k=0;k<(1<<m);k++) //枚举i+1的状态。 52 { 53 if(!flag[i+1][k]) continue; 54 if(!(j&k)) //i+1行的状态与i行的状态不冲突 55 dp[i][j]+=dp[i+1][k]; 56 } 57 dp[i][j]%=100000000; 58 } 59 } 60 int sum=0; 61 for(int i=0;i<(1<<m);i++) 62 sum+=dp[1][i]%100000000; 63 sum%=100000000; 64 cout<<sum<<endl; 65 } 66 return 0; 67 }
标签:
原文地址:http://www.cnblogs.com/--ZHIYUAN/p/5734493.html