您的位置:首页 > 其它

HDU 1392 Surround the Trees(凸包周长)

2014-10-17 20:37 274 查看
HDU 1392 Surround the Trees(凸包周长)
http://acm.hdu.edu.cn/showproblem.php?pid=1392
题意:

二维平面上有一些树,要你用绳子把这些树包围起来,问你最少需要多长的绳子? 树和绳子的半径忽略.

分析:

直接求出凸包,然后算凸包的周长即可.不过要注意,当n==1时,输出0.
当n==2时,只要输出两点的距离即可
.

此题不会出现多点重合.

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 &rhs)const
    {
        return dcmp(x-rhs.x)==0 && dcmp(y-rhs.y)==0;
    }
    bool operator<(const Point &rhs)const
    {
        return dcmp(x-rhs.x)<0 || (dcmp(x-rhs.x)==0 && dcmp(y-rhs.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;
}

//点间距离
double Length(Point A,Point B)
{
    return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y));
}

//求凸包
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);
        if(m==1) printf("%0.00\n");
        else if(m==2) printf("%.2lf\n",Length(ch[0],ch[1]));
        else
        {
            double ans=0;
            for(int i=0;i<m;i++)
                ans+= Length(ch[i],ch[(i+1)%m]);
            printf("%.2lf\n",ans);
        }
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: