【洛谷 P1879】[USACO 06Nov]Corn Fields G【状压DP】

题目描述

题目
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.

农场主John新买了一块长方形的新牧场,这块牧场被划分成M行N列(1 ≤ M ≤ 12; 1 ≤ N ≤ 12),每一格都是一块正方形的土地。John打算在牧场上的某几格里种上美味的草,供他的奶牛们享用。

遗憾的是,有些土地相当贫瘠,不能用来种草。并且,奶牛们喜欢独占一块草地的感觉,于是John不会选择两块相邻的土地,也就是说,没有哪两块草地有公共边。

John想知道,如果不考虑草地的总块数,那么,一共有多少种种植方案可供他选择?(当然,把新牧场完全荒废也是一种方案)

输入格式

第一行:两个整数M和N,用空格隔开。

第2到第M+1行:每行包含N个用空格隔开的整数,描述了每块土地的状态。第i+1行描述了第i行的土地,所有整数均为0或1,是1的话,表示这块土地足够肥沃,0则表示这块土地不适合种草。

输出格式

一个整数,即牧场分配总方案数除以 100 , 000 , 000 100,000,000 100,000,000的余数。

输入输出样例

输入 #1

2 3
1 1 1
0 1 0

输出 #1

9

分析:

状压 D P DP DP( z h e n zhen zhen)( d e de de)( e e e)( x i n xin xin) ! ! ! ! !!!!
状压 D P DP DP说白了就是暴力枚举 但是 t a ta ta用的是二进制
这道题:
用一个二进制数 i i i 如果 i i i的某一位上为 1 1 1 则那一列
f [ i ] [ j ] f[i][j] f[i][j]表示前i行在 j j j个状态下的最多方案数
动态能量转移方程:
f [ i ] [ j ] = ( f [ i ] [ j ] + f [ i − 1 ] [ k ] ) f[i][j]=(f[i][j]+f[i-1][k])%mod f[i][j]=(f[i][j]+f[i1][k])
j j j是第 i i i行的状态 k k k是第 i − 1 i-1 i1行的状态 g [ i ] g[i] g[i]判断i状态是否存在
条件为: i i i的左右有没有 1 1 1 i i i的位置上存在


CODE:

#include<iostream>
#include<cstdio>
#define MOD 100000000  //%%%
using namespace std;
int n,m,f[13][1<<12],g[1<<12],a[13][13],OvO[13],ans=0; 
int main(){
    
    
	scanf("%d%d",&n,&m);
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			scanf("%d",&a[i][j]);  //我蠢死了改了半天结果读入读错。。
	for(int i=1;i<=n;i++)
		for(int j=1;j<=m;j++)
			OvO[i]=(OvO[i]<<1)+a[i][j];  //预处理贡献
	for(int i=0;i<(1<<m);i++)
		if(!(i&(i<<1))&&!(i&(i>>1)))  //i左右没有1 则1上有牛
		{
    
    
			g[i]=1;  //标记
			if((i&OvO[1])==i) f[1][i]=1;  //第一行
		}
	for(int qwq=2;qwq<=n;qwq++)  //枚举
		for(int j=0;j<(1<<m);j++)
			if(((j&OvO[qwq-1])==j)&&g[j])  //上一行
				for(int k=0;k<(1<<m);k++)
					if(((k&OvO[qwq])==k)&&!(j&k)&&g[k])  //这一行有
						f[qwq][k]=(f[qwq][k]+f[qwq-1][j])%MOD;  //DP
	for(int i=0;i<(1<<m);i++)
		ans=(ans+f[n][i])%MOD;
	printf("%d",ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/dgssl_xhy/article/details/108131368
今日推荐