Polar angle sorting
Polar angle
The so-called polar angle refers to the angle that takes the positive half axis of the x axis as the starting edge, establishes polar coordinates and turns counter-clockwise. The range of this angle is [0,2pi].
purpose
1. Computing convex hull
Links:
2, some strange path questions.
You can only turn left and right to find the nearest inflection point by sorting the polar corners.
For example: POJ 1696
Code
Calculating Polar Angle with Cross Product (High Accuracy, Slow Time)
struct point{ double x,y; point(double x=0, double y=0):x(x), y(y){} point operator - (const point &t)const{ return point(x-t.x, y-t.y); }//a - b double operator *(const point &t)const{ return x*t.x + y*t.y; }//a * b double operator ^(const point &t)const{ return x*t.y - y*t.x; }//a X b }; double compare(point a,point b,point c)//Calculation of polar angle ab * ac { return (b-a)^(c-a); } bool cmp(point a,point b) { double f=compare(p[pos],a,b); if(f==0) return a.x-p[pos].x<b.x-p[pos].x; else if(f>0) return true; else return false; }
If the selected point is not the point of the corner, it needs to be sorted according to the quadrant first.
int Quadrant(point a)//Quadrant sorting, note that there are four coordinate axes { if(a.x>0&&a.y>=0) return 1; if(a.x<=0&&a.y>0) return 2; if(a.x<0&&a.y<=0) return 3; if(a.x>=0&&a.y<0) return 4; } bool cmp2(point a,point b)//First quadrant and then polar angle { if(Quadrant(a)==Quadrant(b))//The return value is the quadrant return cmp(a,b); else Quadrant(a)<Quadrant(b); }
atan2 function (fast time, poor accuracy)
atan2(y,x) denotes that the point (x,y) is connected to the point. The angle between the line and the positive half-axis of the x-axis is [pi, pi]. The range of the polar angle here is [pi, pi]. The one-two quadrants are positive and the three-four quadrants are negative. So when we have finished ordering from small to large, it is actually the third quadrant < the fourth quadrant < the first quadrant < the second quadrant.
struct point{ double x,y; double angle; bool operator <(const point &t) { return angle<t.angle; } }p[N]; bool cmp(point a,point b) { if(a.angle==b.angle) return a.x<b.x; else { return a.angle<b.angle; } } for(int i=1;i<=n;i++) { cin>>p[i].x>>p[i].y; p[i].angle=atan2(p[i].y,p[i].x); } sort(a+1,a+1+n,cmp);