hdu 1932 凸包求周长
Surround the Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 14456 Accepted Submission(s): 5591
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.
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 0
Sample Output
243.06
#include<bits/stdc++.h>
#define PI acos(-1.0)
#define MAXN 10100
using namespace std;
struct point
{
double x,y;
double len;
} s[MAXN],pt[MAXN],Point_A; // s中保存最终结果 ,pt起始点 ,Point_A左下起始点
int NUM; // 凸包上总点数
double Cross(point a,point b,point c) //求叉积我(ab,ac)
{
return (b.x - a.x)*(c.y - a.y) - (b.y - a.y)*(c.x - a.x);
}
double dis(point a,point b) // 求两点间的距离
{
return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}
void Find(int n) //查找起始点,左下
{
int temp = 0;
point a = pt[0];
for(int i=0; i<n; i++)
{
if(pt[i].y < a.y || pt[i].y == a.y && pt[i].x < a.x)
{
a = pt[i];
temp = i;
}
}
pt[temp] = pt[0];
pt[0] = a;
Point_A = a; // 保存起始点
}
bool cmp (point a,point b) // 极角排序
{
double x = Cross(Point_A,a,b);
if(x > 0.0) return true;
else if(x < 0.0) return false;
a.len = dis(Point_A,a);
b.len = dis(Point_A,b);
return a.len < b.len;
}
int Graham(int n) //扫描法求解凸包
{
int top = 2;
s[0] = pt[0];
s[1] = pt[1];
s[2] = pt[2];
pt[n] = pt[0];
for(int i=3; i<=n; i++)
{
while(Cross(s[top-1],s[top],pt[i]) <= 0 && top > 1) top--;
s[++top] = pt[i];
}
return top; //表示凸包中的点数
}
void init(int n) // 排序,求凸包
{
Find(n);
sort(pt,pt+n,cmp);
NUM = Graham(n);
}
double Perimeter() // 求凸包周长
{
double sum = 0.0;
for(int i=1; i<NUM; i++)
{
sum += dis(s[i-1],s[i]);
}
sum += dis(s[NUM-1],s[0]);
return sum;
}
int main()
{
int T,n,m,l,i,j;
double sum1,sum2;
while(~scanf("%d",&n)&&n)
{
memset(s,0,sizeof s);
memset(pt,0,sizeof pt);
for(i=0; i<n; i++)
{
scanf("%lf%lf",&pt[i].x,&pt[i].y);
}
init(n);
if(n==1) printf("0.00\n");
else if(n==2) printf("%.2lf\n",dis(pt[0],pt[1]));
else
{
sum2 = Perimeter();
printf("%.2lf\n",sum2);
}
}
return 0;
}
double Area() //计算面积
{
double sum = 0.0;
for(int i=1; i<NUM-1; i++)
{
sum += Cross(s[0],s[i],s[i+1]);
}
sum = fabs(sum)/2;
return sum;
}