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. Source |
[Submit] [Go Back] [Status] [Discuss]
题意:给你一个矩阵,1可以放植物,0不可以放植物,植物间不能相邻。问有多少种放法。思路:轮廓线dp,也可以说是状压dp的一种,枚举每个点,每次把每种状态算一遍,最后加起来就好了,用0 1滚动节省内存,对于每个位置,如果上面有植物的话肯定是不能放植物的,然后如果这个位置是1,左边没有东西或者它在第一列,那么这个位置可以选择放和不放两种,思路基本就这样,下面给代码:
#include<cstdio>
#include<cstring>
#include<vector>
#include<queue>
#include<iostream>
#include<algorithm>
#include<cmath>
#include<bitset>
#include <utility>
using namespace std;
#define maxn (1<<12)+5
typedef long long LL;
const int mod = 1e8;
int dp[2][maxn];
int arr[15][15];
int main(){
int m, n;
while (~scanf("%d%d", &m, &n)){
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
scanf("%d", &arr[i][j]);
}
}
memset(dp[0], 0, sizeof(dp[0]));
dp[0][0] = 1;
int now = 0;
for (int i = 0; i < m; i++){
for (int j = 0; j < n; j++){
now ^= 1;
memset(dp[now], 0, sizeof(dp[now]));
for (int k = 0; k < (1 << n); k++){
if ((k << 1)&(1 << n)){
dp[now][k << 1 ^ (1 << n)] += dp[now ^ 1][k];
dp[now][k << 1 ^ (1 << n)] %= mod;
}
else{
dp[now][k << 1] += dp[now ^ 1][k];
dp[now][k << 1] %= mod;
if (arr[i][j]&&(!j|| !(k & 1))){
dp[now][k << 1 | 1] += dp[now ^ 1][k];
dp[now][k << 1 | 1] %= mod;
}
}
}
}
}
int ans = 0;
for (int i = 0; i < (1 << n); i++){
ans += dp[now][i];
ans %= mod;
}
printf("%d\n", ans);
}
}