求最远点对,输出距离
1 #include<iostream> 2 #include <math.h> 3 #include <algorithm> 4 #include<stdio.h> 5 6 using namespace std; 7 8 #define eps 1e-8 9 #define zero(x) (((x)>0?(x):-(x))<eps) 10 struct point{ double x, y; }p[100005], convex[100005]; 11 12 double xmult(point p1, point p2, point p0) 13 { 14 return (p1.x - p0.x)*(p2.y - p0.y) - (p2.x - p0.x)*(p1.y - p0.y); 15 } 16 17 int dist2(point a, point b) 18 { 19 return (a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y); 20 } 21 22 point p1, p2; 23 int graham_cp(const void* a, const void* b){ 24 double ret = xmult(*((point*)a), *((point*)b), p1); 25 return zero(ret) ? (xmult(*((point*)a), *((point*)b), p2) > 0 ? 1 : -1) : (ret > 0 ? 1 : -1); 26 } 27 void _graham(int n, point* p, int& s, point* ch){ 28 int i, k = 0; 29 for (p1 = p2 = p[0], i = 1; i<n; p2.x += p[i].x, p2.y += p[i].y, i++) 30 if (p1.y - p[i].y>eps || (zero(p1.y - p[i].y) && p1.x > p[i].x)) 31 p1 = p[k = i]; 32 p2.x /= n, p2.y /= n; 33 p[k] = p[0], p[0] = p1; 34 qsort(p + 1, n - 1, sizeof(point), graham_cp); 35 for (ch[0] = p[0], ch[1] = p[1], ch[2] = p[2], s = i = 3; i < n; ch[s++] = p[i++]) 36 for (; s>2 && xmult(ch[s - 2], p[i], ch[s - 1]) < -eps; s--); 37 } 38 39 int wipesame_cp(const void *a, const void *b) 40 { 41 if ((*(point *)a).y < (*(point *)b).y - eps) return -1; 42 else if ((*(point *)a).y >(*(point *)b).y + eps) return 1; 43 else if ((*(point *)a).x < (*(point *)b).x - eps) return -1; 44 else if ((*(point *)a).x >(*(point *)b).x + eps) return 1; 45 else return 0; 46 } 47 48 int _wipesame(point * p, int n) 49 { 50 int i, k; 51 qsort(p, n, sizeof(point), wipesame_cp); 52 for (k = i = 1; i < n; i++) 53 if (wipesame_cp(p + i, p + i - 1) != 0) p[k++] = p[i]; 54 return k; 55 } 56 57 int graham(int n, point* p, point* convex, int maxsize = 1, int dir = 1){ 58 point* temp = new point[n]; 59 int s, i; 60 n = _wipesame(p, n); 61 _graham(n, p, s, temp); 62 for (convex[0] = temp[0], n = 1, i = (dir ? 1 : (s - 1)); dir ? (i < s) : i; i += (dir ? 1 : -1)) 63 if (maxsize || !zero(xmult(temp[i - 1], temp[i], temp[(i + 1) % s]))) 64 convex[n++] = temp[i]; 65 delete[]temp; 66 return n; 67 } 68 69 int rotating_calipers(point *ch, int n) 70 { 71 int q = 1, ans = 0; 72 ch[n] = ch[0]; 73 for (int p = 0; p < n; p++) 74 { 75 while (xmult(ch[p + 1], ch[q + 1], ch[p]) > xmult(ch[p + 1], ch[q], ch[p])) 76 q = (q + 1) % n; 77 ans = max(ans, max(dist2(ch[p], ch[q]), dist2(ch[p + 1], ch[q + 1]))); 78 } 79 return ans; 80 } 81 int main() 82 { 83 int n; 84 cin >> n; 85 for (int i = 0; i < n; i++) 86 { 87 scanf("%lf%lf", &p[i].x, &p[i].y); 88 } 89 int size = graham(n, p, convex, 1, 0); 90 //cout << rotating_calipers(convex, size) << endl; 91 printf("%.8lf\n",sqrt(rotating_calipers(convex, size))); 92 return 0; 93 }