poj 1185

链接:http://poj.org/problem?id=1185
分析:一道经典的状压dp,坑点是如果开dp[100][1<<10][1<<10]会爆内存,其实根本不用开这么大的空间。只需将所有可能的状态找到就行了,用这个代码:

 int num = 0;
    for(int i=0; i<(1<<10); i++)
        if(judge_one(i))
            num++;
    cout<<num<<endl;

发现num只有60。 按60开空间就绝不会爆炸了!
代码:

#include <iostream>
#include <algorithm>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int N = 10;
int dp[101][60][60],mapp[101],mark[1<<N];
int num(int n);
bool judge_one(int x);
bool judge_two(int x, int y);
int main()
{

   // freopen("in.txt","r",stdin);
    char str[15];
    int n,m,i,j,k,l;
    while(cin>>n>>m)
    {
        int len = 0;
        memset(dp,0,sizeof(dp));
        memset(mapp,0,sizeof(mapp));
        for(i=1; i<=n; i++)
        {
            cin>>str;
            for(j=0; j<m; j++)
            {
                int tep = (str[j]=='P'? 1 : 0);
               // cout<<tep;
                mapp[i] += (tep<<(m-j-1));
            }
        }
         int ans = 0;
        for(i=0; i<(1<<m); i++)
          if(judge_one(i))
          {
              if((mapp[1]&i) == i)
              {
                  dp[1][0][len] = num(i);
                  ans = max(ans,dp[1][0][len]);
              }
              mark[len++] = i;
          }

        for(i=2; i<=n; i++)
        for(int x=0; x<len; x++) //这次状态
            if((mapp[i]&mark[x]) == mark[x])
            {
                for(int y=0; y<len; y++) //上次状态
                {
                    int maxx = -1;
                    if(judge_two(mark[x],mark[y]) == false) continue;
                    for(int z=0; z<len; z++) //上上次的状态
                    {
                        if(judge_two(mark[x],mark[z]) == false) continue;
                        if(judge_two(mark[y],mark[z]) == false) continue;
                        maxx = max(maxx,dp[i-1][z][y]);
                    }
                    if(maxx != -1)
                        dp[i][y][x] = maxx + num(mark[x]);
                    ans = max(ans,dp[i][y][x]);
                }
            }

             cout<<ans<<endl;
    }
    return 0;
}
int num(int n)
{
    int ans =0 ;
    while(n)
    {
        if(n&1) ans++;
        n = n>>1;
    }
    return ans;
}
bool judge_one(int x)
{
    if(x&(x<<1)) return false;
    if(x&(x<<2)) return false;
    return true;
}
bool judge_two(int x, int y)
{
    if(x&y) return false;
    return true;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值