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;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章