hdu1392标准求凸包模板

来源:互联网 发布:java io深入 编辑:程序博客网 时间:2024/06/16 00:52
标准求凸包模板
#include<stdio.h>
#include<math.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 103
#define EPS 1e-8
struct point
{
double x;
double y;
}p[N];
point cur;
int s[N];
int top;
int dblcmp(double d)
{
if(fabs(d)<EPS)return 0;
return d>0?1:-1;
}
double det(double x1,double y1,double x2,double y2)
{
return x1*y2-x2*y1;
}
double cross(point a,point b,point c)
{
return det(a.x-c.x,a.y-c.y,b.x-c.x,b.y-c.y);
}
double dis(point a,point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool cmp1(point a,point b)
{
if(a.y==b.y)return a.x<b.x;
return a.y<b.y;
}
bool cmp2(point a,point b)
{
double d=cross(a,b,cur);
if(d>0)return true;
else if(d<0)return false;
else
{
double dis1=dis(a,cur);
double dis2=dis(b,cur);
if(dis1<dis2)return true;
else return false;
}
}
void graham_scan(int n)
{
sort(p,p+n,cmp1);
cur=p[0];
sort(p+1,p+n,cmp2);
top=-1;
s[++top]=0;
s[++top]=1;
s[++top]=2;
for(int i=3;i<n;i++)
{
while(top>=1&&dblcmp(cross(p[s[top]],p[i],p[s[top-1]]))<=0)
{
top--;
}
s[++top]=i;
}
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
for(int i=0;i<n;i++)
{
scanf("%lf%lf",&p[i].x,&p[i].y);
}
if(n<2)
{
printf("0.00\n");
continue;
}
else if(n==2)
{
printf("%.2lf\n",dis(p[0],p[1]));
continue;
}
graham_scan(n);
double ans=0.0;
for(int i=0;i<top;i++)
{
ans+=dis(p[s[i]],p[s[i+1]]);
}
ans+=dis(p[0],p[s[top]]);
printf("%.2lf\n",ans);
}
return 0;
}
0 0
原创粉丝点击