题意:在一个平面内给出了许多点,求出所有点中两点最长距离的平方。
方法:graham法求凸包,枚举
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
using namespace std;
#define N 50005
struct Point
{
int x, y;
}p[N], res[N];
int Cross(Point a, Point b, Point c)
{
return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
int dist(Point a, Point b)
{
return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
int cmp(const void *a, const void *b)
{
Point c = *(Point *)a;
Point d = *(Point *)b;
int t = Cross(p[0], c, d);
if (t) return -t;
return dist(p[0], d)-dist(p[0], c);
}
int graham(int n)//求凸包
{
int i, j, k, top = 2;
j = 0;
for (i=1; i<n; i++)
{
if ( p[i].y<p[j].y || (p[i].y==p[j].y && p[i].x<p[j].x) )
j = i;
}
if (j)
{
Point temp = p[j];
p[j] = p[0];
p[0] = temp;
}
qsort(p+1, n-1, sizeof(p[0]), cmp);
res[0] = p[0];
res[1] = p[1];
res[2] = p[2];
for (int i=3; i<n; i++)
{
while ( top>1 && Cross(res[top-1], res[top], p[i])<=0 )
--top;
res[++top] = p[i];
}
return top;
}
int Ans(int n)//通过枚举求平面最远点
{
int ans = 0;
for (int i=0; i<n; i++)
for (int j=i+1; j<=n; j++)
{
int temp = dist(res[i], res[j]);
if (temp > ans)
ans = temp;
}
return ans;
}
int main()
{
int n, t;
while (~scanf("%d", &n))
{
for (int i=0; i<n; i++)
scanf("%d%d", &p[i].x, &p[i].y);
printf("%d\n", Ans( graham(n) ));
}
return 0;
}