1. 程式人生 > >基於水平序的Andrew凸包演算法 最詳細的圖解(多圖預警)

基於水平序的Andrew凸包演算法 最詳細的圖解(多圖預警)

給出凸包的定義:

簡要說一下思路:

首先將所有點按照x從小到大(x同則y從小到大)排序
把p1,p2放入凸包,從p3開始,當新點在凸包‘前進’方向的左邊時繼續,否則依次刪除最近加入凸包的點,直到新點在左邊
輸入不能有重複點,不希望凸包邊上有點可疑將<=改為<

下面請根據程式,測試資料與輸出 及步驟圖學習,跟著模擬一遍就會非常明白了

#include<bits/stdc++.h>
using namespace std;
const double eps=1e-10;                                                              
struct Point{                                                                        
    double x,y;                                                                     
    int id;
    Point(double x=0,double y=0,int id=0):x(x),y(y),id(id){}
};
typedef Point Vector;

bool operator< (const Point&a,Point &b){
	return a.x<b.x ||(a.x==b.x && a.y<b.y);
}

Vector operator + (Vector A,Vector B){return Vector(A.x+B.x,A.y+B.y);}
Vector operator - (Vector A,Vector B){return Vector(A.x-B.x,A.y-B.y);}
Vector operator * (Vector A,double B){return Vector(A.x*B,A.y*B);}
Vector operator / (Vector A,double B){return Vector(A.x/B,A.y/B);}

int dcmp(double x){if(fabs(x)<eps)return 0;return (x>0)?1:-1;}
bool operator == (const Vector A,const Vector B){
    return dcmp(A.x-B.x)==0 && dcmp(A.y-B.y)==0;
}
double Dot(Vector A,Vector B){return A.x*B.x+A.y*B.y;}  
double Length(Vector A){return sqrt(Dot(A,A));}         
double Cross(Vector A,Vector B){return A.x*B.y-B.x*A.y;}

int ConvexHell(Point p[],int n,Point ch[]) {
	sort(p,p+n);
	int m=0;
	for(int i=0;i<n;i++){
		while(m>1 && Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0){           //下凸包 
			printf("update: segment %d TO %d destination: %d\n",m-2,m-1,i);
			m--;
		}
		ch[m++]=p[i];
		printf("ch[ %d ]= %d\n",m-1,i);
	}
	int k=m;
	for(int i=n-2;i>=0;i--){
		while(m>k && Cross(ch[m-1]-ch[m-2],p[i]-ch[m-2])<=0){          //上凸包 
			printf("update: segment %d TO %d destination: %d\n",m-2,m-1,i);
			m--;
		}
		ch[m++]=p[i];
		printf("ch[ %d ]= %d\n",m-1,i);
	}
	if(n>1)m--;
	return m;
}
int main(){
	int n;
	scanf("%d",&n);
	Point p[20],ch[20];
	for(int i=0;i<n;i++)scanf("%lf%lf",&p[i].x,&p[i].y);
	int sum=ConvexHell(p,n,ch);
	printf("Final Ans:\n");
	for(int i=0;i<sum;i++)printf("%.0lf %.0lf,",ch[i].x,ch[i].y);
    return 0;
}
/*測試資料及輸出
8
3 0
4 8
5 5
6 3
6 7
8 4
9 2
10 7
ch[ 0 ]= 0
ch[ 1 ]= 1
update: segment 0 TO 1 destination: 2
ch[ 1 ]= 2
update: segment 0 TO 1 destination: 3
ch[ 1 ]= 3
ch[ 2 ]= 4
update: segment 1 TO 2 destination: 5
update: segment 0 TO 1 destination: 5
ch[ 1 ]= 5
update: segment 0 TO 1 destination: 6
ch[ 1 ]= 6
ch[ 2 ]= 7
ch[ 3 ]= 6
update: segment 2 TO 3 destination: 5
ch[ 3 ]= 5
update: segment 2 TO 3 destination: 4
ch[ 3 ]= 4
ch[ 4 ]= 3
update: segment 3 TO 4 destination: 2
ch[ 4 ]= 2
update: segment 3 TO 4 destination: 1
update: segment 2 TO 3 destination: 1
ch[ 3 ]= 1
ch[ 4 ]= 0
Final Ans:
3 0,9 2,10 7,4 8,
*/