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==2的时候,只用连住就行了,好尴尬(至今不理解)。

代码:

#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
using namespace std;
const int maxn=109;
struct node
{
    double x,y;
} edge[maxn],ans[maxn];

bool cmp(node a,node b)
{
    if(a.x==b.x) return a.y<b.y;
    return a.x<b.x;
}
double mul(node a,node b,node c)
{
    return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
double dis(node a,node b)
{
    return sqrt((a.x*1.0-b.x)*(a.x*1.0-b.x)+(a.y*1.0-b.y)*(a.y*1.0-b.y));
}
int solve(int n)
{
    int len=0;
    for(int i=0; i<n; i++)
    {
        while(len>1&&mul(ans[len-2],ans[len-1],edge[i])<=0) len--;
        ans[len++]=edge[i];
    }
    int k=len;
    for(int i=n-1; i>=0; i--)
    {
        while(len>k&&mul(ans[len-2],ans[len-1],edge[i])<=0) len--;
        ans[len++]=edge[i];
    }
    return len-1;
}
int main()
{
    int t,n;
    while(~scanf("%d",&n),n)
    {
        for(int i=0; i<n; i++)
            scanf("%lf%lf",&edge[i].x,&edge[i].y);

        sort(edge,edge+n,cmp);//排序

        int len=solve(n);
        double ans1=0;
        for(int i=0; i<len; i++)
            ans1+=dis(ans[i],ans[i+1]);
        if(len==2)//n==2要特判
            ans1/=2.0;
        printf("%.2lf\n",ans1);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nhl19961226/article/details/80056114
今日推荐