二维凸包

· · 算法·理论

P2742 【模板】二维凸包

#include<bits/stdc++.h>
//#define double long double
const int N = 1e5+10;
using namespace std;
int n,top;
struct Point{ //将点与向量存在一起
    double x,y;
    Point operator -(Point nex){ return (Point){x-nex.x,y-nex.y};} //计算两点间的向量
    double operator *(Point nex){ return x*nex.y-y*nex.x; }//计算向量间的叉乘
    double len(){ return sqrtl(x*x+y*y); } //求模长
}p[N],st[N];
bool cmp(Point u,Point v){ //u,v为点
    Point a=(u-p[1]),b=(v-p[1]); //点u,点v与极点的向量
    double det=a*b;//叉乘
//  if(det==0) return a.len()<b.len();
//  else return det>0;
    return det?det>0:a.len()<b.len();
}
void Point_Sort(){
    int id=1; //极点
    for(int i=2;i<=n;i++) 
        if(p[i].x<p[id].x||(p[i].x==p[id].x&&p[i].y<p[id].y)) id=i;
//  cout<<p[id].y<<" id"<<id<<endl;
    swap(p[1],p[id]);
    sort(p+2,p+n+1,cmp);
}
void Graham(){
    Point_Sort();
//  cout<<p[1].x<<" "<<p[1].y<<endl;
    st[++top]=p[1];
    for(int i=2;i<=n;i++){
        while(top>1&&(st[top]-st[top-1])*(p[i]-st[top])<=0) 
            top--;
        st[++top]=p[i];
    }
}
signed main(){
    cin.sync_with_stdio(false); cin.tie(nullptr);
    cin>>n;
    for(int i=1;i<=n;i++){
        cin>>p[i].x>>p[i].y;
    } 
    Graham();
//  cout<<st[1].y<<" "<<st[top].y<<endl;
    double ans=(st[1]-st[top]).len();
    for(int i=2;i<=top;i++) ans+=(st[i]-st[i-1]).len(); //求两点之间的距离
    cout<<fixed<<setprecision(2)<<ans;
    return 0;
}