UVA 11626 Convex Hull(凸包:模板题)
题意:
给你n个点的集合,并且用’N’或’Y’表示出来了该点是否在凸包的边界上,然后要你按逆时针顺序输出凸包且第一个输出的点必须是x坐标最小的(如果x坐标相同,那么就输出y坐标最小的).
分析:
其实本题就是一个求凸包的最大点集,然后输出的题目. 凸包的最大点集包含了所有在凸包边界上的点,所以输出点中有可能相邻3点共线.
刘汝佳<<训练指南>>P272页的模板(需要自己排序且把<=号改成<号)正好符合上面的几乎所有的要求,特别是最大点集,点逆时针输出,从x坐标最小的点开始输出…
AC代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
const double eps=1e-10;
int dcmp(double x)
{
if(fabs(x)<eps) return 0;
return x<0?-1:1;
}
struct Point
{
double x,y;
Point(){}
Point(double x,double y):x(x),y(y){}
bool operator==(const Point& rhs)const
{
return dcmp(x-rhs.x)==0 && dcmp(y-rhs.y)==0;
}
bool operator<(const Point& rhs)const
{
return dcmp(x-rhs.x)<0 || (dcmp(x-rhs.x)==0 && dcmp(y-rhs.y)<0);
}
};
typedef Point Vector;
Vector operator-(Point A,Point B)
{
return Vector(A.x-B.x,A.y-B.y);
}
double Cross(Vector A,Vector B)
{
return A.x*B.y-A.y*B.x;
}
int ConvexHull(Point *p,int n,Point *ch)//求凸包
{
sort(p,p+n);
n=unique(p,p+n)-p;
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) m--;
ch[m++]=p[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) m--;
ch[m++]=p[i];
}
if(n>1) m--;
return m;
}
const int maxn=100000+10;
Point p[maxn],ch[maxn];
int main()
{
int T; scanf("%d",&T);
while(T--)
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
scanf("%lf%lf %*c",&p[i].x,&p[i].y);
int m=ConvexHull(p,n,ch);
printf("%d\n",m);
for(int i=0;i<m;i++)
printf("%.0lf %.0lf\n",ch[i].x,ch[i].y);
}
return 0;
}