您的位置:首页 > 其它

The Fortified Forest - POJ 1873(状态枚举+求凸包周长)

2015-10-25 10:34 417 查看
题目大意:有个国王他有一片森林,现在他想从这个森林里面砍伐一些树木做成篱笆把剩下的树木围起来,已知每个树都有不同的价值还有高度,求出来砍掉那些树可以做成篱笆把剩余的树都围起来,要使砍伐的树木的价值最小,如果有价值相同的尽量使砍伐的树木少一些。

分析:因为树木的数量是比较少的,所以枚举所有的状态,判断那个树需要砍那个树不需要,然后按照要求求出来答案即可。

代码如下:

==============================================================================================

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;

const double EPS = 1e-10;
const int MAXN = 20;
const int oo = 1e9+7;

int vi[MAXN], li[MAXN], sta[MAXN], top;

struct point
{
double x, y;

point(double x=0, double y=0):x(x), y(y){}
point operator - (const point &t)const{
return point(x-t.x, y-t.y);
}
double operator *(const point &t)const{
return x*t.x + y*t.y;
}
double operator ^(const point &t)const{
return x*t.y - y*t.x;
}
}p[MAXN], date[MAXN];
int Sign(double t)
{
if(t > EPS)return 1;
if(fabs(t) < EPS)return 0;
return -1;
}
double Dist(point a, point b)
{
return sqrt((a-b)*(a-b));
}
bool cmp(point a, point b)
{
int t = Sign((a-p[0])^(b-p[0]));

if(t == 0)
return Dist(a, p[0]) < Dist(b, p[0]);
return t > 0;
}
void Graham(int N)
{
int k=0;

for(int i=0; i<N; i++)
{
if(p[k].y>p[i].y || (Sign(p[k].y-p[i].y)==0 && p[k].x > p[i].x))
k = i;
}
swap(p[0], p[k]);
sort(p+1, p+N, cmp);

sta[0]=0, sta[1]=1, top=1;

if(N < 2)
{
top = N-1;
return ;
}

for(int i=2; i<N; i++)
{
while(top>0 && Sign((p[i]-p[sta[top]])^(p[sta[top-1]]-p[sta[top]])) <= 0)
top--;
sta[++top] = i;
}
}
bool Solve(int bitNum, int N, int &val, int &nOne, double &lastLen)
{
int cut_val=0, cnt=0, cut_len=0;

for(int i=0; i<N; i++)
{
if(bitNum & 1)
{
cut_val += vi[i];
cut_len += li[i];
}
else
p[cnt++] = date[i];
bitNum >>= 1;
}

Graham(cnt);

double len=0;
sta[++top] = sta[0];

for(int i=0; i<=top; i++)
{
len += Dist(p[sta[i]], p[sta[i+1]]);
}

if(Sign(cut_len-len) >= 0 && (val > cut_val || (val==cut_val&&nOne > N-cnt)))
{
lastLen = cut_len - len;
val = cut_val;
nOne = N-cnt;
return true;
}
return false;
}

int main()
{
int N, t=1;

while(scanf("%d", &N), N)
{
int val=oo, ans, nOne=oo;
double lastLen;

for(int i=0; i<N; i++)
scanf("%lf%lf%d%d", &date[i].x, &date[i].y, &vi[i], &li[i]);

int Len = (1<<N)-1;

for(int i=1; i<Len; i++)
{
if(Solve(i, N, val, nOne, lastLen) == true)
ans = i;
}
if(t!=1)printf("\n");
printf("Forest %d\n", t++);
printf("Cut these trees:");
for(int i=1; ans; i++)
{
if(ans & 1)
printf(" %d", i);
ans >>= 1;
}
printf("\nExtra wood: %.2f\n", lastLen);
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: