二维凸包模版——旋转卡壳法

#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
const int MAXN = 109;
const double eps = 1e-6;
struct point{
    double x,y;
}p[MAXN],h[MAXN];

inline double distance(const point &p1,const point &p2){
    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}//   求两点之间的距离
inline double multiply(const point &sp,const point &ep,const point &op){
      return ((sp.x-op.x)*(ep.y-op.y)-(ep.x-op.x)*(sp.y-op.y));
}//判断sp,ep,op是否满足左转
int cmp(const void *a,const void *b){//按极角排序
    point *p1 = (point *)a;
    point *p2 = (point *)b;
    double t = multiply(*p2,*p1,p[0]);
    if(t>eps) return 1;
    else if(fabs(t)<=eps) 
	{
	if(distance(p[0],*p1)>distance(p[0],*p2)) return 1;
	else return -1;
	}
    else return -1;
}
void anglesort(point p[],int n){//找到最左下方的点
    int i,k=0;
    point temp;
    for(i=1;i<n;i++)
        if(p[i].x<p[k].x ||( (p[i].x==p[k].x) && (p[i].y<p[k].y)))
            k=i;
    temp=p[0],p[0]=p[k],p[k]=temp;
    qsort(p+1,n-1,sizeof(point),cmp);
}
void Graham_scan(point p[],point ch[],int n,int &len){//建立凸包
    int i,top=2;
    anglesort(p,n);
    if(n<3){
        for(i=0,len=n;i<n;i++) ch[i]=p[i];
        return;
    }
    ch[0]=p[0],ch[1]=p[1],ch[2]=p[2];
	p[n]=p[0];
    for(i=3;i<n;i++){
        while(multiply(p[i],ch[top],ch[top-1])>=0) top--;
        ch[++top]=p[i];
    }
    len=top+1;
}
int main(){
    int i,j,n,len;
    double d,ans;
    scanf("%d",&n);
        for(i=0;i<n;i++) scanf("%lf %lf",&p[i].x,&p[i].y);
        Graham_scan(p,h,n,len);
		double sum=0;
        for(i=1;i<len;i++)
        {
           sum+=distance(h[i],h[i-1]);
        }
        printf("%.2lf\n",sum);
    return 0;
}



   

你可能感兴趣的:(二维凸包模版——旋转卡壳法)