[luogu2742]:[USACO5.1]圈奶牛Fencing the Cows

本文分享了一个计算几何中凸包问题的C++实现代码。通过定义点结构体并使用比较函数、向量乘法等操作,实现了计算点集构成的凸包边界,并给出最终边界长度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

传送门
突然心血来潮开始搞计算几何。。
首先肯定是凸包。。
直接贴代码吧。。。
代码:

#include<cstdio>
#include<cstring>
#include<iostream>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#define ll long long
using namespace std;
inline int read(){
    int x=0;char ch=' ';int f=1;
    while(ch!='-'&&(ch<'0'||ch>'9'))ch=getchar();
    if(ch=='-')f=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
    return x*f;
}
const int N=1e4+5;
const double eps=1e-12;
struct Point{
    double x,y;
    Point(){}
    Point(double _x,double _y):x(_x),y(_y){}
}p[N];
inline bool operator == (const Point& a,const Point& b){
    return fabs(a.x-b.x)<eps && fabs(a.y-b.y)<eps;
}
inline Point operator - (const Point& a,const Point& b){
    return Point(a.x-b.x,a.y-b.y);
}
inline double operator * (const Point& a,const Point& b){
    return (a.x*b.y)-(a.y*b.x);
}
inline bool cmp(const Point& a,const Point& b){
    if(fabs(a.x-b.x)<eps)return a.y<b.y;
    return a.x<b.x;
}
inline double slope(const Point& a,const Point& b){
    return (b.y-a.y)/(b.x-a.x);
}
inline double dis(const Point& a,const Point& b){
    return sqrt((b.x-a.x)*(b.x-a.x)+(b.y-a.y)*(b.y-a.y));
}
int n,s1[N],s2[N],top,len;
int main(){
    n=read();
    for(int i=1;i<=n;i++)scanf("%lf %lf",&p[i].x,&p[i].y);
    sort(p+1,p+n+1,cmp);
    s1[++top]=1;s1[++top]=2;
    for(int i=3;i<=n;i++){
        while(top>1 && (p[i]-p[s1[top]])*(p[s1[top]]-p[s1[top-1]])>0)top--;
        s1[++top]=i;
    }
    len=top;
    top=0;
    s2[++top]=n;s2[++top]=n-1;
    for(int i=n-2;i>=1;i--){
        while(top>1 && (p[i]-p[s2[top]])*(p[s2[top]]-p[s2[top-1]])>0)top--;
        s2[++top]=i;
    }
    double ans=0;
    for(int i=1;i<len;i++)ans+=dis(p[s1[i]],p[s1[i+1]]);
    for(int i=1;i<top;i++)ans+=dis(p[s2[i]],p[s2[i+1]]);
    printf("%.2lf",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值