题目链接:http://poj.org/problem?id=2187
方法一:凸包O(nlogn)+枚举O(n^2)
- #include<cstdio>
- #include<cmath>
- #include<iostream>
- #include<algorithm>
- using namespace std;
- #define N 51000
- struct Point
- {
- double x, y;
- Point(double x = 0, double y = 0) : x(x), y(y) {}
- };
- typedef Point Vector;
- Vector operator - (Point A, Point B) {return Vector(A.x-B.x, A.y-B.y);}
- Point point[N];
- Point convex[N];
- double dist(Point a, Point b)
- {
- return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
- }
- double Cross(Vector A, Vector B)
- {
- return A.x*B.y - A.y*B.x;
- }
- int cmp(Point a, Point b)
- {
- if(a.x != b.x) return a.x < b.x;
- return a.y < b.y;
- }
- int ConvexHull(Point *p, int n, Point *ch)
- {
- sort(p, p+n, cmp);
- int m = 0;
- for(int i = 0; i < n; i++)
- {
- while(m > 1 && Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2]) <= 0) m--;
- ch[m++] = p[i];
- }
- int k = m;
- for(int i = n-2; i >= 0; i--)
- {
- while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
- ch[m++] = p[i];
- }
- if(n > 1) m--;
- return m;
- }
- int main()
- {
- int n;
- scanf("%d", &n);
- for(int i = 0; i < n; i++)
- scanf("%lf %lf", &point[i].x, &point[i].y);
- int len = ConvexHull(point, n, convex);
- double ans = 0;
- for(int i = 0; i < len; i++)
- for(int j = i+1; j < len; j++)
- ans = max(ans, dist(convex[i],convex[j]));
- printf("%.0lf\n", ans);
- return 0;
- }
方法二:凸包O(nlogn)+旋转卡壳O(n)
- #include<cmath>
- #include<cstdio>
- #include<cstring>
- #include<iostream>
- #include<algorithm>
- using namespace std;
- #define N 50000
- //定义点
- struct Point
- {
- double x, y;
- Point(double x = 0, double y = 0) : x(x), y(y) {}
- };
- typedef Point Vector;
- Point p[N+100];
- Point ch[N+100];
- Vector operator - (Point A, Point B) {return Vector(A.x-B.x, A.y-B.y);}
- double Dot(Vector A, Vector B){return A.x*B.x + A.y*B.y;}
- double Length(Vector A){return Dot(A, A);}
- double Cross(Vector A, Vector B){return A.x*B.y - A.y*B.x;}
- bool cmp(Point a, Point b)
- {
- if(a.x == b.x) return a.y < b.y;
- else return a.x < b.x;
- }
- int ConvexHull(Point p[], int n, Point ch[])
- {
- sort(p,p+n,cmp);
- int m = 0;
- for(int i = 0; i < n; i++)
- {
- while(m > 1 && Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2]) <= 0) m--;
- ch[m++] = p[i];
- }
- int k = m;
- for(int i = n-2; i >= 0; i--)
- {
- while(m > k && Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2]) <= 0) m--;
- ch[m++] = p[i];
- }
- if(n > 1) m--;
- return m;
- }
- double slove(Point ch[], int n)
- {
- int q = 1;
- double ans = 0;
- for(int i = 0; i < n-1; i++)
- {
- while(Cross(ch[i+1]-ch[i],ch[q]-ch[i]) < Cross(ch[i+1]-ch[i],ch[q+1]-ch[i]))
- q = (q+1)%n;
- ans = max(ans, max(Length(ch[q]-ch[i+1]), Length(ch[q]-ch[i])));
- }
- return ans;
- }
- int main ()
- {
- //freopen("in.txt", "r", stdin);
- int n;
- scanf("%d", &n);
- for(int i = 0; i < n; i++)
- scanf("%lf %lf", &p[i].x, &p[i].y);
- int len = ConvexHull(p, n, ch);
- double ans = slove(ch, len);
- printf("%.0f\n", ans);
- return 0;
- }