poj2187 凸包问题

Pseudo-Code: Graham Scan Algorithm

Input: a set of points S = {P = (P.x,P.y)}

Select the rightmost lowest point P0 in
S.
Sort
S angularly about P0 as a center.
For ties, discard the closer points.
Let P[N] be the sorted array of points.

Push P[0]=P0 and P[1] onto a stack
W.

while i < N
{
Let PT1 = the top point on
W
Let PT2 = the second top point on
W
if (P[i] is strictly left of the line PT2 to PT1) {
Push P[i] onto
W
i++ // increment i
}
else
Pop the top point PT1 off the stack

}


Output: W = the convex hull ofS.


转自:凸包问题的几种算法,包括Graham scan 算法

这个算法其实也很好想通的。

第一步:找到y坐标最小的点p0;

第二步:以p0为原点,对所有的点按逆时针顺序排序;

第三步:逐步迭代,加入边界点。(画出一条边,如果一个新的边更靠左,则加入,否则不加入)。


#include<iostream> #include<fstream> #include<algorithm> using namespace std; const int num=50005; int N; struct Point { int x; int y; }points[num],output[num]; inline int ccw(Point p1,Point p2,Point p3) //交叉乘积 { return (p2.x-p1.x)*(p3.y-p1.y)-(p2.y-p1.y)*(p3.x-p1.x); } inline int dis(Point p1,Point p2) //距离 { return (p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y); } int cmp(const void *po1,const void *po2) //排序用的比较函数 { Point *p1=(Point *)po1; Point *p2=(Point *)po2; int temp=ccw(points[0],*p1,*p2); //先判断方向 if(temp>0) { return -1; } else if(temp<0) { return 1; } else { return dis(*p1,points[0])-dis(*p2,points[0]); //共线时按距离从大到校排序 } } int maxDist( ) { int min_index=0; for(int i=1;i<N;i++) { if(points[i].x<points[min_index].x) min_index=i; else if(points[i].x<points[min_index].x&&points[i].y<points[min_index].y) min_index=i; } swap(points[0],points[min_index]); //找到y坐标最小的点,并交换到第一个位置 qsort(points+1,N-1,sizeof(Point),cmp); //排序 /* for(int i=0;i<N;i++) { printf("%d %d\n",points[i].x,points[i].y); }*/ output[0]=points[0]; output[1]=points[1]; int top=1; int i=2; while(i<N) { // printf("%d %d\n",points[i].x,points[i].y); int temp=ccw(output[top-1],output[top],points[i]); if(temp>=0) { output[++top]=points[i]; i++; } /*else if(temp==0) { output[top]=points[i]; i++; }*/ else { top--; } } int maxD=0; for(int i=0;i<=top;i++) //计算边界点之间的距离 { // printf("%d %d\n",output[i].x,output[i].y); for(int j=i+1;j<=top;j++) { int temp=dis(output[i],output[j]); if(temp>maxD) maxD=temp; } } printf("%d\n",maxD); return maxD; } int main() { freopen("input.txt","r",stdin); while( scanf("%d",&N)!=EOF) //输入 { for(int i=0;i<N;i++) { scanf("%d %d",&points[i].x,&points[i].y); //printf("%d %d\n",points[i].x,points[i].y); } maxDist(); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值