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

版权声明:喜欢请点个大拇指,感谢各位dalao。弱弱说下,转载要出处呦 https://blog.csdn.net/qq_35786326/article/details/85800515


分析:

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


代码:

// 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;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/85800515