UVa 681 Convex Hull Finding (凸包,Graham‘s Scan)

這道題目沒有直接給出一些點,而是給出了一個凹多邊形,讓求凸包。這讓我誤以爲不用先根據極點排序了,可以直接scan...後來發現好多反例,還是老老實實來。

Graham‘s Scan 其實步驟不復雜:(1)選出最左下的點;(2)對剩下的點按極角排序;(3)按序進棧出棧。

第(3)步,判斷進棧出棧的標準,其實就是判斷線段的走向。其中第(2)和(3)步都要用到矢量積,也就是外積。

#include<iostream>
#include<algorithm>
#include<cmath>
using namespace std;

typedef struct{
	int x, y;
} POINT;

POINT ch[1000];

double dist(POINT a, POINT b){                                           //求兩點間距離  
	return sqrt(pow(a.x - b.x, 2.0) + pow(a.y - b.y, 2.0));
}

int crossProduct(POINT o, POINT a, POINT b){                             //求外積  
	return (a.x - o.x) * (b.y - o.y) - (b.x - o.x) * (a.y - o.y);
}

bool cmp_position(POINT a, POINT b){                                     //找到最左下的點  
	return a.y < b.y || (a.y == b.y && a.x < b.x);
}

bool cmp_angle(POINT a, POINT b){                                        //比較極角  
	int temp = crossProduct(ch[0], a, b);
	if(temp == 0)
		return (dist(a, ch[0]) < dist(b, ch[0]));
	else
		return temp > 0;
}

void print(POINT a[], int N){
	for(int i = 0; i < N; i++)
		cout << a[i].x << " " << a[i].y << endl;
}

int main(){
	int P;
	bool flag = true;
	cin >> P;
	while(P--){
		int N;
		cin >> N;
		for(int i = 0; i < N; i++)
			cin >> ch[i].x >> ch[i].y;
		swap(ch[0], *min_element(ch, ch + N, cmp_position));             //找到最左下點  
		sort(ch + 1, ch + N, cmp_angle);                                 //按極角排序  
		ch[N] = ch[0];
		POINT s[1000];
		int top = 2;
		s[0] = ch[0];
		s[1] = ch[1];
		for(int i = 2; i <= N; i++){                                     //scan  
			while(top >= 2 && crossProduct(s[top - 2], s[top - 1], ch[i]) <= 0){
				top--;
			}
			s[top++] = ch[i];
		}
		if(flag){
			cout << P + 1 << endl;
			flag = false;
		}
		cout << top << endl;
		print(s, top);
		if(P != 0){
			cin >> N;
			cout << N << endl;
		}
	}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章