当前位置: 代码迷 >> 综合 >> POJ - 3254 Corn Fields ( 状态压缩 DP )
  详细解决方案

POJ - 3254 Corn Fields ( 状态压缩 DP )

热度:45   发布时间:2023-11-23 12:44:56.0

POJ - 3254 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.

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.

AC代码

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
typedef long long ll;
const int N=15,M=1<<15;
int f[N][M];   // 表示第 i 行状态为 j 的方案数 
int state[M];  // 一行中,不相邻的所有情况 
int cur[N];	  // 每一行中土地的贫瘠或者肥沃,贫瘠用 1 表示,肥沃用 0 表示 
int n,m;int main()
{
    while(cin>>m>>n){
    int top=1;// 预处理出符合条件的状态 for(int i=0;i<(1<<n);i++)if((i&(i<<1))==0){
    state[top]=i;top++;}top--;// 根据题目的给定,确定那些土地是贫瘠的 memset(cur,0,sizeof cur); for(int i=1;i<=m;i++){
    for(int j=1;j<=n;j++){
    int x;cin>>x;if(x==0) // 土地贫瘠{
    cur[i]=cur[i]|(1<<(n-j)); } }}// 判断所有的状态和第一行的状态的逆是否有重合 memset(f,0,sizeof f);for(int i=1;i<=top;i++){
    if((state[i]&cur[1])==0) f[1][i]=1;}for(int i=2;i<=m;i++){
    for(int k=1;k<=top;k++){
    if((state[k]&cur[i])==0){
    for(int j=1;j<=top;j++){
    if(((state[j]&cur[i-1])==0)&&((state[j]&state[k])==0)){
    f[i][k]=(f[i][k]+f[i-1][j])%100000000;}}}}} int ans=0;for(int i=1;i<=top;i++) ans=(ans+f[m][i])%100000000;cout<<ans<<endl;}return 0;
}
  相关解决方案