ZOJ 1453 Surround the Trees(凸包入门:求凸包周长)

ZOJ 1453 Surround the Trees(凸包入门:求凸包周长)

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1453

题意:

       平面上有n个点,要你求出这n个点的凸包的周长.

分析:

       直接用刘汝佳的模板求出凸包即可,在ch[i]数组中按顺序保存了所有的凸包点,然后循环一边计算周长即可.

AC代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
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(y-B.y)==0;
    }
    bool operator<(const Point& B)const
    {
        return dcmp(x-B.x)<0 || (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=100+5;
Point p[maxn],ch[maxn];
int main()
{
    int n;
    while(scanf("%d",&n)==1 && n)
    {
        for(int i=0;i<n;i++)
            scanf("%lf%lf",&p[i].x,&p[i].y);
        int m=ConvexHull(p,n,ch);
        double ans=0;//总周长
        ch[m]=ch[0];
        for(int i=0;i<m;i++)
            ans+= sqrt((ch[i].x-ch[i+1].x)*(ch[i].x-ch[i+1].x)+(ch[i].y-ch[i+1].y)*(ch[i].y-ch[i+1].y));
        printf("%.2lf\n",ans);
    }
    return 0;
}

你可能感兴趣的:(Algorithm,算法,ACM,计算几何)