状态压缩 dp poj 3254 Corn Fields

Corn Fields
Time Limit: 2000MS   Memory Limit: 65536K
Total Submissions: 13187   Accepted: 6911

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

题目大意:

给出一块 n*m 的空地,给出每块空地的状态, 1 为可以放牛,0 为不可以放牛 ,并且两个牛不可以相邻,问 有多少种安排的方式,其中一头牛都不放也是一种方式。

思路:

这是状压dp的入门题目,对于每一行的状态,我们用一个二进制数字来表示,例如 第一行  101001  表示 第一块空地放牛,第三块空地放牛,第六块空地放牛,其余每行的状态都是这样表示,然后判断当前状态是否合法,如果当前状态合法,那么就是一种可行的情况,累加起来最后就是答案。
状态 : dp [ i ] [ j ] 为第  i 行 状态 j 时的排列方案,
初始值:  第一行所有的合法状态 都为 1 
我们都知道,dp 最重要的是状态转移方程,那么这样的状态转移方程怎么写呢?
我们首先枚举所有的单行合法状态,枚举第  i  行的 第 j 种状态,枚举第 i-1 行的 第 k 种状态  如果两个状态不冲突 那么
dp [ i ] [ j ] + = dp[ i - 1] [ k ] 
最后一行的所有值 加起来 即为答案。

好了说到这里 问题来了  如何判断一个状态是否 合法?
需要满足的条件: 左右的两个 1 不可以相邻 (两个牛不可以相邻) , 状态 i & (i<<1)==0
     只有肥沃的土地才可以放牛 (土地的限制)   状态 i & map [ j ] ==0    状态 i  & 当前行地图
    上下的牛不相邻     i & j ==0      i 为当前行状态  j 为前一行的状态 。 

感想:

好好理解这道题目 可以 A 好多题,真的,

AC代码:

#include 
#include 
#include 
using namespace std;
const int mod = 100000000;
const int maxx=1<<12+1;
int n,m;
int mapp[15];
int all[maxx];
int dp[15][maxx];
bool isok(int f,int s)
{
    return (mapp[f]&all[s]);
}
int main()
{
    int i,j,t;
    while(~scanf("%d%d",&n,&m))
    {
        int k=0;
        memset(mapp,0,sizeof(mapp));
        memset(dp,0,sizeof(dp));
        memset(all,0,sizeof(all));
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                scanf("%d",&t);
                if(t==0)
                {
                    mapp[i]+=(1<<(m-j));
                }
                //cout<


你可能感兴趣的:(状态压缩,dp,压缩,dp)