【HDU 1329】Surround the Trees 凸包周长

Problem 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

代码:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
#include<stack>
#include<cmath>
#include<set>
#include<map>
using namespace std;
#define inf 0x3f3f3f3f
#define ll long long
 

struct Point 
{
    double x, y;
    Point friend operator - (Point a, Point b) 
	{
        return {a.x - b.x, a.y - b.y};
	}
}p[105], Stack[105];

double X(Point a, Point b) 
{
    return a.x * b.y - a.y * b.x;
}

double multi(Point p1, Point p2, Point p3) 
{
    return X(p2 - p1, p3 - p1);
}

double dis(Point a, Point b) 
{
    Point c = a - b;
  	  return sqrt(c.x * c.x + c.y * c.y);
}
int cmp(Point a, Point b) 
{
    double x = X(a - p[1], b - p[1]);

    if(x > 0) 
		return 1;
    if(x == 0 && dis(a, p[1]) < dis(b, p[1])) 
		return 1;
    return 0;
}

int main()
{
    int n,i;
    while(cin>>n&&n)
    {
        for(i = 1; i <= n; i++)
            cin>>p[i].x>>p[i].y;
        if(n == 1)
		{
            cout<<"0.00"<<endl;
            continue;
        }
        else if(n == 2)
		{
            printf("%.2lf\n",dis(p[1], p[2]));
            continue;
        }
        int k = 1;
        for(i = 2; i <= n; i++)
            if(p[i].y<p[k].y || (p[i].y == p[k].y && p[i].x < p[k].x))
                k = i;
        swap(p[1], p[k]);
        sort(p + 2, p + n + 1, cmp);
        Stack[1] = p[1];
        Stack[2] = p[2];
        int tot = 2;
        for(i = 3; i <= n; i++) 
		{
            while(tot >= 2 && multi(Stack[tot - 1], Stack[tot], p[i]) <= 0) 
				tot--;
            Stack[++tot] = p[i];
        }
        Stack[tot + 1] = Stack[1];
        double sum = 0;
        for(i = 1; i <= tot; i++) 
        	sum += dis(Stack[i],Stack[i + 1]);  
        printf("%.2lf\n", sum);
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Xylon_/article/details/81589206