poj 1185

来源:互联网 发布:node gzip压缩 编辑:程序博客网 时间:2024/05/22 17:04

链接: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