您的位置:首页 > Web前端 > AngularJS

poj 2836 Rectangular Covering(状压dp)

2016-07-15 16:18 363 查看
问题描述

n points are given on the Cartesian plane. Now you have to use some rectangles whose sides are parallel to the axes to cover them. Every point must be covered. And a point can be covered by several rectangles. Each rectangle should cover at least
two points including those that fall on its border. Rectangles should have integral dimensions. Degenerate cases (rectangles with zero area) are not allowed. How will you choose the rectangles so as to minimize the total area of them?

输入

The input consists of several test cases. Each test cases begins with a line containing a single integer
n (2 ≤ n ≤ 15). Each of the next n lines contains two integers
x, y (−1,000 ≤ x, y ≤ 1,000) giving the coordinates of a point. It is assumed that no two points are the same as each other. A single zero follows the last test case.

输出

Output the minimum total area of rectangles on a separate line for each test case.

样例输入

2
0 1
1 0
0


样例输出

1

我们先把所有的矩形保存下来,然后问题就变成了选择若干个矩形,覆盖所有的点,且使面积最小.
用s二进制表示状态,dp[s]表示在s状态下的最小面积,即覆盖s中的顶点的状态下的最小面积,因此我们最后要求的是
dp[(1<<n)-1].状态转移方程为:
dp[s1]=min(dp[s1,dp[s2]+area(i,j))
其中s1,s2表示两个状态,s1是由s2加上(i,j)这个矩形得到的状态。area表示(i,j)的面积.
代码如下:
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace std;

int x[16],y[16];
const int INF=999999;

int n;

struct node
{
int area;
int cover;
}no[16*16];

int AREA(int i,int j)
{
if(i==j)return 0;
int l=abs(x[i]-x[j]);
if(l==0)l=1;
int w=abs(y[i]-y[j]);
if(w==0)w=1;
return l*w;
}

int dp[1<<16];

bool is_in(int k,int i,int j)
{
return (x[k]-x[i])*(x[k]-x[j])<=0&&(y[k]-y[i])*(y[k]-y[j])<=0;
}

int main()
{
while(scanf("%d",&n),n)
{
for(int i=0;i<n;i++)
{
scanf("%d %d",&x[i],&y[i]);
}
int top=0;
for(int i=0;i<n;i++)
for(int j=i+1;j<n;j++)
{
no[top].area=AREA(i,j);
no[top].cover=(1<<i)|(1<<j);

for(int k=0;k<n;k++)
{
if(is_in(k,i,j))
no[top].cover|=(1<<k);
}
top++;
}

for(int s=0;s<1<<n;s++)
dp[s]=INF;
dp[0]=0;

for(int s=0;s<1<<n;s++)
{
for(int v=0;v<top;v++)
if(s|no[v].cover!=s)
dp[s|no[v].cover]=min(dp[s|no[v].cover],dp[s]+no[v].area);
}
printf("%d\n",dp[(1<<n)-1]);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: