Surround the Trees:
http://acm.hdu.edu.cn/showproblem.php?pid=1392
1 /* 2 2015.5 3 Surround the Trees 4 5 */ 6 7 #include<iostream> 8 #include<math.h> 9 #include<stdlib.h> 10 #define MAXD 110 11 using namespace std; 12 13 typedef struct 14 { 15 double x, y; 16 }point; 17 point Tree[MAXD], Result[MAXD]; 18 int N, P; 19 20 /* 21 叉乘 22 P1 x P2 23 >0 : P1 is clockwise from P2 with respect to (0,0) 24 <0 : counterclockwise (即P1在P2左边) 25 =0 : collinear 26 */ 27 double cross(double x1, double y1, double x2, double y2) 28 { 29 return x1 * y2 - x2 * y1; 30 } 31 32 // 按 y坐标从低到高排序,若 y相等则按 x坐标排序 33 int cmp(const void *_p, const void *_q) 34 { 35 point *p = (point *)_p, *q = (point *)_q; 36 if (p->y == q->y) 37 return p->x < q->x ? -1 : 1; 38 39 return p->y < q->y ? -1 : 1; 40 } 41 42 double Distance(double x, double y, double x1, double y1) 43 { 44 double temp1 = (x - x1)*(x - x1); 45 double temp2 = (y - y1)*(y - y1); 46 return sqrt(temp1+temp2); 47 } 48 49 double sqr(double x) 50 { 51 return x * x; 52 } 53 54 // 是否删除 55 int del(int top, int i) 56 { 57 if (cross(Result[top].x - Result[top - 1].x, Result[top].y - Result[top - 1].y, 58 Tree[i].x - Result[top].x, Tree[i].y - Result[top].y) < 0) 59 return 1; 60 return 0; 61 } 62 63 int graham() 64 { 65 int i, mint, top = 1; 66 Result[0] = Tree[0]; 67 Result[1] = Tree[1]; 68 for (i = 2; i < N; i++) 69 { 70 while (top && del(top, i)) 71 --top; 72 Result[++top] = Tree[i]; 73 } 74 mint = top; 75 Result[++top] = Tree[N - 2]; 76 for (i = N - 3; i >= 0; i--) 77 { 78 while (top != mint && del(top, i)) 79 --top; 80 Result[++top] = Tree[i]; 81 } 82 return top; 83 } 84 85 int main() 86 { 87 int i; 88 double sum; 89 while (1) 90 { 91 cin >> N; 92 if (!N) 93 break; 94 95 for (i = 0; i < N; i++) 96 cin >> Tree[i].x >> Tree[i].y; 97 98 // 快排 99 qsort(Tree, N, sizeof(Tree[0]), cmp); 100 sum = 0; 101 102 if (N == 1) 103 cout << "0.00\n"; 104 else if (N == 2) 105 { 106 sum = Distance(Tree[0].x,Tree[0].y,Tree[1].x,Tree[1].y); 107 cout << sum << endl; 108 } 109 else 110 { 111 P = graham(); 112 for (i = 0; i < P; i++) 113 sum += Distance(Result[i].x, Result[i].y, Result[i + 1].x, Result[i + 1].y); 114 cout << sum << endl; 115 } 116 } 117 118 return 0; 119 }
时间: 2024-11-09 00:53:40