poj 3254 Corn Fields
http://poj.org/problem?id=3254
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7113 | Accepted: 3778 |
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
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
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
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.
#include<iostream> #include<cstdio> #include<cstring> #define inf 100000000 using namespace std; int sta[4096],n,m,p; int dp[16][100000]; void init() { int i; for(i=0;i<1<<m;i++) { if(!(i&i<<1)) sta[p++]=i; } }//符合不相邻的所有状态,用sta数组来保存。 int fit(int x,int y) { if(x&y) return 0; else return 1; }//上一行与下一行是否相邻。不相邻为1,相邻为0。 int main() { int i,j,tem,a[20],k,ans; scanf("%d%d",&n,&m); p=0; memset(dp,0,sizeof(dp)); memset(a,0,sizeof(a)); memset(sta,0,sizeof(sta)); for(i=1;i<=n;i++) { for(j=1;j<=m;j++) { scanf("%d",&tem); if(tem==0) a[i]+=1<<m-j; }//把原来的状态取反,判断sta数组的状态与题意给出的状态是否相符。 } init(); for(i=0;i<p;i++) if(fit(sta[i],a[1]))//&出来的结果为0,返回值为1,则题意存在这种状态。 dp[1][i]=1;//初始化赋为1。 for(i=2;i<=n;i++)//该行 { for(j=0;j<p;j++)//遍历该行所有的状态。 { if(!fit(sta[j],a[i]))//判断该状态是否存在。 continue; for(k=0;k<p;k++)//遍历上一行的状态。 { if(!fit(sta[k],a[i-1]))//上一行状态是否存在。 continue; if(!fit(sta[k],sta[j]))//上一行与这一行是否有冲突。 continue; dp[i][j]+=dp[i-1][k];//叠加上一行。 dp[i][j]=(dp[i][j]+inf)%inf; } } } ans=0; for(i=0;i<p;i++) ans+=dp[n][i];//把最后一行所有的状态全部叠加。 ans=(ans+inf)%inf; printf("%d\n",ans); return 0; }