Corn Fields POJ

来源:互联网 发布:4g那家网络制式好 编辑:程序博客网 时间:2024/06/14 15:52

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.

大致题意:给你一个m*n的01矩阵,0表示该格子不能放牛,1表示可以,相邻的两个格子不能同时放牛,问有多少种放牛的方案

思路:

代码如下

#include <cstdio>  #include <cstring>  #include <algorithm> #include <iostream> #include <vector>using namespace std;  #define ll long long   const int mod=1e9;int n,m;int  dp[15][1<<13];//dp[i][j]表示第i行的状态为j时的方案数有多少种int mp[15];int check(int x)//判断状态x在二进制表示下是否有相邻的两个位置上都是1,即判断当前状态x是否合法{    if(x&(x<<1)) return 0;    return 1;}int main ()  {        cin>>n>>m;    memset(dp,0,sizeof(dp));    memset(mp,0,sizeof(mp));    for(int i=0;i<n;i++)    for(int j=0;j<m;j++)    {        int x;        cin>>x;        if(x==1)        mp[i]=mp[i]|(1<<j);//记录当前第i行第j列能放牛          }    dp[0][0]=1;    for(int state=0;state<(1<<m);state++)//第0行        if(((mp[0]|state)==mp[0])&&check(state))        dp[0][state]=1;    for(int r=1;r<n;r++)//枚举第r行         for(int sta1=0;sta1<(1<<m);sta1++)//枚举第r行的状态        {            if(((mp[r]|sta1)==mp[r])&&check(sta1))//如果对于第r行该状态sta1合法             for(int sta2=0;sta2<(1<<m);sta2++)//枚举上一行r-1的状态            {                if((sta1&sta2))  continue;//如果sta1和sta2两个状态有冲突(上下两个相邻的格子也不能同时放牛)                dp[r][sta1]=(dp[r][sta1]+dp[r-1][sta2])%mod;            }         }     ll ans=0;    for(int i=0;i<(1<<m);i++)            ans=(ans+dp[n-1][i])%mod;    printf("%lld\n",ans);    return 0;  }  
原创粉丝点击