計算幾何 部分常用函式模板
阿新 • • 發佈:2018-12-06
來自《演算法競賽入門經典-訓練指南》 劉汝佳/陳峰 清華大學出版社
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> using namespace std; const double eps = 1e-8; int dcmp(double x) //三態函式 處理與double零有關的精度問題 { if(fabs(x) < eps) return 0; return x<0 ? -1 : 1; } #define Vector Point //向量使用點作為表示方法 結構相同 為了程式碼清晰定義巨集加以區別 struct Point//點 向量 { double x,y; Point(double x=0,double y=0):x(x),y(y) {} }; //向量運算 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);} bool operator == (const Vector& A, const Vector& B) {return dcmp(A.x-B.x)==0 && dcmp(A.y-B.y)==0;} double Dis(Point A, Point B)//兩點距離 { return sqrt((A.x - B.x)*(A.x - B.x) + (A.y - B.y)*(A.y - B.y)); } 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 Angle(Vector A, Vector B){ //向量夾角 return acos(Dot(A,B) / Length(A) / Length(B)); } double Cross(Vector A, Vector B){ //向量叉積 return A.x * B.y - A.y * B.x; } double Area2(Point A, Point B, Point C){ // 三角形有向面積兩倍 return Cross(B-A,C-A); } Vector Rotate(Vector A, double rad){//向量旋轉 rad為弧度 return Vector(A.x * cos(rad) - A.y * sin(rad), A.x * sin(rad) + A.y * cos(rad)); } Vector Normal(Vector A){ //單位法線 (左轉90度後的單位向量) //呼叫需確定A為非零向量 double L = Length(A); return Vector(-A.y/L , A.x/L); } //直線向量引數方程 P+tv P為點,v為單位向量 (v長度無用) Point GetLineIntersection(Point P, Vector v, Point Q, Vector w)//獲取直線交點 { //呼叫應保證P,Q有交點 : 即 Cross(v,w)!=0 Vector u = P-Q; double t = Cross(w,u) / Cross(v,w); return P+v*t; } //點到直線距離 使用叉積 即平行四邊形的面積除以底 double DisToLine(Point P, Point A, Point B){ Vector v1 = B - A, v2 = P - A; return fabs(Cross(v1,v2)) / Length(v1); //不取絕對值是有向距離 } // 直線 struct Line_v //vector form { //P+t*v; v長度無關 Point P; Vector v; Line_v(Point A,Point B) { v = B-A; P = A; } }; struct Line_n //normal form { //ax+by+c=0 double a,b,c; Line_n(Point x,Point y) { a = y.y - x.y; b = x.x - y.x; c = x.x * y.x - x.x * y.y; } }; double PolygonArea(Point *p, int n)//多邊形有向面積 支援非凸多邊形 { double area = 0; for(int i=1; i<n-1; i++) area+=Cross(p[i]-p[0],p[i+1]-p[0]); return area/2; } int main() { return 0; }