状态dp POJ 3254 Corn Fields

来源:互联网 发布:南昌大学网络教学平台 编辑:程序博客网 时间:2024/05/16 10:53

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 31 1 10 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.

这题的思路主要是一行一行的找,而每一行所能取到的情况用i&i<<1来找如果是0的话就成立,之后就是确定所选的情况,有没有点是不能用的,和有没有点是与上一行相连的,之后再把最后一行的所有情况加起来就好;

代码中比较难以理解的地方就是位运算的部分,比如说第一个init()函数,他的作用是找出所有满足1和1是分开放置的情况,就是说二进制表示的话起码得是101010这样,其他的见注释吧。

#include <stdio.h>#include <cstring>int v[1<<12],dp[13][1<<12],l;int n,m,a[13][13];void init(){int i;l=0;for(i=0;i<(1<<12);i++){if((i&(i<<1))==0)//这个运算能找出所有若表示成二进制的形式则1和1之间是不相邻的的数v[l++]=i;}}int judge(int x,int y){int i;for(i=0;i<m;i++)if((1<<i)&v[y]&&!a[x][i])//先是看看该点是不是被选中了,再看该点是不是不能被选中return 0;return 1;}int main(){int i,j,k;init();while(~scanf("%d%d",&n,&m)){memset(dp,0,sizeof(dp));for(i=0;i<n;i++)for(j=0;j<m;j++)scanf("%d",&a[i][j]);for(i=0;i<n;i++){for(j=0;v[j]<(1<<m);j++){if(judge(i,j)){if(i==0)dp[0][j]=1;else{for(k=0;v[k]<(1<<m);k++)if((v[k]&v[j])==0)//和上一行比较看看有没有相连的情况dp[i][j]+=dp[i-1][k];}}}}__int64 ans=0;for(i=0;v[i]<(1<<m);i++)ans=(ans+dp[n-1][i])%100000000;printf("%d\n",ans);}return 0;}

1 0
原创粉丝点击