1. 程式人生 > >Surround the Trees

Surround the Trees

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

    }

}