pku 2187(最远点对,旋转卡壳)

 1 #include <cstdio>
 2 #include <cstdlib>
 3 #include <iostream>
 4 
 5 using namespace std;
 6 
 7 const int N = 50005;
 8 
 9 //旋转卡壳(变化)求凸包直径O(n)
10 struct point {
11     int x, y;
12 }p[N];
13 
14 int dis(point A, point B) {
15     return (A.x - B.x) * (A.x - B.x) + (A.y - B.y) * (A.y - B.y);
16 }
17 
18 int crossProd(point A, point B, point C) {
19     return (B.x - A.x) * (C.y - A.y) - (B.y - A.y) * (C.x - A.x); 
20 }
21 
22 int cmp(const void *a, const void *b) {
23     point *c = (point *)a;
24     point *d = (point *)b;
25     int k = crossProd(p[0], *c, *d);
26     if (k<0 || !k&&dis(p[0], *c)>dis(p[0], *d)) return 1;
27     return -1;
28 }
29 
30 //计算凸包,输入点集p,点的个数n,输出凸包的顶点个数 
31 int Graham(point *p, int n) {
32     int x = p[0].x;
33     int y = p[0].y;
34     int mi = 0;
35     for (int i=1; i<n; ++i) {
36         if (p[i].y<y || p[i].y==y&&p[i].x<x) {
37             x = p[i].x;
38             y = p[i].y;
39             mi = i;
40         }
41     }
42     point tmp = p[0];
43     p[0] = p[mi];
44     p[mi] = tmp;
45     qsort(p+1, n-1, sizeof(point), cmp);
46     int top = 1;
47     for (int i=2; i<n; ++i) {
48         while (crossProd(p[top-1], p[top], p[i])<=0 && top>=1) --top;
49         p[++top] = p[i];
50     }
51     return top + 1;
52 }
53 
54 //计算凸包直径,输入凸包ch,顶点个数为n,按逆时针排列,输出直径的平方
55 int rotating_calipers(point *ch, int n) {
56     int q = 1, ans = 0;
57     ch[n] = ch[0];
58     for (int i=0; i<n; ++i) {
59         while (crossProd(ch[i+1], ch[q+1], ch[i]) > crossProd(ch[i+1], ch[q], ch[i])) q = (q + 1) % n;
60         ans = max(ans, max(dis(ch[i+1], ch[q+1]), dis(ch[i], ch[q])));
61     }
62     return ans;
63 }
64 
65 int main() {
66     int n;
67     while (scanf("%d", &n) != EOF) {
68         for (int i=0; i<n; ++i) scanf ("%d%d", &p[i].x, &p[i].y);
69         int top = Graham(p, n);
70         int ans = rotating_calipers(p, top);
71         printf ("%d\n", ans);
72     }
73     return 0;
74 }

 

posted on 2012-05-31 07:41  Try86  阅读(217)  评论(0)    收藏  举报