1. 程式人生 > >【最大凸多邊形周長】HDU

【最大凸多邊形周長】HDU

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;
}