# [POJ 3254] Corn Fields【状压DP】

• 2018-01-22
• 0
• 0

## Problem:

 Time Limit: 2000MS Memory Limit: 65536K

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

USACO 2006 November Gold

## Solution:

1. (s & mp[i]) == s，保证本行可以种成 s 状态。
2. (t & mp[i - 1]) == t，保证上一行可以种成 r 状态。
3. (s & s >> 1) > 0，保证 s 状态没有左右相邻的两只牛，用 islegal[] 记录。
4. (t & t >> 1) > 0，同条件 3 理。
5. (s & t) == 0，保证 s 状态和 t 状态没有上下相邻的两只牛。

## Code: O(22NM) [716K, 0MS]

```#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cmath>
#include<iostream>
#include<algorithm>
using namespace std;

int M, N, S, mp, sq;
int dp;
bool islegal;

int main(){
scanf("%d%d", &M, &N), S = 1 << N;
for(register int i = 1; i <= M; i++)
for(register int j = 1; j <= N; j++)
scanf("%d", &sq), mp[i] = mp[i] << 1 | sq;
for(register int s = 0; s < S; s++){
if(s & s >> 1) continue;
islegal[s] = 1;
if((s & mp) == s) dp[s] = 1;
else dp[s] = 0;
}
#define MOD 100000000
#define inc(a, b) a = (a + (b) < MOD ? a + (b) : a + (b) - MOD)
for(register int i = 2; i <= M; i++)
for(register int s = 0; s < S; s++)
if(islegal[s] && (s & mp[i]) == s)
for(register int r = 0; r < S; r++)
if(islegal[r] && (r & mp[i - 1]) == r && (s & r) == 0)
inc(dp[i][s], dp[i - 1][r]);
int ans = 0;
for(register int s = 0; s < S; s++)
if(islegal[s]) inc(ans, dp[M][s]);
printf("%d\n", ans);
return 0;
}
```

#### 评论

darkleafin.cf
(该域名已过期且被抢注。。)
darkleafin.github.io

49750

https://github.com/Darkleafin

OPEN AT 2017.12.10

Please refresh the page if the code cannot be displayed normally.

https://visualgo.net/en

- Theme by Qzhai