首页 > 代码库 > POJ 3254 Corn Fields(状压dp)
POJ 3254 Corn Fields(状压dp)
题目链接:http://poj.org/problem?id=3254
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 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
题意:
给出一个M*N的矩阵,元素为0表示这个地方不能种玉米,为1表示这个地方能种玉米,现在规定所种的玉米不能相邻,即每行或者没列不能有相邻的玉米,问一共有多少种种植方法。
详细见:http://www.cnblogs.com/buptLizer/archive/2012/08/22/2650717.html
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> #include <iostream> using namespace std; #define maxn 1<<13 #define mod 100000000 int N, M; int mapp[14], use[maxn]; int dp[13][maxn]; int num;//统计能表示状态的数量 int judge1(int x) { if(x&x<<1)//二进制中有两个1相邻 { return 0; } return 1; } int judge2(int x, int y) { if(mapp[x] & use[y])//相邻 return 0; return 1; } void init(int m) { for(int i = 0; i <= (1<<m)-1; i++) { if(judge1(i)) use[num++] = i; } } int main() { int x; while(~scanf("%d%d",&N,&M)) { num = 0; memset(dp,0,sizeof(dp)); memset(mapp,0,sizeof(mapp)); memset(use,0,sizeof(use)); for(int i = 1; i <= N; i++) { for(int j = 1; j <= M; j++) { scanf("%d",&x); if(x == 0) mapp[i]+=1<<(M-j);//讲二进制转换为十进制 } } init(M); for(int i = 0; i < num; i++) { if(judge2(1,i)) dp[1][i] = 1; } for(int i = 2; i <= N; i++) { for(int j = 0; j < num; j++) { if(!judge2(i,j))//i,j相邻 continue; for(int k = 0; k < num; k++) { // if(!judge2(i-1, k))//i-1和k相邻 // continue; if(!(use[j] & use[k]))//不相邻 { dp[i][j]=(dp[i][j]+dp[i-1][k])%mod; } } } } int ans = 0; for(int i = 0; i < num; i++) { ans = (ans+dp[N][i])%mod; } printf("%d\n",ans); } return 0; }
POJ 3254 Corn Fields(状压dp)