POJ - 3254 - Corn Fields(dp & 状压)

POJ - 3254 - Corn Fields

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 3
1 1 1
0 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.
题目链接
题目说给你一个地图,1表示能种草,0表示不能。牛不能在相邻场地吃草,问种草的方法。
这也是一个状压dp的题目,和炮兵阵地很像,但是做法略有点不同。
同样也是先要把一行中所有可行的方案都记录下来,这里我们申请一个dp二维数组,dp[i][j],i 代表第 i 行,j代表第 j 种状态。然后就是与上一行进行比较,枚举每一种状态,找出可行的方案,然后继续向下找。

#include <algorithm>
#include <cstdio>
#include <cstring>
const int mod = 1e8;
const int N = 13;
int dp[N][1 << N];
int beg[N];

int main()
{
    int n, m, t;
    while(~scanf("%d%d", &n, &m))
    {
        memset(dp, 0, sizeof(dp));
        memset(beg, 0, sizeof(beg));
        for(int i = 0; i < n; i++)
        {
            for(int j = 0; j < m; j++)
            {
                scanf("%d", &t);
                if(t) beg[i] += (1 << j);
            }
        }

        for(int i = 0; i < (1 << m); i++) //求出第一行的合法状态数目
            if((beg[0] | i) == beg[0] && !(i & i >> 1))
                dp[0][i] = 1;

        for(int i = 1; i < n; i++)
        {
            for(int j = 0; j < (1 << m); j++)
            {  //枚举本行状态
                if(((beg[i] | j) == beg[i]) && !(j & j >> 1))
                {
                    for(int k = 0; k < (1 << m); k++) { //枚举上一行的状态
                        if(!(j & k)) //根据上一行递推出本行
                            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);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_40788897/article/details/81813035