HDU-1392 Surround the Trees(凸包+周長)

鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1392

題意:求凸包的周長。

思路:凸包裸題。

#include <cstdio>
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
const int N = 1e2+10;
const double eps = 1e-8;
int sgn(double x)
{
	if(fabs(x)<eps) return 0;
	else if(x<0) return -1;
	else return 1;
}
struct Point
{
	double x,y;
	Point(){}
	Point(double x,double y):x(x),y(y){}
	Point operator -(const Point& b)const//相減 
	{
		return Point(x-b.x,y-b.y);
	}
	double operator ^(const Point& b)const//叉乘 
	{
		return x*b.y-y*b.x;
	}
	double operator *(const Point& b)const//點乘 
	{
		return x*b.x+y*b.y;
	}
}ps[N],st[N];
int n,pos,top;
double x;
bool cmp(const Point& a,const Point& b)
{
	x=(a-ps[1])^(b-ps[1]);
	if(sgn(x)==0)
	{
		if(a.y==b.y)
			return a.x<b.x;
		else return a.y<b.y;
	}
	else if(x>0) return 1;
	else return 0;
}
bool check(Point a,Point b,Point c)
{
	x=(b-a)^(c-a);
	return x<0||sgn(x)==0;
}
double dist(Point a,Point b)
{
	return sqrt((b-a)*(b-a));
}
double circum()
{
	++top;
	if(top==2)
	{
		return dist(st[0],st[1]);
	}
	double  ans=0;
	for(int i=0;i<top;i++)
	{
		ans+=dist(st[i],st[(i+1)%top]);
	}
	return ans;
}
int main(void)
{
	while(~scanf("%d",&n)&&n)
	{	
		pos=1;		
		for(int i=1;i<=n;i++)
		{
			scanf("%lf%lf",&ps[i].x,&ps[i].y);
			if(ps[i].y<ps[pos].y || (ps[i].y==ps[pos].y&&ps[i].x<ps[pos].x))
				pos=i;
		}
		if(n==1)
		{
			puts("0.00");
			continue;
		}
		swap(ps[1],ps[pos]);
		sort(ps+2,ps+n+1,cmp);
		top=-1;
		st[++top]=ps[1];
		st[++top]=ps[2];
		for(int i=3;i<=n;i++)
		{
			while(top>1&&check(st[top-1],st[top],ps[i])) 
				top--;			
			st[++top]=ps[i];
		}		
		printf("%.2f\n",circum());	
	}
	
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章