凸包-Graham-Scan算法

(1)问题:

给定二维平面点集,求最小的包含所有点的凸多边形。

(2)Gramham-Scan算法:

Gramham-Scan是一种灵活的凸包算法,其总的时间复杂度仅为O(n*log(n))。

步骤:

Step1: 选定x坐标最小(相同情况y最小)的点作为极点,这个点必在凸包上;

Step2: 将其余点按极角排序,在极角相同的情况下比较与极点的距离,离极点比较近的优先;

Step3: 用一个栈S存储凸包上的点,先将按极角和极点排序最小的两个点入栈;

Step4: 按序扫描每个点,检查栈顶的两个元素与这个点构成的折线段是否“拐”向右侧(叉积小于等于零);

Step5: 如果满足,则弹出栈顶元素,并返回Step4再次检查,直至不满足。将该点入栈,并对其余点不断执行此操作;

Step6: 最终栈中元素为凸包的顶点序列。

(3)模板(来自kuangbin模板)

  1. #include <iostream>  
  2. #include <cstdio>  
  3. #include <cmath>  
  4. #include <algorithm>  
  5. using namespace std;  
  6.   
  7. const double eps = 1e-8;  
  8. struct Point{  
  9.     double x, y;  
  10. };  
  11.   
  12. const int MAXN = 1010;  
  13. Point list[MAXN];  
  14. int stack[MAXN], top;  
  15.   
  16. /*** 
  17. * 叉积 
  18. * a×b>0, 则b在a的逆时针方向; 
  19. * a×b<0, 则b在a的顺时针方向; 
  20. * a×b=0, 则a与b共线,但可能同向也可能反向。 
  21. */  
  22. double crossProduct(Point a, Point b){  
  23.     return a.x*b.y - a.y*b.x;  
  24. }  
  25.   
  26. int sgn(double x){  
  27.     if(fabs(x) < eps) return 0;  
  28.     if(x < 0) return -1;  
  29.     else return 1;  
  30. }  
  31.   
  32. Point sub(Point a, Point b){  
  33.     Point p;  
  34.     p.x = a.x - b.x;  
  35.     p.y = a.y - b.y;  
  36.     return p;  
  37. }  
  38.   
  39. double dist(Point a, Point b){  
  40.     return sqrt((a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y));  
  41. }  
  42.   
  43. //相对于极点list[0]的极角排序  
  44. bool cmp(Point p1, Point p2){  
  45.     double temp  = crossProduct(sub(p1, list[0]), sub(p2, list[0]));  
  46.     if(sgn(temp)>0) return true;  
  47.     else if(sgn(temp)==0 && sgn(dist(p1, list[0])-dist(p2, list[0]))<=0) return true;  
  48.     else return false;  
  49. }  
  50.   
  51. /* 
  52. * 求凸包,Graham算法 
  53. * 点的编号0~n-1 
  54. * 返回凸包结果Stack[0~top-1]为凸包的编号 
  55. */  
  56. void Graham(int n){  
  57.     Point p0 = list[0];  
  58.     int k = 0;  
  59.     for(int i=1;i<n;i++){  
  60.         if(p0.y>list[i].y || (p0.y==list[i].y && p0.x>list[i].x)){  
  61.             p0 = list[i];  
  62.             k = i;  
  63.         }  
  64.     }  
  65.     swap(list[k], list[0]);  
  66.     sort(list+1, list+n, cmp);  
  67.   
  68.     stack[0] = 0;  
  69.     if(n==1){top = 1; return;}  
  70.     stack[1] = 1;  
  71.     if(n==2){top = 2; return;}  
  72.   
  73.     top = 2;  
  74.     for(int i=2;i<n;i++){  
  75.         while(top>1 && sgn(crossProduct(sub(list[stack[top-1]], list[stack[top-2]]), sub(list[i], list[stack[top-2]])))<=0){  
  76.             top--;  
  77.         }  
  78.         stack[top++] = i;  
  79.     }  

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值