【状压DP水题】[USACO06NOV]玉米田Corn Fields

题目描述

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.

农场主John新买了一块长方形的新牧场,这块牧场被划分成M行N列(1 ≤ M ≤ 12; 1 ≤ N ≤ 12),每一格都是一块正方形的土地。John打算在牧场上的某几格里种上美味的草,供他的奶牛们享用。

遗憾的是,有些土地相当贫瘠,不能用来种草。并且,奶牛们喜欢独占一块草地的感觉,于是John不会选择两块相邻的土地,也就是说,没有哪两块草地有公共边。

John想知道,如果不考虑草地的总块数,那么,一共有多少种种植方案可供他选择?(当然,把新牧场完全荒废也是一种方案)

输入输出格式

输入格式:
第一行:两个整数M和N,用空格隔开。

第2到第M+1行:每行包含N个用空格隔开的整数,描述了每块土地的状态。第i+1行描述了第i行的土地,所有整数均为0或1,是1的话,表示这块土地足够肥沃,0则表示这块土地不适合种草。

输出格式:
一个整数,即牧场分配总方案数除以100,000,000的余数。

输入输出样例

输入样例#1: 复制
2 3
1 1 1
0 1 0
输出样例#1: 复制
9
T

这道题就是一个状压的模板

首先状压顾名思义就是把一个状态压缩,这类题的标志是数据范围比较小

这道题首先我们把所有一行里不相邻的状态都搜出来

1 void init(int id,int sit)
2 {
3     if(id>n)
4         {situ[++initpp]=sit;return;}
5     init(id+2,sit+(1<<(id-1)));//fang,不能相邻所以要加2
6     init(id+1,sit);//bufang
7 }

我选择的是在这个数前面填加1或0,这样不会涉及到冒了的问题,最开始我写成向这个数的后面加1或0,这样就不对了

这样situ里就是一行里所有不相邻的状态

然后我用一个can数组表示第i行的让不让放的状态,

这么预处理之后,只要将当前行和之前行&一下,与上一行的状态&一下,不让它为真,然后就保证不冲突了

代码在此

 1 #include<cstdio>
 2 #include<algorithm>
 3 #define mod 100000000
 4 #define initma (1<<12)+1
 5 using namespace std;
 6 typedef long long ll;
 7 int n,m,initpp;
 8 ll ans;
 9 int in,situ[initma],dp[15][initma],can[15];
10 void init(int id,int sit)
11 {
12     if(id>n)
13         {situ[++initpp]=sit;return;}
14     init(id+2,sit+(1<<(id-1)));//fang
15     init(id+1,sit);//bufang
16 }
17 int main()
18 {
19     scanf("%d%d",&m,&n);
20     for(int i=1;i<=m;i++)for(int j=1;j<=n;j++)
21     {
22         scanf("%d",&in);
23         can[i]|=((in^1)<<(j-1));
24     }
25     init(1,0);
26     for(int i=1;i<=initpp;i++)
27         if(!(situ[i]&can[1]))
28             dp[1][i]=1;
29     for(int i=2;i<=m;i++)
30     {
31         for(int j=1;j<=initpp;j++)
32         {
33             for(int k=1;k<=initpp;k++)
34                 if((!(situ[k]&situ[j]))&&(!(situ[j]&can[i]))&&(!(situ[k]&can[i-1])))
35                     dp[i][j]+=dp[i-1][k],dp[i][j]%=mod;
36         }
37     }
38     for(int j=1;j<=initpp;j++)ans+=dp[m][j],ans%=mod;
39     printf("%lld
",ans%mod);
40     return 0;
41 }
原文地址:https://www.cnblogs.com/Qin-Wei-Kai/p/10215159.html