Crawling in process... Crawling failed Time Limit:2000MS Memory Limit:65536KB 64bit IO Format:%lld & %llu
Description
Input
Output
Sample Input
Sample Output
Hint
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 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.
题意:
有一片地,有的地方可以种草,有的地方不能,并且相邻的两块不能同时种草,问总共有多少种种草的方法。
思路:
由于一行的状态可由前一行的状态推出,dp[i][j]+=dp[i-1][k],k,j表示此行的状态。第一道状压DP,虽然是照着别人的博客写出来的但确实学到了很多。
代码:
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int MOD = 1e8;
int n, m, f[][ << ], mp[], g[][ << ];
int main()
{
while (~scanf("%d %d", &n, &m)) {
for (int i = ; i < n; ++i) {
for (int j = m - , x; j >= ; --j) {
scanf("%d", &x);
if (x) mp[i] |= ( << j);
}
}
for (int i = ; i < n; ++i) {
for (int j = ; j < ( << m); ++j) {
g[i][j] = ;
if (j & (j <<)) continue;
if (~mp[i] & j) continue;
//原来第i行的状态取反与j状态相与为1说明j状态在没草的地方放牛,所以不合法即~mat[i]&j
//判断j状态是否有相邻的两个1,若有即不合法,用j&(j<<1)判断,j<<1即j右移1位
//eg:01101--->11010,相与为1,即可判断出有相邻的1,不合法。
g[i][j] = ;
}
}
for (int j = ; j < ( << m); ++j) f[][j] = g[][j];
for (int i = ; i < n; ++i) {
for (int j = ; j < ( << m); ++j) {
f[i][j] = ;
if (!g[i][j]) continue;
for (int k = ; k < ( << m); ++k) {
if (!g[i - ][k]) continue;
if (j & k) continue; //i+1行的状态与i行的状态不冲突
f[i][j] = (f[i][j] + f[i - ][k]) % MOD;
}
}
}
int ans = ;
for (int j = ; j < ( << m); ++j) {
ans = (ans + f[n - ][j]) % MOD;
}
printf("%d\n", ans);
}
return ;
}