题意:给你一些点,让你按照极角的顺序输出凸包的顶点
思路:直接按照向量排序
按照向量叉乘的正负判断点所在的位置,类似于卷包裹的凸包,每次按照一条边排序,选择最外面的一条边,再按照选择的边在排序,再选直到点重合位置
这道题直接按照(0,0)点极角排序,如果极角相同选择最近的那个因为在一条直线上先选近的再选远的,如果选择远的那点的顺序都不对了
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<vector>
#include<algorithm>
using namespace std;
struct Point
{
double x,y;
Point(double x = 0,double y = 0) : x(x),y(y) {}
};
typedef Point Vector;
Vector operator + (Vector a,Vector b) { return Vector(a.x+b.x,a.y+b.y) ;}
Vector operator - (Vector a,Vector b) { return Vector(a.x-b.x,a.y-b.y) ;}
Vector operator * (Vector a,double p) { return Vector(a.x*p,a.y*p) ;}
Vector operator / (Vector a,double p) { return Vector(a.x/p,a.y/p) ;}
const double eps = 1e-9;
const double PI = acos(-1.0);
double Dot(Vector a,Vector b) { return a.x*b.x + a.y*b.y ;}
double Length(Vector a) { return sqrt(Dot(a,a)) ;}
double Cross(Vector a,Vector b) { return a.x*b.y - a.y*b.x ;}
int dcmp(double x)
{
if(fabs(x) < eps) return 0;
else return x < 0 ? -1 : 1;
}
bool operator < (Point a,Point b) { return a.x < b.x || (a.x == b.x && a.y < b.y) ;}
bool operator == ( Point a, Point b) { return dcmp(a.x-b.x) == 0 && dcmp(a.y-b.y) == 0 ;}
double Angle(Vector a,Vector b) { return acos( Dot(a,b) / Length(a) / Length(b) ) ;}
double Area(Point a,Point b,Point c) { return fabs(Cross(b-a,c-a))/2 ;}
Vector Rotate(Vector a,double rad) { return Vector(a.x*cos(rad) - a.y*sin(rad),a.x*sin(rad) + a.y*cos(rad) );}
Vector Normal(Vector a)
{
double L = Length(a);
return Vector(-a.y/L,a.x/L);
}
Point GetLineIntersection(Point p,Vector v,Point q,Vector w)
{
Vector u = p - q;
double t = Cross(w,u) / Cross(v,w);
return p + v*t;
}
bool SegmentProperIntersection(Point a1,Point a2,Point b1,Point b2)
{
double c1 = Cross(a2-a1,b1-a1) ,c2 = Cross(a2-a1,b2-a1),c3 = Cross(b2-b1,a1-b1),c4 = Cross(b2-b1,a2-b1);
return dcmp(c1)*dcmp(c2) < 0 && dcmp(c3) *dcmp(c3) < 0;
}
bool OnSengment(Point p,Point a,Point b)
{
return dcmp(Cross(p-a,b-a)) == 0 && dcmp(Dot(a-p,b-p) < 0);
}
double PolyArea(Point *p,int n)
{
double area = 0;
int i;
for(i = 0; i < n; i++)
{
area += Cross(p[i]-p[0],p[i+1]-p[0]);
}
return area/2;
}
struct Line
{
Point s,e;
};
int ConvexHull(Point* p,int n,Point* ch)
{
sort(p,p+n);
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;
}
Point p[1005];
bool cmp(Point a,Point b)
{
double temp = Cross(a-p[0],b-p[0]);
if(dcmp(temp) > 0) return true;
else if(dcmp(temp) == 0 && dcmp( Length(a-p[0]) - Length(b-p[0]) ) <= 0) return true;
else return false;
}
int main()
{
int n = 0;
while(scanf("%lf%lf",&p[n].x,&p[n].y) != EOF) n++;
sort(p,p+n,cmp);
for(int i = 0; i < n; i++)
{
printf("(%.0lf,%.0lf)\n",p[i].x,p[i].y);
}
return 0;
}
本文介绍了一种基于极角排序的凸包算法实现方法,通过向量叉乘判断点的位置,并详细展示了如何使用C++实现该算法,包括点的定义、向量运算、排序等关键步骤。
495

被折叠的 条评论
为什么被折叠?



