【最大凸多边形周长】HDU - 1392 H - Surround the Trees

HDU - 1392 H - Surround the Trees 

There are a lot of trees in an area. A peasant wants to buy a rope to surround all these trees. So at first he must know the minimal required length of the rope. However, he does not know how to calculate it. Can you help him? 
The diameter and length of the trees are omitted, which means a tree can be seen as a point. The thickness of the rope is also omitted which means a rope can be seen as a line. 



There are no more than 100 trees. 

Input

The input contains one or more data sets. At first line of each input data set is number of trees in this data set, it is followed by series of coordinates of the trees. Each coordinate is a positive integer pair, and each integer is less than 32767. Each pair is separated by blank. 

Zero at line for number of trees terminates the input for your program. 

Output

The minimal length of the rope. The precision should be 10^-2. 

Sample Input

9 
12 7 
24 9 
30 5 
41 9 
80 7 
50 87 
22 9 
45 1 
50 7 
0 

Sample Output

243.06

这道题给你n个点,问你怎样用最小的绳子长度把树给包围住

就是问你n个点的最大凸多边形周长

有一个bug,特判 n==2 时

就是两点间的距离

然而 实际包围我个人认为应该要绕一圈

hin无奈啊

#include <bits/stdc++.h>
using namespace std;
const int maxn =1005;
const double pi=atan(1.0)*4;
struct point
{
    int x,y;
}pt[maxn],ans[maxn];
int cnt;

bool cmp(const point &a,const point &b)  //左下的点优先
{
    if(a.x==b.x) return a.y<b.y;
    return a.x<b.x;
}

int cross(point p0,point p1,point p2)  //计算叉乘
{
    return (p1.x-p0.x)*(p2.y-p0.y)-(p1.y-p0.y)*(p2.x-p0.x);
}

double length(point a,point b)   //计算两点间距离
{
    return sqrt(1.00*(a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}

void convex(int n)  //将凸包的点放入ans结构体,放入的点就是构成凸包的点
{
    sort(pt,pt+n,cmp);
    cnt=0;
    for(int i=0;i<n;i++)  //下凸包
    {
        while(cnt>1&&cross(ans[cnt-2],ans[cnt-1],pt[i])<=0) cnt--;  //如果新增的点与前两点够不成凸型,则把上一点删去
        ans[cnt++]=pt[i];
    }
    int key=cnt;
    for(int i=n-2;i>=0;i--) //上凸包
    {
        while(cnt>key&&cross(ans[cnt-2],ans[cnt-1],pt[i])<=0) cnt--;
        ans[cnt++]=pt[i];
    }
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        if(n==0) break;
        for(int i=0;i<n;i++)
        {
            scanf("%d%d",&pt[i].x,&pt[i].y);
        }
        double res=0;
        convex(n);
        for(int i=0;i<cnt-1;i++)
        {
            res+=length(ans[i],ans[i+1]);  //按顺序算出凸包上点的距离
        }
        if(n==2)
        {
            printf("%.2lf\n",length(pt[0],pt[1]));
        }
        else printf("%.2lf\n",res);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_41037114/article/details/82947161