HDU - 1392 Surround the Trees (凸包入门裸题,模板)

版权声明:本文为博主原创文章,转载请附上注明就行_(:з」∠)_。 https://blog.csdn.net/vocaloid01/article/details/82773021

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 <bits/stdc++.h>

using namespace std;

typedef long long LL;

const int MAXN = 105;

struct Point{
	LL x,y;
	Point(){}
	Point(LL _x,LL _y):x(_x),y(_y){}
	Point operator - (const Point& b)const {
		return Point(x - b.x,y - b.y);
	}
	bool operator < (const Point& b)const {
		if(x == b.x)return y < b.y;
		return x < b.x;
	}
}points[MAXN],ch[MAXN];

LL Cross(const Point& a,const Point& b){
	if(a.x * b.y - a.y * b.x <= 0)return 0;//如果不希望在凸包的边上有输入点把<=改成<。 
	else return 1;
}

double Distance(const Point& a,const Point& b){
	return sqrt((a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y));
}

int Andrew(int size){
	int m = 0;
	for(int i=1 ; i<=size ; ++i){
		while(m >= 2 && !Cross(ch[m-1]-ch[m-2],points[i]-ch[m-2]))--m;
		ch[m++] = points[i];
	}
	int k = m;
	for(int i=size-1 ; i>0 ; --i){//注意如果points下标是0到(size-1)那么这里是(size-2)到0。 
		while(m > k && !Cross(ch[m-1]-ch[m-2],points[i]-ch[m-2]))--m;
		ch[m++] = points[i];
	}
	return m;
}

int main(){
	
	int N;
	while(scanf("%d",&N) && N){
		for(int i=1 ; i<=N ; ++i){
			scanf("%lld %lld",&points[i].x,&points[i].y);
		}
		if(N == 2){
			printf("%.2f\n",Distance(points[1],points[2]));
			continue;
		}
		sort(points+1,points+1+N);
		
		int num = Andrew(N);
		double re = 0;
		
		for(int i=1 ; i<num ; ++i){
			re += Distance(ch[i-1],ch[i]);
		}
		re += Distance(ch[num-1],ch[0]);
		printf("%.2f\n",re);
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/vocaloid01/article/details/82773021