Surround the Trees(hdu 1392)

依旧是凸包题

Graham 扫描法:

但是有一些细节要注意,就是输入数据只有一个点或者两个点的时候。

#include 
#include 
#include 
using namespace std;

struct point
{
	int x, y;
}p[110], stack[110];
int top;


double dis(point a, point b)
{
	return (double)sqrt(1.0 * ((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y)));	
}

int multi(point a, point b, point c)
{
	return (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
} 

int cmp(point a, point b)
{
	int m = multi(a, b, p[0]);
	if(m > 0)
		return 1;
	if(m == 0 && dis(a, p[0]) < dis(b, p[0]))
		return 1;
	return 0; 
}

void input(int t)
{
	int k = 0;
	for(int i = 0; i < t; i++)
	{
		scanf("%d %d", &p[i].x, &p[i].y);
		if(p[k].x > p[i].x || (p[k].x == p[i].x && p[k].y > p[i].y))
			k = i;
	}
	point temp = p[0];
	p[0] = p[k];
	p[k] = temp;
	sort(p + 1, p + t, cmp);
}

void graham(int t)
{
	top = 2;
	stack[0] = p[0];
	stack[1] = p[1];
	stack[2] = p[2];
	for(int i = 3; i < t; i++)
	{
		while(top > 0 && multi(stack[top], p[i], stack[top - 1]) < 0)
			top --;
		stack[++top] = p[i];		
	}
}


int main (void)
{
	int t;
	while(scanf("%d", &t))
	{
		if(t == 0)
			break;
		input(t);
		if(t == 1)
		{//特判
			printf("0.00\n");
			continue;
		}
		if(t == 2)
		{//特判
			printf("%.2lf\n", dis(p[0], p[1]));
			continue;
		}
		graham(t);
		double sum = 0;
		for(int i = 0; i < top; i++)
			sum += dis(stack[i], stack[i + 1]);
		sum += dis(stack[0], stack[top]);
		printf("%.2lf\n", sum);
	}
	return 0;
}



你可能感兴趣的:(计算几何,HDU)