洛谷传送门数组
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.ide
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.spa
农场主John新买了一块长方形的新牧场,这块牧场被划分红M行N列(1 ≤ M ≤ 12; 1 ≤ N ≤ 12),每一格都是一块正方形的土地。John打算在牧场上的某几格里种上美味的草,供他的奶牛们享用。code
遗憾的是,有些土地至关贫瘠,不能用来种草。而且,奶牛们喜欢独占一块草地的感受,因而John不会选择两块相邻的土地,也就是说,没有哪两块草地有公共边。get
John想知道,若是不考虑草地的总块数,那么,一共有多少种种植方案可供他选择?(固然,把新牧场彻底荒废也是一种方案)it
第一行:两个整数M和N,用空格隔开。io
第2到第M+1行:每行包含N个用空格隔开的整数,描述了每块土地的状态。第i+1行描述了第i行的土地,全部整数均为0或1,是1的话,表示这块土地足够肥沃,0则表示这块土地不适合种草。ast
一个整数,即牧场分配总方案数除以100,000,000的余数。class
输入 #1复制angular
输出 #1复制
看到这个数据范围,和这个招牌的01串。应该能想到是状压\(DP\)计数的问题。
(话说状压\(DP\)就是按数据范围碰?)
那么咱们考虑把状态设置成:\(dp[i][j]\)表示第\(i\)行状态为\(j\)的时候的方案数。
如今这道题最让咱们无所适从的条件就是判断这块地能不能种草。
咱们容易发现:不能种草的状况只有两种:有一些地原本就是荒芜的,不能种草。另外有一些地是由于相邻的地被种上草了因此不能种草。因此咱们在转移的时候必定要把判断条件处理好了。
这个怎么去判断呢?
须要高深的位运算知识
因此咱们的判断条件就是\(j\&F[i]==j\)。这样的话,若是\(j\)在不应种草的地方种上了草(得1),那么它与上0会得0,就不等于\(j\)了。
显然,若是一个状态合法,在横向上会有\(010101...\)这样的状况出现,也就是说对于一个1,它的前一位和后一位确定是\(0\).那么咱们开一个状态数组\(st[i]\)。若是它符合“\(010101...\)”的条件,那么显然会有:
\(i\&(i<<1)=0,i\&(i>>1)=0\)。
那么纵向相邻怎么判呢?能够发现,纵向是否相邻是由当前枚举到的状态决定的。因此没法预处理,只能在枚举当前状态时看。
当咱们枚举到一个状态:\(dp[i][j]\)的时候,咱们须要知道的是\(dp[i-1]\)的状态。不须要考虑\(dp[i+1]\)的状态的缘由是动态规划的无后效性。那么咱们只须要再枚举\(dp[i-1]\)的状态,依次确认是否合法便可。合法的条件就是\(k\&j=0\)。也就是说,在\(k\)能种的地上\(j\)必须选择不种。
那么转移方程就是:
\[ dp[i][j]=dp[i][j]+dp[i-1][k]\quad(mod\,\,p) \]
最终的答案还要统计全部的方案数。须要把全部状态枚举一遍,依次累加\(dp[m][i]\)。
那么这道题就完事了。难点不是状压的过程,是状压合法转移的判断过程。
代码:
#include<cstdio> #include<bitset> using namespace std; const int mod=1e9; int m,n; int map[20][20]; int dp[20][1<<12],F[20]; bool st[1<<12]; //dp[i][j]表示第i行状态为j的时候的方案数 int main() { scanf("%d%d",&m,&n); for(int i=1;i<=m;i++) for(int j=1;j<=n;j++) { scanf("%d",&map[i][j]); F[i]=(F[i]<<1)+map[i][j]; } for(int i=0;i<(1<<n);i++) st[i]=((i&(i<<1))==0) && (((i&(i>>1))==0)); dp[0][0]=1; for(int i=1;i<=m;i++) for(int j=0;j<(1<<n);j++) if(st[j] && ((j&F[i])==j)) for(int k=0;k<(1<<n);k++) if((k&j)==0) dp[i][j]=(dp[i][j]+dp[i-1][k])%mod; int ans=0; for(int i=0;i<(1<<n);i++) ans=(ans+dp[m][i])%mod; printf("%d",ans); return 0; }