HDU1392(凸包)

时间:2024-01-13 17:58:08

Surround the Trees

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 10299    Accepted Submission(s): 3991

Problem Description

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.

HDU1392(凸包)

There are no more than 100 trees.

Input

The input contains one or more data sets. At first line of each input data set is number of trees in this data set, it is followed by series of coordinates of the trees. Each coordinate is a positive integer pair, and each integer is less than 32767. Each pair is separated by blank.

Zero at line for number of trees terminates the input for your program.

Output

The minimal length of the rope. The precision should be 10^-2.

Sample Input

9
12 7
24 9
30 5
41 9
80 7
50 87
22 9
45 1
50 7

Sample Output

243.06

Source

Graham扫描法求凸包,凸包周长即为答案。
 //2016.10.2
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#define N 105
#define eps 1e-8 using namespace std; struct point
{
double x, y;
point(){}
point(double a, double b):x(a), y(b){}
point operator-(point a){//向量减法
return point(x-a.x, y-a.y);
}
point operator+(point a){//向量加法
return point(x+a.x, y+a.y);
}
double operator*(point a){//向量叉积
return x*a.y-y*a.x;
}
bool operator<(const point a)const{
if(fabs(x-a.x)<eps)return y<a.y;//浮点数的判等不能直接用‘==’直接比较
return x<a.x;
}
double len(){//向量的模
return sqrt(x*x+y*y);
}
}p[N], s[N];//p为点,s为栈 double cp(point a, point b, point o)//向量oa,ob叉积
{
return (a-o)*(b-o);
} void Convex(point *p, int &n)//Graham扫描法,栈内为所有凸包点
{
sort(p, p+n);
int top, m;
s[] = p[]; s[] = p[]; top = ;
for(int i = ; i < n; i++)//从前往后扫
{
while(top> && cp(p[i], s[top], s[top-])>=)top--;
s[++top] = p[i];
}
m = top;
s[++top] = p[n-];
for(int i = n-; i >= ; i--)//从后往前扫
{
while(top>m && cp(p[i], s[top], s[top-])>=)top--;
s[++top] = p[i];
}
n = top;
} int main()
{
int n;
while(scanf("%d", &n)!=EOF && n)
{
for(int i = ; i < n; i++)
scanf("%lf%lf", &p[i].x, &p[i].y);
sort(p, p+n);
int cnt = ;
for(int i = ; i < n; i++)//去掉重复的点
if(fabs(p[i].x-p[cnt].x)>eps || fabs(p[i].y-p[cnt].y)>eps)
p[++cnt] = p[i];
cnt++;
if(cnt == ){
printf("0.00\n");continue;
}else if(cnt==){
printf("%.2lf\n", (p[]-p[]).len());continue;
}
Convex(p, cnt);
double ans = ;
s[cnt] = s[];
for(int i = ; i < cnt; i++)ans+=(s[i+]-s[i]).len();
printf("%.2lf\n", ans);
} return ;
}