Surround the Trees
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 13238 Accepted Submission(s): 5116
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
凸包问题:求能把所有点包进去的边长的周长
Graham扫描法
1、先选出点集中y坐标最小的点记为, 如果y坐标相同则相同点中x坐标最小的点。
2、把按照极角(polar angle)从小到大排序(以原点为极点),极角相同的点按照到的距离从小到大排序。
3、把压入栈。
4、遍历剩下的点,while循环把发现不是凸包顶点的点移除出去,因为当逆时针遍历凸包时,我们应该在每个顶点向左转。因此当while循环发现在一个顶点处没有向左转时,就把该顶点移除出去。至于如何判断向左向右则是根据叉积来判断,前面我们已经解决过这个问题了
#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
struct point{
double x,y;
point friend operator -(point a,point b){
return {a.x-b.x,a.y-b.y};
}
}p[105],Stack[105];
double X(point a,point b){//求叉乘
return a.x*b.y - a.y*b.x;
}
double multi(point p1,point p2,point p3){//
return X(p2-p1,p3-p1);
}
double dis(point a,point b){//
point c=a-b;
return sqrt(c.x*c.x+c.y*c.y);
}
//极角排序
int cmp(point a,point b){
double x=X(a-p[1],b-p[1]);
if(x>0) return 1;
if(x==0&&dis(a,p[1])<dis(b,p[1])) return 1;
return 0;
}
int main(){
int N;
while(scanf("%d",&N)&&N){
for(int i=1;i<=N;i++){
scanf("%lf%lf",&p[i].x,&p[i].y);
}
if(N==1){
printf("0.00\n");
continue;
}else if(N==2){
printf("%.2lf\n",dis(p[1],p[2]));
continue;
}
int k=1;
double sum=0;
for(int i=2;i<=N;i++){
if(p[i].y<p[k].y||(p[i].y==p[k].y&&p[i].x<p[k].x))
k=i;
}
swap(p[1],p[k]);
sort(p+2,p+N+1,cmp);
Stack[1]=p[1];
Stack[2]=p[2];
int tot=2;
for(int i=3;i<=N;i++){
while(tot>=2&&multi(Stack[tot-1],Stack[tot],p[i])<=0)
tot--;
Stack[++tot]=p[i];
}
Stack[tot+1]=Stack[1];
for(int i=1;i<=tot;i++){
sum+=dis(Stack[i],Stack[i+1]);
}
printf("%.2lf\n",sum);
}
return 0;
}