题目大意:按照输出格式,从起点开始,逆时针输出凸包顶点,最后仍输出起点.
解题策略:今天提前看了一下凸包相关的算法,思想是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;
}