Surround the Trees

3 篇文章 0 订阅
1 篇文章 0 订阅

Description

  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=1, 无需长度。
当n=2, ans=dis*2。

你也许会问,凸包不会自动解决这问题吗?
注意:我们利用的是极角排序,排除时(进栈),至少要有三个数。

代码:

#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<cstring>
using namespace std;
int n,m;
struct P
{

    int x,y;

}p[101],q[101];
int i,j,top;
int cp(P p1,P p2,P p3)
{

    return (p1.x-p3.x)*(p2.y-p3.y)-(p2.x-p3.x)*(p1.y-p3.y);

}
double dist(P p1,P p2)
{

    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));

}
bool cmp(P a,P b)
{

    return cp(a,b,p[1])>0||cp(a,b,p[1])==0&&dist(p[1],a)>dist(p[1],b);

}
double ass;
int main()
{

    while(1)
    {

        memset(p,0,sizeof(p));
        memset(q,0,sizeof(q));
        top=0; ass=0;
        scanf("%d",&n);
        if (n==0) return 0;
        for (i=1;i<=n;i++)
        scanf("%d%d",&p[i].x,&p[i].y);
        if (n==1) {printf("0.00\n"); continue;}
        if (n==2) {printf("%.2lf\n",dist(p[1],p[2])*2); continue;}
        p[0]=p[1];
        for (i=2;i<=n;i++)
        if (p[0].y>p[i].y||p[0].y==p[i].y&&p[0].x>p[i].x)
        {

            p[0]=p[i];
            j=i;

        }
        p[0]=p[1];p[1]=p[j];p[j]=p[0];
        sort(p+2,p+n+1,cmp);
        q[top]=p[1];
        top++;
        q[top]=p[2];
        top++;
        q[top]=p[3];
        for (i=4;i<=n;i++)
        {

            while (cp(p[i],q[top],q[top-1])>=0) top--;
            top++;
            q[top]=p[i];

        }
        for (i=1;i<=top;i++)
        ass+=dist(q[i],q[i-1]);
        ass+=dist(q[top],q[0]);
        printf("%.2lf\n",ass);

    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值