POJ - 3254 Corn Fields(状压DP入门)

链接POJ 3254
题目: 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.
题意: 农民有一个矩阵草原养牛,为1的方块才能养,为0的不能养,而且每头牛不能相邻,现在给你一个草原,问你农名最多有多少种养牛方案.
思路: 一道非常经典并且简单的状压DP入门题,可以看出每头牛不能相邻的含义就是其上下左右四个方向上都不能有牛,我可以先保证一行里没有相邻的牛,再考虑上下两行直接有没有牛相邻,而上下两行之间有没有牛相邻我们可以看成每一行跟上一行没有牛相邻,所以我们可以得出动态转移方程:
dp[i][j] =sum( dp[i-1][k] );
其中i表示行数,j表示该行选择的一个状态,k表示i-1行 不与 j 状态状态相邻的状态.dp表示种类数.具体解释看代码注释.
AC代码

const long long mod = 100000000;
int n,m;
int mn[15];
long long dp[15][1<<13];
int vis[15][1<<13];

int main() {
	cin>>n>>m;
	for(int i=0;i<n;i++) {
		int ans = 0;
		for(int j=0;j<m;j++) {//用二进制的方式构造草原,1为能养牛,0为不能养牛
			int a;
			cin>>a;
			ans = (ans<<1)+a;
		}
		mn[i]=ans;
		for(int j=0;j<=mn[i];j++) {//把每一行符合条件的状态筛选出来.
			if((j & mn[i])!=j) continue;//剔除在不能养牛的位置养牛的状态,如mn[i]=100,j=010;
			if((j&(j<<1))||(j&(j>>1))) continue;//剔除有两头牛相邻的状态,如mn[i]=110,j=110;
			vis[i][j]=1;// 符合条件的标记一下。
			//cout<<j<<endl;
		}
	}
	for(int i=0;i<n;i++) {//从第一行开始
		for(int j=0;j<=mn[i];j++) {
			if(!vis[i][j]) continue;
			if(i==0) {
				dp[i][j]=1;//第一行初始化
			} 
			else {
				for(int k=0;k<=mn[i-1];k++) {
					if(!vis[i-1][k]) continue;
					if((j&k) != 0) continue;//不相邻表示他们 & 后为0,否则就有一列为 1 ;如 101,001
					dp[i][j]=(dp[i][j]%mod+dp[i-1][k]%mod)%mod;//把上一行符合条件的加起来
				}
			}
		}
	}
	long long ans = 0;
	for(int i=0;i<=mn[n-1];i++) {//把最后的结果加起来.
		if(!vis[n-1][i]) continue;
		ans = (ans%mod+dp[n-1][i]%mod) %mod ;
	}
	cout<<ans<<endl;
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值