您的位置:首页 > 其它

zoj 1453 Surround the Trees(凸包求周长)

2014-07-25 16:19 337 查看
链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=453

Time Limit: 2 Seconds Memory Limit: 65536 KB
There are a lot of trees in an area. A peasant wants to buy a rope to surround all these trees. So at first he must know the minimal required length of the rope. However, he does not know how to calculate it. Can you help him?

The diameter and length of the trees are omitted, which means a tree can be seen as a point. The thickness of the rope is also omitted which means a rope can be seen as a line.

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

#define  MAX 110
const double eps=1e-6;

typedef struct
{
double x,y;
}point;

point c[MAX];

bool dy(double x,double y)
{
return x>y+eps;
}
bool xy(double x,double y)
{
return x<y-eps;
}
bool xyd(double x,double y)
{
return x<y+eps;
}
bool dyd(double x,double y)
{
return x>y-eps;
}
bool dd(double x,double y)
{
return fabs(x-y)<eps;
}

double crossProduct(point a,point b,point c)
{
return (c.x-a.x)*(b.y-a.y)-(c.y-a.y)*(b.x-a.x);
}
double dist(point a,point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

bool cmp(point a,point b)
{
if(dd(a.y,b.y))
return xy(a.x,b.x);
return xy(a.y,b.y);
}
bool cmp1(point a,point b)
{
double len=crossProduct(c[0],a,b);
if(dd(len,0.0))
return xy(dist(c[0],a),dist(c[0],b));
return xy(len,0.0);
}

point stk[MAX];
int top;

double dis()
{
double sum=0.0;
for(int i=0;i<top;i++)
{
sum+=dist(stk[i],stk[i+1]);
}
sum+=dist(stk[top],stk[0]);
return sum;
}

double Graham(int n)
{
sort(c,c+n,cmp);
sort(c+1,c+n,cmp1);
top=0;
stk[top++]=c[0];
stk[top++]=c[1];
stk[top++]=c[2];
top--;
for(int i=3;i<n;i++)
{
while(1)
{
point a,b;
a=stk[top];
b=stk[top-1];
if(xyd(crossProduct(a,b,c[i]),0.0))
{
top--;
}
else
break;
}
stk[++top]=c[i];
}
return dis();
}

int main()
{
int i,j,k,t;
int n,m;
while(scanf("%d",&n)!=EOF&&n)
{
for(i=0;i<n;i++)
{
scanf("%lf%lf",&c[i].x,&c[i].y);
}
if(n==1)
{
printf("0.00\n");
//continue;
}
else if(n==2)
{
printf("%.2lf\n",2*dist(c[0],c[1]));
//continue;
}
else
{
printf("%.2lf\n",Graham(n));
}
}
return 0;
}


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