| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 12738 | Accepted: 6681 |
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.
Source
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
const int N=13;
const int M=1<<13;
const int Mod=1e8;
int dp[N][M];//dp[i][j]表示第i行状态为j的方法数
int Map[N];//每一行给出地的状态
int state[M];//状态
bool judge(int i,int x)//第i行是否可以放状态x,false可以,true不可以
{
return (Map[i]&state[x]);
}
int main()
{
memset(dp,0,sizeof(dp));
memset(state,0,sizeof(state));
memset(Map,0,sizeof(Map));
int m,n,x;
//m行n列
scanf("%d%d",&m,&n);
for(int i=1;i<=m;i++){
for(int j=1;j<=n;j++){
scanf("%d",&x);
if(x==0){
Map[i]+=1<<(j-1);
}
}
}
int k=0;
for(int i=0;i<(1<<n);i++){
if(!(i&(i<<1))){
state[k++]=i;
}
}
//总共有k种状态满足条件:不存在相邻的1
for(int i=0;i<k;i++){
if(!judge(1,i)){
dp[1][i]=1;
}
}
for(int i=2;i<=m;i++){
for(int j=0;j<k;j++){
if(judge(i,j)) continue;//第i行不能按状态j放牛
for(int f=0;f<k;f++){
if(judge(i-1,f)) continue;//第i-1行不能按状态f放牛
if(!(state[j]&state[f])){//判断第i行与第i-1行是否存在相邻的1
dp[i][j]+=dp[i-1][f];
}
}
}
}
int ans=0;
for(int i=0;i<k;i++){
ans+=dp[m][i];
ans%=Mod;
}
cout<<ans<<endl;
return 0;
}

本文介绍了一道经典的牧场景问题,通过状态压缩动态规划方法解决。问题要求在一块矩形草地中种植玉米,避免相邻种植,同时考虑草地肥沃度。文章详细解释了状态压缩的思想,并给出了AC代码。
815

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



