Corn Fields
Time Limit: 2000MS Memory Limit: 65536K
Total Submissions: 4348 Accepted: 2289
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
[cpp]
#include<iostream>
#include<cstdlib>
#include<stdio.h>
#include<memory.h>
#define ll long long
#define maxn (1<<13)
#define mod 100000000
using namespace std;
int n,m;
int dp[15][maxn];//第i行狀態為j時滿足的方案數。
bool flag[15][maxn];//判斷第i行狀態為j時是否合法。
int mat[15];
int mm;
void init()
{
for(int i=1;i<=n;i++)
for(int j=0;j<=mm;j++)
{
flag[i][j]=true;
//原來第i行的狀態取反與j狀態相與為1說明j狀態在沒草的地方放牛,所以不合法即~mat[i]&j
//判斷j狀態是否有相鄰的兩個1,若有即不合法,用j&(j<<1)判斷,j<<1即j右移1位
//eg:01101--->11010,相與為1,即可判斷出有相鄰的1,不合法。
if((~mat[i]&j)||(j&(j<<1)))
flag[i][j]=false;
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(dp,0,sizeof(dp));
memset(mat,0,sizeof(mat));
int num;
for(int i=1;i<=n;i++)
for(int j=m-1;j>=0;j--)
{
scanf("%d",&num);
if(num==1)mat[i]|=(1<<j);
}
mm=(1<<m)-1;
init();
for(int i=0;i<=mm;i++)
if(flag[n][i]) dp[n][i]=1;//初始化為1
int i,j;
for(i=n-1;i>=1;i--)//自底向上
{
for(j=0;j<=mm;j++)
{
if(!flag[i][j]) continue;
for(int k=0;k<=mm;k++)//枚舉i+1行的狀態
{
if(!flag[i+1][k]) continue;
if(!(j&k))//i+1行的狀態與i行的狀態不沖突
dp[i][j]+=dp[i+1][k];
}
dp[i][j]%=mod;
}
}
int ans=0;
for(i=0;i<=mm;i++)
ans+=dp[1][i]%mod;
ans%=mod;
cout<<ans<<endl;
}