算法介绍:
凸包问题的朴素实现,我比较喜欢的解释就是拿一根橡皮筋,地图上的点就是一个个钉子,用橡皮筋从一个位置开始,绕着钉子转一圈,所得到的就是最终结果凸包。
算法流程:
1.对点进行排列,可以按照x轴最小或者y轴最小来排序,如果有多个最小点则按照y轴最小/x轴最小来选取点,不考虑重复点。
2.选定初始点之后,选择第一个判断点(第一次不是初始点,后面都设为初始点),再遍历所有节点作为候选点(跳过判断点)判断是否在线段的左侧(使用AB向量xAC向量=|AB||AC|sina来判断,为正则为左侧。),如果是在右侧则将候选点赋值给判断点,循环完毕后选择的判断点即为凸包上的点。
3.重复此操作直到候选点为初始点。
测试用例:
INPUT:
8
0 5
5 0
6 2
6 6
8 3
1 8
3 4
8 7
OUTPUT:
8
0 5
5 0
8 3
8 7
0 5
来自《挑战程序设计竞赛[第二版]》P261
算法代码:
/*
输入数据:(在该cpp所在目录下创建input.txt文件,并把数据保存到里面)
8
0 5
5 0
6 2
6 6
8 3
1 8
3 4
8 7
*/
#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
FILE *fin=fopen("input.txt","r");
typedef struct Point{
int x;
int y;
bool operator!=(const Point &a)const{
return x!=a.x&&y!=a.y;
}
bool operator==(const Point &a)const{
return x==a.x&&y==a.y;
}
bool operator<(const Point &a)const{
return x==a.x?y<a.y:x<a.x;
}
}P;
int check(P a,P b,P c){//返回(ab,ac)夹角
return (b.x-a.x)*(c.y-a.y)-(b.y-a.y)*(c.x-a.x);
}
int distance(P a,P b){//返回(a,b)之间距离
return (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y);
}
P p[100];
vector<P>ans;//保存凸包上的点
int n;
bool isVisited[100]={0};
int main(){
fscanf(fin,"%d",&n);
printf("%d\n",n);
for(int i=0;i<n;i++){
fscanf(fin,"%d%d",&p[i].x,&p[i].y);
}
sort(p,p+n);
ans.push_back(p[0]);
P p1=ans[0];
P p2;
int choose = -1;
while(choose!=0){
if(p1!=p[0])p2=p[0],choose=0;//如果p1是初始点,则p2不能是初始点
else p2=p[1],choose=1;
for(int i=0;i<n;i++){
if(isVisited[i])continue;
if(check(p1,p2,p[i])<=0){
if(distance(p1,p2)>distance(p2,p[i]))continue;
p2=p[i];
choose=i;
}
}
ans.push_back(p2);
isVisited[choose]=true;//已选的凸包点(不包括初始点)
p1=p2;
}
for(int i=0;i<ans.size();i++){
cout<<ans[i].x<<" "<<ans[i].y<<endl;
}
return 0;
}