Surround the Trees 7.1.4

Surround the Trees

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 183    Accepted Submission(s): 93


 

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<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;

const int MAXN = 100 + 10;
struct Point {
	int x, y;
}p[MAXN], stack[MAXN];
double dist(Point a, Point b){
	return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
double cross(Point pi, Point pj, Point pk){
	//pj-pk * pi-pk
	return (pj.x - pk.x) * (pi.y - pk.y) - (pj.y - pk.y) * (pi.x - pk.x);
}
int cmp(Point a, Point b){
	double d = cross(a, b, p[0]);
	if(d == 0) return dist(p[0], a) > dist(p[0], b);
	else return d > 0;
}
int main(){
	int n;
	while(scanf("%d", &n) && n){
		for(int i = 0; i < n; i++){
			scanf("%d%d", &p[i].x, &p[i].y);
			if(i){
				if(p[i].y < p[0].y){
					swap(p[i].x, p[0].x);
					swap(p[i].y, p[0].y);
				}
				else if(p[i].y == p[0].y && p[i].x < p[0].x){
					swap(p[i].x, p[0].x);
				}
			}
		}
		if(n == 1) {
			printf("0.00\n");
			continue;
		}
		else if(n == 2) {
			printf("%.2lf\n", dist(p[0], p[1]));
			continue;
		}
		sort(p+1, p+n, cmp);
		stack[0] = p[0];
		stack[1] = p[1];
		int top = 1;
		for(int i = 2; i < n; i++){
			while(top && cross(p[i], stack[top], stack[top-1]) >= 0){
				top--;
			}
			stack[++top] = p[i];
		}
		while(top && cross(p[0], stack[top], stack[top-1]) >= 0) top--;
		double ans = 0.0;
		for(int i = 0; i < top; i++){
			ans += dist(stack[i], stack[i+1]);
		}
		ans += dist(stack[top], stack[0]);
		printf("%.2lf\n", ans);
		
	}
	return 1;
}

猜你喜欢

转载自blog.csdn.net/bruce_teng2011/article/details/38645209