hdu 1392【Surround the Trees】

凸包

代码如下:
 1 #include  <cstdio>
 2 #include  <algorithm>
 3 #include <cstring>
 4 #include <cmath>
 5 using namespace std;
 6 
 7 struct node
 8 {
 9     int x,y;
10 }p[1000],stack[1000];
11 int n,top;
12 
13 double dis(node &a,node &b)
14 {
15     return sqrt(1.0*(a.x - b.x) * (a.x - b.x) + 1.0 * (a.y-b.y) * (a.y - b.y));
16 }
17 
18 double polar(node &a,node &b,node & o)
19 {
20     return 1.0*(a.x - o.x) * (b.y - o.y) - 1.0*(b.x - o.x) * (a.y - o.y);
21 }
22 
23 bool cmp(node& a,node& b)
24 {
25     double temp = polar(a,b,p[0]);
26     
27     if(temp == 0)
28     {
29         return dis(a,p[0]) < dis(b,p[0]);
30     }
31 
32     return temp > 0;
33 }
34 
35 void convex_hull()
36 {
37     stack[0] = p[0];
38     stack[1] = p[1];
39     top = 1;
40     for(int i = 2;i < n;i ++)
41     {
42         while(top && polar(p[i],stack[top],stack[top-1]) >= 0)
43         {
44             top -- ;
45         }
46         stack[++top] = p[i];
47     }
48 }
49 
50 int main()
51 {
52     while(scanf("%d",&n),n)
53     {
54         for(int i = 0;i < n; i ++)
55         {
56             scanf("%d%d",&p[i].x,&p[i].y);
57             if(i)
58             {
59                 if(p[i].y < p[0].y)
60                 {
61                     swap(p[i].y,p[0].y);
62                     swap(p[i].x,p[0].x);
63                 }
64                 else if(p[i].y == p[0].y && p[i].x < p[0].x)
65                 {
66                     swap(p[i].x,p[0].x);
67                 }
68             }
69         }
70         if(n == 1)
71         {
72             printf("0.00\n");
73             continue;
74         }
75         else if(n == 2)
76         {
77             printf("%.2lf\n",dis(p[1],p[0]));
78             continue;
79         }
80 
81         sort(p + 1,p + n,cmp);
82         convex_hull();
83 
84         double sum = 0;
85         for(int i = 1;i <= top;i ++)
86         {
87             sum += dis(stack[i],stack[i-1]);
88         }
89         sum += dis(stack[0],stack[top]);
90         printf("%.2lf\n",sum);
91     }
92 
93     return 0;
94 }

可以当做模板来用

原文地址:https://www.cnblogs.com/Shirlies/p/2510870.html