hunnu11326(基础凸包题,求凸包的点个数,和凸包顶点)

本文介绍了一种使用Andrew算法来构建凸包的方法,并提供了一份完整的C++代码实现。该算法首先对输入点集进行排序,确保从最下最左的点开始处理。通过两次扫描过程确定上壳和下壳,最终形成凸包。

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

采用的是凸包Andrew算法

因为题目要求凸包中第一个输出最下最左点,所以sort要先按y从小到大牌,若y相同,然后x从小到大排序;

代码如下:

#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
#include<queue>
#include<set>
#include<map>
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
#include<time.h>
#include<math.h>

#define eps 1e-9
#define N 105
#define pi acos(-1.0)
#define P system("pause")
using namespace std;
struct node
{
       double x,y;       
}p[N],ch[N];
node operator -(node a,node b)
{
     a.x -= b.x;
     a.y -= b.y;
     return a;     
}
bool cmp(node a,node b)
{
     if(a.y != b.y) return a.y < b.y;
     return a.x < b.x;
}
double cross(node A,node B)
{
     return A.x*B.y - A.y*B.x;     
}
int dcmp(double x)
{
    if( fabs(x) < eps ) return 0;
    return x > 0 ? 1 :-1;
}
int convexhull(int n)  //Andrew的模板
{
     sort(p,p+n,cmp);
     int i,m=0;
     for(i = 0; i < n; i++)
     {
           while(m > 1 && dcmp(cross(ch[m-1]-ch[m-2], p[i]-ch[m-2])) <= 0)
                   m--;
           ch[m++] = p[i];                          
     }   
     int k = m;
     for(i = n-2; i >= 0; i--)
     {
           while(m > k && dcmp(cross(ch[m-1]-ch[m-2], p[i]-ch[m-2])) <= 0) 
                     m--;
           ch[m++] = p[i];      
     }
     if(n > 1)  m--;
     return m;
}
int main()
{
//freopen("input.txt","r",stdin);
//freopen("output.txt","w",stdout);
    int i,n;
    while(scanf("%d",&n)&&n)
    {
         for(i=0;i<n;i++)
           scanf("%lf%lf",&p[i].x,&p[i].y);
         int k = convexhull(n);
         printf("%d\n",k);
         for(i=0;i<k;i++)
              printf("%.0lf %.0lf\n",ch[i].x,ch[i].y);         
    }
    
  //  P;                               
    return 0;    
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值