POJ 3254 Corn Fields (状压dp)

来源:互联网 发布:mac安装win10激活工具 编辑:程序博客网 时间:2024/05/16 15:26
Corn Fields
Time Limit: 2000MS Memory Limit: 65536KTotal Submissions: 10860 Accepted: 5690

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 31 1 10 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.

Source

USACO 2006 November Gold

题目链接:http://poj.org/problem?id=3254

题目大意:一个n行m列的矩阵,1表示可以放东西,0表示不能放,且要求相邻的两个格不能同时放,问有多少种放的方案

题目分析:n和m很小,直接状态压缩,sta[i]表示第i行的允许状态,dp[i][j]表示第i行状态为j时的方案数,对于每一行的状态s,直接通过判断s&(s>>1) 的值,若为1则该状态不可行,先预先处理第一行,之后的每行,判断完行状态再枚举上一行的状态,保证列上也不相邻,最后答案就是Σdp[n-1][i]  (0 <= i <= (1 << m) - 1)
#include <cstdio>int const MOD = 1e8;int n, m, a[20][20];int dp[16][1 << 16];int sta[1 << 16];int main(){scanf("%d %d", &n, &m);for(int i = 0; i < n; i++){for(int j = 0; j < m; j++){scanf("%d", &a[i][j]);if(a[i][j])sta[i] |= (1 << j);}}for(int i = 0; i < (1 << m); i++)if((i | sta[0]) == sta[0] && !(i & (i >> 1)))dp[0][i] = 1;for(int i = 1; i < n; i++)for(int j = 0; j < (1 << m); j++)if((j | sta[i]) == sta[i] && !(j & (j >> 1)))for(int k = 0; k < (1 << m); k++)if(dp[i - 1][k] && !(k & j))dp[i][j] = (dp[i][j] + dp[i - 1][k]) % MOD;int ans = 0;for(int i = 0; i < (1 << m); i++)ans = (ans + dp[n - 1][i]) % MOD;printf("%d\n", ans);}


0 0
原创粉丝点击