【几何】-几何基础大模板(更新中)

来源:互联网 发布:c语言中合法的字符常量 编辑:程序博客网 时间:2024/06/14 06:50

四省赛的选拔赛(东京2009)出了一堆几何题。。不会做,从此开始学几何!


以下代码为大白鼠模板,是主要基础部分。

#include <iostream>#include <cstdio>#include <cmath>using namespace std;struct Point{    double x,y;    Point(double x=0,double y=0):x(x),y(y){}    ///构造函数};typedef Point Vector;   ///从程序实现上,Vector只是Point的别名///向量+向量=向量,点+向量=点Vector operator + (Vector A, Vector B) { return Vector(A.x+B.x, A.y+B.y); }///点-点=向量Vector operator - (Point A, Point 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 Point& a,const Point& b){    return a.x<b.x || (a.x == b.x && a.y < b.y);}///用于解决精度问题的三态函数const double eps = 1e-10;int dcmp(double x){    if(fabs(x) < eps) return 0;    else return x < 0 ? -1 : 1;}bool operator == (const Point& a,const Point& b){    return dcmp(a.x-b.x) == 0 && dcmp(a.y-b.y) == 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 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; }int main(){    return 0;}
注:

①-叉乘:

叉乘的结果是两个向量构成三角形面积的两倍,但是是有正负的,上图,Cross(v, w)= - Cross(w, v)。

若Cross(w, v)> 0 ,v 在 w 的左侧

这是重要的性质,可以判断位置关系。结合点乘可以更精确,详见大白鼠!
②-三态函数:

三态函数dcmp 可以结果各种求角或double型数运算带来的精度问题,放心食用即可!

判断两线段是否相交(规范相交即不包括端点相交的情况)

bool SideCross(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(c4)<0;}

判断点是否在凸包中

///只需要判断该店是否在凸包每一条边的左侧即可,以下函数中,凸包至少是一条线段bool pInConvex(Point a, Point* ch, int n)    ///ch指的是一个闭合的凸包多边形,起点多存了一遍(为了构成闭合图形),n的值是凸包顶点数加一{      int i;      if(n==3)  ///如果凸包退化成线段,先特殊除去以下情况,在判断是否在凸包内(即是否在线段上)    {          if(a.x < min(ch[0].x, ch[1].x) || a.x > max(ch[0].x, ch[1].x)) return 0;          if(a.y < min(ch[0].y, ch[1].y) || a.y > max(ch[0].y, ch[1].y)) return 0;      }      for(i=1;i<n;i++)      {          if(Cross( ch[i]-ch[i-1], a-ch[i-1] ) < 0 ) return 0;      }      return 1;  }  



0 0
原创粉丝点击