UVA 681 Convex Hull Finding【逆时针输出凸包顶点】

题目大意:按照输出格式,从起点开始,逆时针输出凸包顶点,最后仍输出起点.

解题策略:今天提前看了一下凸包相关的算法,思想是Graham-Scan算法,但是使用的“序”是水平序。

                      第一道凸包题,Mark下微笑


/*
   UVA 681 Convex Hull Finding
   AC by J_Dark
   ON 2013/5/6 0:25
   Time 0.146s
*/
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
#include <stack>
using namespace std;
/
struct point{
	int x, y;
	point(int a, int b){
		x = a;
		y = b;
	}
};
vector<point> p;
vector<int> CH; //存放凸包顶点序号   模拟栈
int testCase, top = 1, temp, nodeNum;
/
void Input(){
	p.clear();
	CH.clear();
	cin >> nodeNum;
	CH.resize(nodeNum+1);
	//p.resize(nodeNum);
	int xx, yy;
	for(int i=0; i<nodeNum; i++){
		cin >> xx >> yy;
		p.push_back(point(xx, yy));
	}
	cin >> temp;
}

bool cmp(point a, point b){
	if(a.y == b.y)  return a.x < b.x;
	return a.y < b.y;
}

bool turnRight(point px1, point px2, point pp){
	return (px2.x - px1.x)*(pp.y - px2.y) <= (pp.x - px2.x)*(px2.y - px1.y);
}
void Compute(){
	sort(p.begin(), p.end(), cmp);
	CH[0] = 0;
	CH[1] = 1;
	if(nodeNum == 3) { return; CH[2] = 2;}

	top = 1;
	//从起点0到到排序最后点作凸包右链  过程1
	for(int i=2; i<nodeNum; i++){
		while( top && turnRight(p[CH[top-1]], p[CH[top]], p[i]) )
		{
		   top--;
		}
		CH[++top] = i;
		//printf("CH[%d] = %d\n", top, i);
	}

	int len = top;
	//从排序最高点到到起点0fab反向作凸包右链  过程2
	CH[++top] = nodeNum-2;
	for(int i=nodeNum-3; i>=0; i--){
		//top!=len, 不考虑已在过程1生成凸包上的点
		while( top!=len && turnRight(p[CH[top-1]], p[CH[top]], p[i]) )
		{
		   top--;
		}
		CH[++top] = i;
		//printf("CH[%d] = %d\n", top, i);
	}
}

void Output(int cc){
	cout << top+1 << endl;
	int sPos;
	//在栈中找到凸包起点
	for(sPos=0; sPos<top; sPos++){
		if(p[CH[sPos]].x == p[0].x && p[CH[sPos]].y == p[0].y)
		   break;
	}
	//从起点开始逆时针输出凸包
	for(int i=sPos; i<top; i++){
		cout << p[CH[i]].x << " " << p[CH[i]].y << endl;
	}
	for(int i=0; i<sPos; i++){
		cout << p[CH[i]].x << " " << p[CH[i]].y << endl;
	}
	cout << p[CH[sPos]].x << " " << p[CH[sPos]].y << endl;
	if(cc != testCase-1)  cout << temp << endl;

}

/
int main(){
	while(cin >> testCase)
	{
		cout << testCase << endl;
		for(int i=0; i<testCase; i++){
		   Input();
		   Compute();
		   Output(i);
		}

	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值