洛谷 P2742 【模板】二维凸包 / [USACO5.1]圈奶牛Fencing the Cows

本文介绍了一种求解二维凸包的算法,并利用勾股定理计算两点间直线距离。通过具体代码实现,展示了如何从一组点中找出构成凸包的点集,并计算凸包周长。

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


分析:

求二维凸包既可
距离通过勾股定理求直线距离既可


代码:

// luogu-judger-enable-o2
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring> 
#include<cstdlib>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<map>
#include<list>
#include<ctime>
#include<iomanip>
#include<string>
#include<bitset>
#include<deque>
#include<set>
#define LL long long
#define ch cheap
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
struct node{
    double x,y;
}e[10005],w[10005];
double cj(node a1,node a2,node b1,node b2)
{
    return (a2.x-a1.x)*(b2.y-b1.y)-(b2.x-b1.x)*(a2.y-a1.y);
}
double dis(node a,node b)
{
    return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
bool cmp(node x,node y)
{
    if(cj(e[1],x,e[1],y)>0) return 1;
    if(cj(e[1],x,e[1],y)==0&&dis(x,e[0])<dis(y,e[0])) return 1;
    return 0;
}
int main()
{
    int n=read();
    for(int i=1;i<=n;i++)
    {
        scanf("%lf%lf",&e[i].x,&e[i].y);
        if(i==1) continue;
        if(e[i].y<e[1].y) {swap(e[1].x,e[i].x);swap(e[1].y,e[i].y);}
    }
    sort(e+2,e+1+n,cmp);
    int tot=1;
    w[tot]=e[1];
    for(int i=2;i<=n;i++)
    {
        while(tot>1&&cj(w[tot-1],w[tot],w[tot],e[i])<=0) tot--;
        w[++tot]=e[i];
    }
    double ans=0;
    w[++tot]=e[1];
    for(int i=2;i<=tot;i++) ans+=dis(w[i-1],w[i]);
    printf("%.2lf",ans);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值