`
阿尔萨斯
  • 浏览: 4183372 次
社区版块
存档分类
最新评论

POJ 2187 Beauty Contest(凸包:最远点对距离)

 
阅读更多

POJ 2187 Beauty Contest(凸包:最远点对距离)

http://poj.org/problem?id=2187

题意:

平面上给你n个点,要你求出这n个点中的任意两点的最远距离的平方?

分析:

点集的最远点对一定是在凸包上的两个顶点,本题先求出点集的凸包,然后暴力枚举凸包上任意两个顶点的距离即可.(不会超时)本来用旋转卡壳应该是最好的,但是还没有学,只能暴力枚举了…

本题所有数据都是int,最后结果也只要返回距离的平方就行.这明摆着再说”如果全都用int计算,能加快计算速度”. 当然我还是用double做的.

还要注意凸包退化成2点的情况.

AC代码: C++提交,G++提交有double精度问题,会出错

#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
using namespace std;
const double eps=1e-10;
int dcmp(double x)
{
    if(fabs(x)<eps) return 0;
    return x<0?-1:1;
}
struct Point
{
    double x,y;
    Point(){}
    Point(double x,double y):x(x),y(y){}
    bool operator<(const Point &B)const
    {
        return dcmp(x-B.x)<0 || (dcmp(x-B.x)==0 && dcmp(y-B.y)<0);
    }
    bool operator==(const Point &B)const
    {
        return dcmp(x-B.x)==0 && dcmp(y-B.y)==0;
    }
};
typedef Point Vector;
Vector operator-(Point A,Point B)
{
    return Vector(A.x-B.x,A.y-B.y);
}
double Cross(Vector A,Vector B)
{
    return A.x*B.y-A.y*B.x;
}
int ConvexHull(Point *p,int n,Point *ch)
{
    sort(p,p+n);
    n=unique(p,p+n)-p;
    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;
}

const int maxn=50000+5;
Point p[maxn],ch[maxn];
double dist2(Point a,Point b)//返回距离的平方
{
    return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
int main()
{
    int n;
    while(scanf("%d",&n)==1)
    {
        for(int i=0;i<n;++i)
            scanf("%lf%lf",&p[i].x,&p[i].y);
        int m=ConvexHull(p,n,ch);
        if(m==2)
        {
            printf("%.0lf",dist2(ch[0],ch[1]));
            continue;
        }
        else
        {
            double ans=-1e10;
            for(int i=0;i<m;i++)
            for(int j=i+1;j<m;j++)
                ans=max(ans,dist2(ch[i],ch[j]));
            printf("%.0lf\n",ans);//要用C++提交,G++有精度问题
        }
    }
    return 0;
}

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics