二维凸包

塞一篇我看得懂的blog 点击打开链接

#include<bits/stdc++.h>
#define V (to[i])
#define debug printf("%d %s\n",__LINE__,__FUNCTION__)
#define PP system("pause")
#define N 1000010
#define NN 2010
#define NNN 310
#define eps 1e-9

using namespace std;

namespace program
{
    #define gc() getchar()
    #define pc putchar
    inline long long read(){
        register long long x=0,f=1;register char c=gc();
        for(;!isdigit(c);c=gc())if(c=='-')f=-1;
        for(;isdigit(c);c=gc())x=(x<<1)+(x<<3)+(c^48);
        return x*f;
    }
    inline void write(long long x){if(x<0)x=-x,pc('-');if(x>=10)write(x/10);putchar(x%10+'0');}
    inline void writeln(long long x){write(x);puts("");}
    
    int n,top=0;
    struct point{double x,y;}a[10010],Stack[10010];
    
    inline double js(point a,point b)
    {
    	return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
    }
    inline bool cmp1(point a,point b)
    {
    	if(a.x==b.x)
    		return a.y<b.y;
    	else
    		return a.x<b.x;
    }
    inline double cross(point a,point b,point c)
    {
        return (b.x-a.x)*(c.y-a.y)-(c.x-a.x)*(b.y-a.y);//叉积
    }
    inline bool cmp2(point a,point b)
    {
        double k=cross(Stack[1],a,b);
        if(k>0)return 1;
        else if(k==0)return js(Stack[1],a)<=js(Stack[1],b);
        else return 0;
    }
    inline void work()
    {
    	n=read();
    	for(int i=1;i<=n;i++)
    		scanf("%lf%lf",&a[i].x,&a[i].y);
    	sort(a+1,a+n+1,cmp1);
    	Stack[++top]=a[1];
    	sort(a+2,a+n+1,cmp2);//以最最左下角的点为基点  对点集的极角排序
    	Stack[++top]=a[2];
    	Stack[++top]=a[3];
    	for(int i=4;i<=n;i++)
    	{
    		while(top>0&&cross(Stack[top-1],Stack[top],a[i])<=0)top--;//小于等于0
                Stack[++top]=a[i];
        }
        double ans=0;
        for(int i=2;i<=top;i++)
            ans+=js(Stack[i-1],Stack[i]);
        ans+=js(Stack[top],Stack[1]);
        printf("%.2lf\n",ans);
    }
}

int main()
{
// 	freopen("gaojunonly1.in","r",stdin);
    program::work();
    return 0;
}

点赞