标签:动态规划
Time Limit: 2000MS | Memory Limit: 65536K | |
Total Submissions: 7578 | Accepted: 4045 |
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
Output
Sample Input
2 3 1 1 1 0 1 0
Sample Output
9
Hint
1 2 3 4
Source
/* 当上一行状态确定时,可以枚举下一行的状态; */ #include <stdio.h> #include <string.h> int a[15]; int dp[15][1<<13]; int main() { int n, m; int i, j, k, v; int sum, x, all; while(scanf("%d%d", &m, &n)!=-1) { memset(dp, 0, sizeof(dp)); memset(a, 0, sizeof(a)); for(i=1; i<=m; i++) for(j=1; j<=n; j++) { scanf("%d", &v); a[i] |= (v<<(n-j));//a[i]存状态。如 5 就代表 0101 } all = 1<<n; for(i=0; i<all; i++)//先枚举第一行的状态 { if((a[1]|i)==a[1] && (i&(i<<1))==0)//当此时状态i中没有把牛放在没有草的地方 即 a[i]|i==a[1],当此时状态没有左右相邻的情况即i&(i<<1). //因为dp是从上往下,从左往右,所以不用在意右边与下面的情况 dp[1][i]=1; } for(i=2; i<=m; i++) { for(j=0; j<all; j++) { x = dp[i-1][j]; if(x!=0) //当dp[i-1][j]==0时,代表这个点没草╮(╯_╰)╭ { for(k=0; k<all; k++) //枚举通过dp[i-1][j]这个状态到达后面的所有状态 { if((a[i]|k)==a[i] && (k&(k<<1))==0 && (k&j)==0)//当上一行的牛不和下一行相邻时就是(k&j)==0 { dp[i][k] += x; } } } } } sum = 0; for(i=0; i<all; i++) //最后一行的状态就是所求 sum += dp[m][i]; printf("%d\n", sum%100000000); } return 0; }
POJ 3254 Corn Fields //入门状压dp,布布扣,bubuko.com
标签:动态规划
原文地址:http://blog.csdn.net/ash_zheng/article/details/38560033