poj1038 Bugs Integrated, Inc.(状压DP)

版权声明:本文为博主原创文章,未经博主允许不得转载,除非先点了赞。 https://blog.csdn.net/A_Bright_CH/article/details/82865867

题意

在空余位置放入尽量多的2*3或3*2的矩形。

题解

状压DP
对于横着0,1没问题,对于竖着的,还需要一个2,所以状态就用三进制来表示。
对于一个横着的矩形:
1 1 1
0 0 0
对于一个竖着的矩形:
2 2
1 1
0 0
当上一行的状态为0时,这一行才可以放新的矩形。

实现时,可以在确定旧状态之后,搜索一个合法的新状态出来,这对于限制条件很多的时候很适用。

代码

#include<cmath>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=160,maxm=20,maxt=59060;

int n,m,k;
int ma[maxn][maxm];

int f[2][maxt];

int num[maxm];
void get_num(int x)
{
    for(int len=1;len<=m;len++)//debug所有num都要遍历一边,否则会有残余 
    {
        num[len]=x%3;
        x/=3;
    }
}

bool check(int x,int h,int l,int r)
{
    for(int i=l;i<=r;i++)
        if(num[i]>0) return false;
    for(int i=0;i<h;i++)
        for(int j=l;j<=r;j++)
            if(ma[x+i][j]==1) return false;
    return true;
}

int now[maxm];
void dfs(int x,int p,int t0,int t1,int cnt)//t0新状态 t1旧状态 
{
    if(p==0)
    {
        f[x&1][t0]=max(f[x&1][t0],f[x-1&1][t1]+cnt);//debug状态方程应是大小比较 
    }
    else
    {
        if(now[p]>0)
        {
            dfs(x,p-1,t0*3+now[p],t1,cnt);
            return ;
        }
        if(num[p]>0)
        {
            now[p]=num[p]-1;
            dfs(x,p-1,t0*3+now[p],t1,cnt);
            now[p]=0;
            return ;
        }
        dfs(x,p-1,t0*3,t1,cnt);
        if(p>=3 && check(x,2,p-2,p))
        {
            now[p]=now[p-1]=now[p-2]=1;
            dfs(x,p-1,t0*3+now[p],t1,cnt+1);
            now[p]=now[p-1]=now[p-2]=0;
        }
        if(p>=2 && check(x,3,p-1,p))
        {
            now[p]=now[p-1]=2;
            dfs(x,p-1,t0*3+now[p],t1,cnt+1);
            now[p]=now[p-1]=0;
        }
    }
}

int main()
{
    int T;scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&n,&m,&k);
        memset(ma,0,sizeof(ma));
        for(int i=1;i<=k;i++)
        {
            int x,y;scanf("%d%d",&x,&y);
            ma[x][y]=1;
        }
        
//        memset(num,0,sizeof(num));
        memset(f,-1,sizeof(f));
        f[0][0]=0;
        int mx=pow(3,m)-1;
        for(int i=1;i<=n;i++)
            for(int j=0;j<=mx;j++) if(~f[i-1&1][j])
            {
                get_num(j);
                //以下判断无意义,因为前面已有 ~f[i-1&1][j]==true
                /*bool flag=false;
                for(int k=1;k<=m;k++)
                    if(num[k]>1 && ma[i][k]==1){flag=true;break;}//debug 0也占位置 
                if(flag) continue;*/
                dfs(i,m,0,j,0);
            }
        
        printf("%d\n",f[n&1][0]);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/A_Bright_CH/article/details/82865867