bzoj1670 [Usaco2006 Oct]Building the Moat(凸包)

求凸包裸题。用的是Graham扫描法求凸包。
a × b > 0 说明向量b在向量a的逆时针方向上。
我们一开始极角排序就是要把这些点与点1的连线逆时针排序。
然后按顺序处理这些点,维护一个栈,使得相邻点之间的线段都是逆时针转的。这样就得到了一个凸包。
写个模板题还被卡精度了gg 要1e-6…

#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 5010
#define eps 1e-6
inline char gc(){
    static char buf[1<<16],*S,*T;
    if(S==T){T=(S=buf)+fread(buf,1,1<<16,stdin);if(T==S) return EOF;}
    return *S++;
}
inline int read(){
    int x=0,f=1;char ch=gc();
    while(ch<'0'||ch>'9'){if(ch=='-') f=-1;ch=gc();}
    while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=gc();
    return x*f;
}
int n,qq[N],top=0;double ans=0;
inline double sqr(double x){return x*x;}
struct P{
    double x,y;
    P(double _x=0.0,double _y=0.0){x=_x;y=_y;}
    friend double det(P a,P b){return a.x*b.y-a.y*b.x;}
    friend P operator-(P a,P b){return P(a.x-b.x,a.y-b.y);}
    friend double dis(P a,P b){return sqrt(sqr(a.x-b.x)+sqr(a.y-b.y));}
}p[N];
inline bool operator<(P a,P b){double res=det(a-p[1],b-p[1]);if(abs(res)<eps) return dis(a,p[1])<dis(b,p[1]);return res>0;}
int main(){
//  freopen("a.in","r",stdin);
    n=read();int s=1;
    for(int i=1;i<=n;++i) p[i].x=read(),p[i].y=read();
    for(int i=2;i<=n;++i) if(p[i].y<p[s].y||p[i].y==p[s].y&&p[i].x<p[s].x) s=i;
    swap(p[1],p[s]);sort(p+2,p+n+1);
    for(int i=1;i<=n;++i){
        while(top>=2&&det(p[qq[top]]-p[qq[top-1]],p[i]-p[qq[top-1]])<=eps) --top;
        qq[++top]=i;
    }for(int i=1;i<top;++i) ans+=dis(p[qq[i]],p[qq[i+1]]);ans+=dis(p[1],p[qq[top]]);
    printf("%.2lf\n",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/icefox_zhx/article/details/80821045