Surround the Trees(凸包求周长)

Surround the Trees

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


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

题解:

当n==2时竟然还要特判,不等于二倍。。。
代码:
 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<cmath>
 5 #include<algorithm>
 6 using namespace std;
 7 const int INF=0x3f3f3f3f;
 8 struct Node{
 9     double x,y;
10     friend int operator <(Node a,Node b){
11         if(a.x<b.x||a.x==b.x&&a.y<b.y)return 1;
12         else return 0;
13     }
14 }a[110],ans[110];
15 double cj(Node a,Node b,Node c){
16     return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
17 }
18 double getl(Node a,Node b){
19     double x=a.x-b.x,y=a.y-b.y;
20     return sqrt(1.0*x*x+1.0*y*y);
21 }
22 int main(){
23     int N;
24     while(~scanf("%d",&N),N){
25         for(int i=0;i<N;i++)scanf("%lf%lf",&a[i].x,&a[i].y);
26         int k=0;
27         if(N==1){
28             puts("0.00");continue;
29         }
30         if(N==2){
31             printf("%.2lf\n",getl(a[0],a[1]));continue;//手一滑写成a[2]了,坑了10分钟 
32         }
33         sort(a,a+N);
34         for(int i=0;i<N;i++){//下凸包; 
35             while(k>1&&cj(ans[k-2],ans[k-1],a[i])<=0)k--;
36             ans[k++]=a[i];
37         }
38         int t=k;
39         for(int i=N-1;i>=0;i--){
40             while(k>t&&cj(ans[k-2],ans[k-1],a[i])<=0)k--;
41             ans[k++]=a[i];
42         }
43         double length=0;
44         
45         for(int i=0;i+1<k;i++){
46             length+=getl(ans[i],ans[i+1]);
47         }
48         printf("%.2lf\n",length);
49     }
50     return 0;
51 }

 

posted @ 2015-11-02 19:50  handsomecui  阅读(334)  评论(0编辑  收藏  举报