Surround the Trees HDU - 1392(凸包模板)

本文介绍了一个凸包算法的实现过程,使用C++编程语言,并详细展示了如何通过点集来构造凸包。该算法首先找到最左侧的点作为起始点,然后对所有点按极角进行排序,并利用栈结构来确定最终的凸包顶点集合。

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

#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>

using namespace std;
const int maxn=1000;
const double eps=1e-8;

int sgn(double x)
{
    if(fabs(x)<eps)
        return 0;
    if(x<0)
        return -1;
    else
        return 1;
}
struct Point
{
    double x,y;
    Point(){}
    Point(double _x,double _y)
    {
        x=_x;
        y=_y;
    }
    Point operator -(const Point &b)const
    {
        return Point(x-b.x,y-b.y);
    }
    double operator ^(const Point &b)const
    {
        return x*b.y-y*b.x;
    }
    double operator *(const Point &b)const
    {
        return x*b.x+y*b.y;
    }
};

Point p[maxn];
int Stack[maxn];
int top=0;

double dist(Point a,Point b)
{
    return sqrt((a-b)*(a-b));
}
bool cmp(Point a,Point b)
{
    int t=sgn((a-p[0])^(b-p[0]));
    if(t>0)
        return true;
    else if(t==0)
        return dist(a,p[0])<dist(b,p[0]);
    else
        return false;
}
void gram(int n)
{
    for(int i=0;i<n;i++)
    {
        if(p[i].x<p[0].x||(p[i].x==p[0].x&&p[i].y<p[0].y))
            swap(p[0],p[i]);
    }
    sort(p+1,p+n,cmp);
    if(n==1)
    {
        Stack[0]=0;
        top=0;
    }
    else if(n==2)
    {
        Stack[0]=0;
        Stack[1]=1;
        top=1;
    }
    else
    {
        Stack[0]=0;
        Stack[1]=1;
        top=1;
        for(int i=2;i<n;i++)
        {
            while(top>0&&((p[Stack[top]]-p[Stack[top-1]])^(p[i]-p[Stack[top-1]]))<=0)
                top--;
            top++;
            Stack[top]=i;
        }
    }
}
int main()
{
    int n;
    while(1)
    {
        cin>>n;
        if(n==0)
            break;
        for(int i=0;i<n;i++)
        {
            cin>>p[i].x>>p[i].y;
        }
        gram(n);
        double sum=0;
        if(n==2)
        {
            printf("%.2lf\n",dist(p[1],p[0]));
        }
        else{
            for(int i=0;i<=top;i++)
        {
            sum+=dist(p[Stack[i]],p[Stack[(i+1)%(top+1)]]);
        }
        printf("%.2lf\n",sum);
        }

    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值