poj2836 状态压缩dp

自己的做法是枚举i,j作为顶点的矩形,然后再更新状态S,但是这种做法是错误的

正解是先把所有矩形对求出来,然后枚举状态S,每个处理每个状态时再枚举已经求出的矩形对,用旧状态更新新状态

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<math.h>
#include<map>
#include<queue>
using namespace std;
struct node
{
    int x,y;
}p[25];
int main()
{
    int n;
    while(cin>>n && n)
    {
        int state[120],dp[1<<15],area[120];
        int cnt=0;
        for(int i=0;i<n;i++)
        cin>>p[i].x>>p[i].y;
        for(int i=0;i<n;i++)
        {
            for(int j=i+1;j<n;j++)
            {
                state[cnt]=(1<<i|1<<j);
                for(int k=0;k<n;k++)
                {
                    if((p[i].x-p[k].x)*(p[k].x-p[j].x)>=0 && (p[i].y-p[k].y)*(p[k].y-p[j].y)>=0)//当一个点在这个矩形中时,把这个矩形的包含点的状态更新
                    state[cnt]|=1<<k;
                }
                if(p[i].x==p[j].x)//特判
                area[cnt]=abs(p[i].y-p[j].y);
                else if(p[i].y==p[j].y)
                area[cnt]=abs(p[i].x-p[j].x);
                else
                {
                    area[cnt]=abs(p[i].y-p[j].y)*abs(p[i].x-p[j].x);
                }
                cnt++;
            }
        }
        for(int i=0;i<(1<<n);i++)
        dp[i]=0xfffffff;
        dp[0]=0;
        for(int i=0;i<(1<<n);i++)//好好想想为什么后枚举矩形?
        {
            for(int j=0;j<cnt;j++)
            {
                dp[i|state[j]]=min(dp[i|state[j]],dp[i]+area[j]);
            }
        }
        cout<<dp[(1<<n)-1]<<endl;
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/zsben991126/p/10369305.html