题目链接:POJ-3245 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
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), 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.
题目解析
首先,这题其实就是炮兵阵地(POJ-1185)的简化版(强烈建议A了这道题目后去写一下那道炮兵阵地,有助于理解筛选状态这一思想)。写这篇博客就是为了给一些刚刚入门的选手提供一个缓冲 (其实就是为了水一篇博客)。
n
,
m
n,m
n,m的数据范围基本上能联想到状压
d
p
dp
dp,最高复杂度
12
×
2
12
×
2
12
×
12
×
12
12\times 2^{12}\times2^{12}\times 12\times 12
12×212×212×12×12,妥妥的T。这里就需要简化。我们注意到,在状压后的
2
12
2^{12}
212的状态里,其实有很多是不满足条件里左右不相邻的,那么我们可以预处理出所有符合的情况,只有不到400种,这样的复杂度还是可以接受的。 (啊,又水了一篇博客,爽)
代码:
#include <cstdio>
#include <cstring>
using namespace std;
const int mod = 1e8;
int n, m;
int g[15], c[500][2], tot = 0, dp[15][500][200];
void solve()
{
scanf("%d%d", &n, &m);
memset(dp, 0, sizeof(dp));
for(int i = 1; i <= n; i++){
int tmp = 0, s;
for(int j = 0; j < m; j++){
scanf("%d", &s);
if(s) tmp += (1<<j);
}
g[i] = tmp;
}
dp[1][0][0] = 1;
for(int i = 0; i <= tot; i++)
if((g[1] & c[i][0]) == c[i][0]) dp[1][i][c[i][1]] = 1;
for(int i = 2; i <= n; i++){
for(int j = 0; j <= tot; j++){
if((g[i] & c[j][0]) != c[j][0]) continue;
for(int k = 0; k <= tot; k++){
if((g[i-1] & c[k][0]) != c[k][0]) continue;
if((c[j][0] & c[k][0]) != 0) continue;
for(int t = c[j][1]; t <= m*n/2; t++)
dp[i][j][t] += dp[i-1][k][t-c[j][1]],
dp[i][j][t] %= mod;
}
}
}
int res = 0;
for(int i = 0; i <= tot; i++)
for(int j = 0; j <= m*n/2; j++)
res += dp[n][i][j], res %= mod;
printf("%d\n", res);
}
int main()
{
c[0][0] = c[0][1] = 0;
for(int i = 1; i < (1<<12); i++){
bool flag = true;
int cc = 0;
for(int j = 0; j < 12; j++)
if(i & (1<<j)){
cc++;
if(i & (1<<(j+1))) {flag = false; break;}
}
if(flag) c[++tot][0] = i, c[tot][1] = cc;
}
solve();
}