计算几何 部分常用函数模板

时间:2021-05-07 06:16:47

来自《算法竞赛入门经典-训练指南》 刘汝佳/陈峰 清华大学出版社


#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;
}