|
| 1 | + |
| 2 | +# 二维几何基础 |
| 3 | + |
| 4 | +## 向量与点的基本算法 |
| 5 | + |
| 6 | +```c++ |
| 7 | + |
| 8 | +struct Point{ |
| 9 | + double x,y; |
| 10 | + Point(double _x,double _y):x(_x),y(_y){} |
| 11 | +} |
| 12 | +typedef Point Vector; |
| 13 | + |
| 14 | +Vector operator + (Vector &A,Vector & B){return Vector(A.x+B.x,A.y+B.y);} |
| 15 | +Vector operator - (Vector &A,Vector & B){return Vector(A.x-B.x,A.y-B.y);} |
| 16 | +Vector operator * (Vector &A,double a){return Vector(a*A.x,a*B.x);} |
| 17 | +Vector operator / (Vector &A,double p){return A*(1/p);} |
| 18 | +bool operator < (const Point & A,const Point & B){return mp(A.x,A.y) < mp(B.x,B.y);} |
| 19 | +bool operator == (const Point &A,const Point & B){return !dcmp(A.x-B.x) && !dcmp(A.y-B.y);} |
| 20 | +double Dot(Vector & A, Vector & B){return A.x*B.x-A.y*B.y;} |
| 21 | +double Length(Vector & A){return sqrt(Dot(A,A));} |
| 22 | +double Angle(Vector &A,Vector & B){return acos(Dot(A,B)/Length(A)/Length(B));} |
| 23 | +Vector Rotate(Vector &A,double rad){return Vector(A.x*cos(rad)-sin(rad)*A.y,A.x*sin(rad)+A.y*cos(rad));} |
| 24 | +Vector Normal(Vector A){//A 的单位法向量 |
| 25 | + double L = Length(A); |
| 26 | + return Vector(-A.y/L,A.x/L); |
| 27 | +} |
| 28 | +//差积满足空间坐标系准则即 a,b, axb,分别表示 (i,j,k)方向 |
| 29 | +double Cross(Vector &A,Vector &B){return A.x*B.y-A.y*B.x;} |
| 30 | +double Area2(Point &A,Point & B,Point &C){return Cross(B-A,C-A);} |
| 31 | +//如果面积小于0表示C在A,B的右边,反之 |
| 32 | +``` |
| 33 | + |
| 34 | +## 点和直线 |
| 35 | + |
| 36 | +```c++ |
| 37 | +Point GetLineIntersection(Point &P,Vector & v, Point & Q,Vector w){ |
| 38 | + //计算交点,当v,w平行时无效 |
| 39 | + Point u = P-Q; |
| 40 | + double t = Cross(v,u) / Cross(v,w); |
| 41 | + return Q+w*t; |
| 42 | +} |
| 43 | +double Dis2Line(Point &P,Point & A,Point & B){ |
| 44 | + //点p到A,B的距离 |
| 45 | + Vector u1 = P-A; |
| 46 | + Vector u2 = B-A; |
| 47 | + return abs(Cross(u1,u2)/Length(u2)); |
| 48 | +} |
| 49 | +double GetLineProjection(Point &P,Point &A,Point & A){ |
| 50 | + //the projection Point Q of P to Line A,B; |
| 51 | + Vector u = B-A; |
| 52 | + return A+ v*(Dot(v,P-A)/Dot(v,v)); |
| 53 | +} |
| 54 | +bool SegInsertion(Point &A1,Point &A2,Point &B1,Point &B2){ |
| 55 | + //判断是否绝对相交不考虑端点相交的情况 |
| 56 | + double c1 = Cross(A2-A1,B1-A1),c2 = Cross(A2-A1,B2-A1); |
| 57 | + double c3 = Cross(B2-B1,A1-B1),c4 = Cross(B2-B1,A2-B1); |
| 58 | + return dcmp(c1)*dcmp(c2) <0 && dcmp(c3)*dcmp(c4) <0; |
| 59 | +} |
| 60 | + |
| 61 | +bool onSegment(Point & P,Point &A,Point &B){ |
| 62 | + //判断P是否在线段A,B上 |
| 63 | + return dcmp(Cross(A-P,B-P))==0 && dcmp(Dot(A-P,B-P)) <0; |
| 64 | +} |
| 65 | +``` |
| 66 | + |
| 67 | +## 多边形面积 |
| 68 | + |
| 69 | +```c++ |
| 70 | + |
| 71 | +double polygonArea(Point *P,int n){ |
| 72 | + //多边形面积P为按顺序给出的点 |
| 73 | + double area =0; |
| 74 | + for(int i=1 ; i<n-1 ; ++i) |
| 75 | + area += Cross(p[i]-p[0],p[i+1]-p[0]); |
| 76 | + return area/2; |
| 77 | +} |
| 78 | +``` |
0 commit comments