凸包入门(Graham扫描法)(A - Wall POJ - 1113)

本文介绍了一种解决国王在城堡周围建立围墙问题的算法,通过计算凸包和半径为l的圆周长,得出围墙最小消耗量。适用于特定几何问题的解决方案。

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

题目链接:https://cn.vjudge.net/contest/276359#problem/A

题目大意:有一个国王,要在自己的城堡周围建立围墙,要求围墙能把城堡全部围起来,并且围墙距离城堡的距离至少为l,然后问你最小的消耗量。

具体思路: 将围起来城堡的围墙全部往外移,求出这些点构成的凸包,然后再加上半径为l的圆的周长,这就是最终答案。

AC代码:

#include<iostream>
#include<stack>
#include<iomanip>
#include<string>
#include<stdio.h>
#include<cstring>
#include<iomanip>
#include<cmath>
#include<algorithm>
using namespace std;
# define ll long long
const int maxn = 1e3+100;
const double pi= acos(-1.0);
struct node
{
    double x,y;
} p[maxn],P[maxn];
int n,tot;
double ans,l;
double X(node A,node B,node C)//求叉积的过程
{
    return (B.x-A.x)*(C.y-A.y)-(C.x-A.x)*(B.y-A.y);
}
double len(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 A,node B)
{
    double pp=X(p[0],A,B);
    if(pp>0)
        return true;
    if(pp<0)
        return false;
    return len(p[0],A)<len(p[0],B);
}
int main()
{
    while(~scanf("%d %lf",&n,&l))
    {
        ans=2.0*pi*l;
        for(int i=0; i<n; i++)
        {
            scanf("%lf %lf",&p[i].x,&p[i].y);
        }
        if(n==1)
        {
            printf("%.0lf\n",ans);
        }
        else if(n==2)
        {
            printf("%.0lf\n",ans+=len(p[0],p[1]));
        }
        else
        {
            for(int i=0; i<n; i++)
            {
                if(p[i].y<p[0].y)
                {
                    swap(p[i],p[0]);
                }
                else if(p[i].y==p[0].y&&p[i].x<p[0].x)
                {
                    swap(p[i],p[0]);
                }
            }//先把第一个点找出来
            sort(p+1,p+n,cmp);
            P[0]=p[0];
            P[1]=p[1];//寻找凸包的起点和终点
            tot=1;
            for(int i=2; i<n; i++)
            {
                while(tot>0&&X(P[tot-1],P[tot],p[i])<=0)//斜率相同的时候,取较远的。
                    tot--;
                tot++;
                P[tot]=p[i];
            }
            for(int i=0; i<tot; i++)
            {
                ans+=len(P[i],P[i+1]);
            }
            ans+=len(P[0],P[tot]);
            printf("%.0lf\n",ans);
        }
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值