pku 2187(最远点对)

 1 /*
 2 *  题目要求:求一组点中距离最远的一对的距离 
 3 *  解法:凸包+枚举 
 4 */
 5 
 6 #include <cmath>
 7 #include <cstdio>
 8 #include <cstdlib>
 9 #include <iostream>
10 
11 using namespace std;
12 
13 const int N = 50005;
14 
15 struct point {
16     int x;
17     int y;
18 }p[N], stack[N];
19 
20 int dis(point A, point B) {
21     return (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y);
22 }
23 
24 int crossProd(point A, point B, point C) {
25     return (B.x-A.x)*(C.y-A.y) - (B.y-A.y)*(C.x-A.x);
26 }
27 
28 int cmp(const void *a, const void *b) {
29     point *c = (point *)a;
30     point *d = (point *)b;
31     int k = crossProd(p[0], *c, *d);
32     if (k<0 || (!k&&dis(p[0], *c)>dis(p[0], *d))) return 1;
33     return -1;
34 }
35 
36 int Graham(int n) {
37     int x = p[0].x;
38     int y = p[0].y;
39     int mi = 0;
40     for (int i=1; i<n; ++i) {
41         if (p[i].y<y || (p[i].y==y&&p[i].x<x)) {
42             x = p[i].x;
43             y = p[i].y;
44             mi = i;
45         }
46     } 
47     point tmp = p[mi];
48     p[mi] = p[0];
49     p[0] = tmp;
50     qsort(p+1, n-1, sizeof(point), cmp);
51     p[n] = p[0];
52     for (int i=0; i<2; ++i) stack[i] = p[i];
53     int top = 1;
54     for (int i=2; i<n; ++i) {
55         while (crossProd(stack[top-1], stack[top], p[i])<=0 && top>=1) --top;
56         stack[++top] = p[i];
57     }
58     return top;
59 }
60 
61 int solve(int n) {
62     int top = Graham(n);
63     int s, maxL = 0;
64     for (int i=0; i<top; ++i) {
65         for (int j=i+1; j<=top; ++j) {
66             s = dis(stack[i], stack[j]);
67             if (s > maxL) maxL = s;
68         }
69     }
70     return maxL;
71 }
72 
73 int  main() {
74     int n;
75     while (scanf("%d", &n) != EOF) {
76         for (int i=0; i<n; ++i) scanf ("%d%d", &p[i].x, &p[i].y);
77         int ans = solve(n);
78         printf ("%d\n", ans);
79     }
80     return 0;
81 }

 

posted on 2012-04-27 07:26  Try86  阅读(243)  评论(0)    收藏  举报