[poj 3254] Corn Fields 状压dp
Posted whileskies的博客
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[poj 3254] Corn Fields 状压dp相关的知识,希望对你有一定的参考价值。
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 3There 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.
4
#include <iostream> #include <stdio.h> #include <cstring> #include <algorithm> using namespace std; #define LL long long #define mod 100000000 int M, N; const int MaxN = (1<<12)+5; const int MaxM = 12; LL dp[MaxM][MaxN]; int farm[13][13]; bool GetBit(int i, int k) { return (1 & (i >> k)); } bool nowok(int n, int r) { for (int i = 0; i < N; i++) { if (farm[r][N-1-i] == 0 && GetBit(n, i) == 1) return 0; } for (int i = 0; i < 11; i++) { if (GetBit(n, i) == 1 && GetBit(n, i+1) == 1) return 0; } return 1; } bool preok(int p, int n) { for (int i = 0; i < 12; i++) { if (GetBit(p, i) && GetBit(n, i)) return 0; } return 1; } int main() { //freopen("1.txt", "r", stdin); scanf("%d%d", &M, &N); for (int i = 0; i < M; i++) for (int j = 0; j < N; j++) { scanf("%d", &farm[i][j]); } int sp = 1<<N; memset(dp, 0, sizeof(dp)); for (int i = 0; i < sp; i++) { if (nowok(i, 0)) dp[0][i] = 1; } for (int i = 1; i < M; i++) { for (int j = 0; j < sp; j++) { if (nowok(j, i)) { for (int k = 0; k < sp; k++) { if (dp[i-1][k] && preok(k, j)) { dp[i][j] = (dp[i][j]+dp[i-1][k])%mod; dp[i][j] %= mod; } } } } } int ans = 0; for (int i = 0; i < sp; i++) { if (dp[M-1][i]) { ans = (ans+dp[M-1][i])%mod; ans %= mod; } } printf("%d\n", ans); return 0; }
以上是关于[poj 3254] Corn Fields 状压dp的主要内容,如果未能解决你的问题,请参考以下文章