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>
#include<algorithm>
using namespace std;
const int mod=100000000;
int n,m;//n*m
int a[30][30];
int dp[30][500];//dp[i][j]第i行j状态的个数
int num[500],sum[500];//第i个状态的10进制,第i个状态的1的个数
int len;//状态个数
int num2[500];//地形
void build()
{
len=0;
for(int i=0;i<(1<<m);i++)
{
if((i<<1)&i) continue;
num[++len]=i;
int tmp=i,cnt=0;
while(tmp) cnt+=(tmp&1),tmp>>=1;
sum[len]=cnt;
}
}
bool match(int x,int y)//地形x与状态y是否匹配
{
if(x&y) return 0;
return 1;
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
build();
for(int i=1;i<=n;i++)
{
num2[i]=0;
for(int j=0;j<m;j++)
{
int x;scanf("%d",&x);
if(x==0) num2[i]|=(1<<j);
}
}
//第一行
memset(dp,0,sizeof(dp));
for(int j=1;j<=len;j++)
{
if(match(num2[1],num[j]))
{
dp[1][j]=1;
}
}
for(int i=2;i<=n;i++)
{
for(int j=1;j<=len;j++)
{
if(match(num2[i],num[j])){
for(int k=1;k<=len;k++)
{
if((num[k]&num[j])==0)
{
dp[i][j]+=dp[i-1][k];
dp[i][j]%=mod;
}
}
}
}
}
int cnt=0;
for(int j=1;j<=len;j++)
{
cnt=(cnt+dp[n][j])%mod;
}
printf("%d\n",cnt);
}
return 0;
}
本文介绍了一个关于农场种植的算法问题,旨在找出在考虑地形限制和避免相邻种植的情况下,选择种植地块的所有可能方式的数量。通过使用动态规划的方法解决了该问题,并提供了一段C++实现代码。
813

被折叠的 条评论
为什么被折叠?



