BZOJ 1670: [Usaco2006 Oct]Building the Moat护城河的挖掘

Description

求凸包周长.

Sol

凸包+计算几何.

这好像叫什么 Graham Scan 算法...

这个可以求凸包的周长,直径,面积.

选择一个基点,然后按极角排序,最后用一个栈一直维护方向单调.

极角排序就是先按与基点的向量和 \(x\) 轴的夹角排序,就是点积变一变.

维护方向的时候就是用叉积判断顺逆关系...

Code

/**************************************************************
    Problem: 1670
    User: BeiYu
    Language: C++
    Result: Accepted
    Time:36 ms
    Memory:1352 kb
****************************************************************/
 
#include<cstdio>
#include<cmath>
#include<utility>
#include<algorithm>
#include<iostream>
using namespace std;
 
#define mpr make_pair
#define sqr(x) ((x)*(x))
#define x first
#define y second
typedef pair< int,int > pr;
const int N = 5005;
int n,b;
pr g[N];
int stk[N],top;
 
inline int in(int x=0,char ch=getchar()){ while(ch>'9' || ch<'0') ch=getchar();
    while(ch>='0' && ch<='9') x=(x<<3)+(x<<1)+ch-'0',ch=getchar();return x; }
pr operator - (const pr &a,const pr &b){ return mpr(a.x-b.x,a.y-b.y); }
int operator * (const pr &a,const pr &b){ return a.x*b.y-b.x*a.y; }
double Length(const pr &a){ return sqrt(sqr(1.0*a.x)+sqr(1.0*a.y)); }
int cmp(const pr &a,const pr &b){
    pr v1=a-g[1],v2=b-g[1];double l1=Length(v1),l2=Length(v2);
    if(v1.x*l2<v2.x*l1 || (v1.x*l2==v2.x*l1 && l1<l2)) return 1;return 0; 
}
int main(){
//  freopen("in.in","r",stdin);
    n=in(),b=1;
    for(int i=1,u,v;i<=n;i++){
        u=in(),v=in(),g[i]=mpr(u,v);
        if(v<g[b].y || (v==g[b].y && u<g[b].x)) b=i;
    }swap(g[1],g[b]);
    sort(g+2,g+n+1,cmp);
//  for(int i=1;i<=n;i++) printf("%d:(%d,%d)\n",i,g[i].x,g[i].y);
//  n=unique(g+2,g+n+1)-(g+2);
    stk[++top]=1,stk[++top]=2;
    for(int i=3;i<=n;i++){
        while(top>2 && (g[i]-g[stk[top]])*(g[stk[top]]-g[stk[top-1]])<0) --top;
        stk[++top]=i;
    }
//  cout<<"-----------"<<endl;
//  for(int i=1;i<=top;i++) printf("%d:(%d,%d)\n",i,g[stk[i]].x,g[stk[i]].y);
    double ans=Length(g[stk[top]]-g[1]);
    for(int i=2;i<=top;i++) ans+=Length(g[stk[i]]-g[stk[i-1]]);
    printf("%.2lf\n",ans);
    return 0;
}

  

 

posted @ 2016-11-10 20:51  北北北北屿  阅读(165)  评论(0编辑  收藏  举报