hdu 1392 Surround the Trees(凸包模板)

凸包: 给你n个散落的点,让你求出最小的凸多边形将所有的点包括起来,或者点在边上。

注意 n=1和n=2的情况

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cmath>
using namespace std;
#define N 1050
#define PI 4*atan(1.0)
#define eps 1e-8
struct Node
{
    double x,y;
} p[N],stack[N];
double mulit(Node a,Node b,Node c)//向量ab与向量ac的叉乘
{
    return ((b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x));
}

double dist(Node s,Node e)//s点与e点的距离的平方(此处如果直接开根怕影响在传递的时候影响精度)
{
    return (s.x-e.x)*(s.x-e.x)+(s.y-e.y)*(s.y-e.y);
}

int cmp(Node a,Node b)//设<p1,p2,...pm>为对其余点按以p0为中心的极角逆时针排序所得的点集(如果有多个点有相同的极角,除了距p0最远的点外全部移除)
{
    if(mulit(p[0],a,b)>0)//向量p[0]a在向量p[0]b顺时针方向,返回1
        return 1;
    if(mulit(p[0],b,a)==0&&(dist(p[0],b)-dist(p[0],a)>eps))//p[0]a与p[0]b共线,而且b点距离更远
        return 1;
    return 0;
}

int Graham(int n)
{
    int top=2;
    sort(p+1,p+n,cmp);
    stack[0]=p[0];
    stack[1]=p[1];
    stack[2]=p[2];
    for(int i=3;i<n;i++)
    {
        while(top>=1&&mulit(stack[top-1],p[i],stack[top])>=0)
            top--;
        stack[++top]=p[i];
    }
    return top;
}
int main()
{
    int n;
    while(scanf("%d",&n)&&n)
    {
        
        for(int i=0; i<n; i++)
            scanf("%lf %lf",&p[i].x,&p[i].y);
        
        if(n==1)
		{
        	printf("0.00\n");
        	continue;
		}
		else if(n==2){
			printf("%.2lf\n",dist(p[0],p[1]));
			continue;
		}
            
        int k=0;
        for(int i=0; i<n; i++)
        {
            if(p[k].y>p[i].y||(p[k].y==p[i].y&&p[k].x>p[i].x))
                k=i;
        }
        swap(p[0],p[k]);
 
		int top=Graham(n);
        double sum=0.0;
        for(int i=1; i<=top; i++)
            sum+=sqrt(dist(stack[i],stack[i-1]));
        sum+=sqrt(dist(stack[0],stack[top]));
      
        printf("%.2lf\n",sum);
      
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值