Corn Fields
| Time Limit: 2000MS | Memory Limit: 65536K | |
| Total Submissions: 21643 | Accepted: 11344 |
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.
题意:
给你一个n*m(n,m<=12)的网格,有些格子有障碍物,每一个格子都可以放一个兵,但它的上下左右不能有其他的兵,问你最多放多少个兵。
思路:
经典状压dp,预处理出合法状态,再枚举上一行、这一行的状态即可。
代码:
#include<iostream>
#include<cmath>
#include<iomanip>
#include<cstring>
#include<algorithm>
#include<cstdio>
#include<string>
#include<queue>
#include<vector>
#include<map>
#define ll long long
#define inf 0x3f3f3f3f
using namespace std;
const int maxn=14;
const ll mo=1e8;
int n,m,q;
int a[maxn][maxn];
int tmp[maxn];
int zt[maxn][(1<<12)+5];
ll dp[maxn][(1<<12)+5];
int main()
{
int T,cas=1;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(tmp,0,sizeof(tmp));
for(int i=1;i<=n;i++)
{
for(int j=0;j<m;j++)
{
int x;
scanf("%d",&x);
if(!x) tmp[i]|=(1<<j);
}
}
int mm=(1<<m);
zt[0][0]=1;
zt[0][1]=0;
for(int i=1;i<=n;i++)
{
zt[i][0]=0;
for(int j=0;j<mm;j++)
{
if((j|tmp[i])!=j) continue;
int x=j^tmp[i];
if(x&(x<<1)) continue;
if(x&(x>>1)) continue;
zt[i][++zt[i][0]]=j;
}
}
memset(dp,0,sizeof(dp));
dp[0][0]=1;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=zt[i-1][0];j++)
{
int x=zt[i-1][j],xx=x^tmp[i-1];
for(int k=1;k<=zt[i][0];k++)
{
int y=zt[i][k],yy=y^tmp[i];
if(xx&yy) continue;
dp[i][y]=(dp[i][y]+dp[i-1][x])%mo;
}
}
}
ll ans=0;
for(int j=1;j<=zt[n][0];j++)
ans=(ans+dp[n][zt[n][j]])%mo;
//ans=(ans-1+mo)%mo;
printf("%lld\n",ans);
}
return 0;
}

本文介绍了一个经典的状压动态规划问题,通过预处理合法状态并枚举上一行和当前行的状态来求解在一个n*m网格中,避免相邻放置士兵的最大数量。问题背景为在某些格子不可用的情况下,考虑所有可能的种植方案。
816

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



